How to check is Server or Client in Nodejs?

When you create an app with Nodejs, sometime you'd like to check a component is running on Client or Server to handle the logic code. The short piece of code bellow may help you handle this.

Create a helper isServer

const isServer = !(
  typeof window !== 'undefined' &&
  window.document &&
  window.document.createElement
);


Explanation:

In the helper, we use the window object to check, if is Server, the type of the window will be undefined and the window properties is undefined also.

usage:

if(isServer){
	// server logic handle
}else{
	// client logic handle
}


© 2019 4codev

Created with love by Sil.