How to Detect Server vs Client Environment in Next.js

Updated: January 10, 2023 By: Goodman Post a comment

In Next.js, you can programmatically detect between the server environment and the client environment by checking whether the window object exists or not, like this:

const isServer = typeof window === 'undefined';
if(isServer){
  // do your server stuff here
} else {
  // do your client stuff here
}

Because the window object is only available when your code is running on the client side, typeof window === ‘undefined’ will always return true on the server side and return false on browsers.

Alternative

If you want a piece of code to run only on the client side, you can use the useEffect hook.

If you want to ensure some code will only run on the server side, you can use the getServerSideProps or getStaticProps functions.

Here’s a tiny example:

// pages/index.js
import { useEffect } from 'react';

export default function Home() {
  useEffect(() => {
    // This will run on the client only
  }, []);

  return <div>Sling Academy</div>;
}

export function getServerSideProps() {
  // This will run on the server only
  // Secret and sensitive things can be done here
}

That’s it. Happy coding!