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,370
  • 5
  • 42
  • 65
LongHike
  • 4,016
  • 4
  • 37
  • 76
  • 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,999
  • 3
  • 16
  • 28