5

I have a Vue SSR-application and for some components, I need to know whether they run on Node during server-side rendering or whether they run on the browser.

I've set the process env in the Webpack config like

process.env.VUE_ENV === 'server' 

which works. But for various reasons, I need a detection independent of the built environment.

I'd like to check for the browser/node in the created() hook.

How would I do that?

Yashwardhan Pauranik
  • 5,160
  • 5
  • 37
  • 59
LongHike
  • 3,362
  • 3
  • 31
  • 59
  • 1
    You can try to access a browser specific object (like navigator object) within your `created()` hook - and catch the error it throws when trying to access this object on nodejs fails – Mortz Nov 21 '18 at 10:37
  • https://stackoverflow.com/questions/4224606/how-to-check-whether-a-script-is-running-under-node-js – ssc-hrep3 Nov 21 '18 at 10:38

1 Answers1

6

I took the following line -verbatim- from the Vue.js source code ..

const inBrowser = typeof window !== 'undefined';

You can use it to verify if your code is running in the browser.

Husam Ibrahim
  • 6,509
  • 1
  • 14
  • 26