Sling Academy
Home/Next.js/How to Detect Server vs Client Environment in Next.js

How to Detect Server vs Client Environment in Next.js

Last updated: January 10, 2023

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!

Next Article: How to Import & Display Local Images in Next.js

Previous Article: Next.js: How to Set Page Title and Meta Description

Series: Fetching and Rendering Data in Next.js

Next.js

Related Articles

You May Also Like

  • Solving Next.js Image Component Error with CSS Classes
  • How to Use MUI (Material UI) in Next.js 14
  • Fixing Data Update Issues in Next.js Production
  • Fixing Next.js Undefined ENV Variables in Production Build
  • Solving Next.js SyntaxError: Unexpected token ‘export’
  • Next.js Error: Found Page Without a React Component as Default Export – How to Fix
  • Fixing Next.js Error: Blank Page on Production Build
  • Fixing Next.js Error when Importing SVGs: A Step-by-Step Guide
  • Next.js Issue: useEffect Hook Running Twice in Client
  • Fixing ‘self’ is not defined error in Next.js when importing client-side libraries
  • How to Dockerize a Next.js App for Production
  • How to set up Next.js with Docker Composer and Nginx
  • Solving Next.js CORS Issues: A Comprehensive Guide
  • Fixing Next.js Hydration Mismatch Error in Simple Ways
  • Next.js Error: Cannot use import statement outside a module
  • Next.js: How to Access Files in the Public Folder
  • Fixing Next.js Import CSS Error: A Simple Guide
  • Fixing LocalStorage Not Defined Error in Next.js
  • Fixing Next.js Error: No HTTP Methods Exported