24

I want to determine whether my js code is running on the node server or on the client, and store it into a variable isServer = true if it is running on the server. How can I do that? Is there a way to simply check for the existence of a property that is only available on the server and, if this is possible, which is the best option?

Thanks for help!

wandarkaf
  • 1,839
  • 20
  • 30
Pascal Bayer
  • 2,615
  • 8
  • 33
  • 51

1 Answers1

36

You could use this:

function is_server() {
   return ! (typeof window != 'undefined' && window.document);
}

As the global window.document object is only present in the browser context.

Nelson
  • 49,283
  • 8
  • 68
  • 81
  • 3
    window.document can be easily injected. – Parv Sharma Nov 30 '12 at 11:30
  • ReferenceError: window is not defined at repl:1:4 at REPLServer.self.eval (repl.js:111:21) at Interface. (repl.js:250:12) at Interface.EventEmitter.emit (events.js:88:17) at Interface._onLine (readline.js:199:10) at Interface._line (readline.js:517:8) at Interface._ttyWrite (readline.js:735:14) at ReadStream.onkeypress (readline.js:98:10) at ReadStream.EventEmitter.emit (events.js:115:20) at emitKey (readline.js:1057:12) – Pascal Bayer Nov 30 '12 at 11:30
  • Seems like i can't check for window at all on the server... I know that the difference between browser and node server is window vs. global. – Pascal Bayer Nov 30 '12 at 11:33
  • @pbcoder Yes there was an error, I needed to prevent bad access with `typeof`, see my updated answer for the fixed version. – Nelson Nov 30 '12 at 11:36
  • Is there any other way because as @ParvSharma stated I can easily inject window = {} and window.document = {} and it is no longer working. – Pascal Bayer Nov 30 '12 at 11:42
  • Globals var in node.js are under a 'global' object http://nodejs.org/api/globals.html#globals_global so if someone created a global window object in node.js it would be `global.window` not `window` as in the browser case. – Nelson Nov 30 '12 at 12:03
  • 1
    @ParvSharma Does checking for `if (this != window) //server` fix the problem of injection? Because `this` should be `global` on node and `window` on the browser right? – Pascal Bayer Dec 02 '12 at 15:29
  • 1
    what about `process`. It is only available in nodejs and `undefined` in browser. – Ravi Nov 04 '17 at 18:24
  • @Ravi in projects using webpack, process can't be used since webpack defines that even when targeting browser – niceman Dec 02 '19 at 12:57
  • Nowadays, you canalso do `globalThis.window !== undefined`, as `globalThis` is now the global object cross-platform. – n1ru4l Apr 11 '22 at 11:37