/

Next.js: Running Code on the Server Side or Client Side

Next.js: Running Code on the Server Side or Client Side

Learn how to write code that is executed only on the specific side of your stack: either on the frontend or the backend.

In your page components, you can choose to execute code exclusively on the server-side or the client-side by checking the window property.

The window property exists only in the browser environment. Therefore, you can use the following code to determine if you are on the server-side:

1
2
3
if (typeof window === 'undefined') {
// Server-side code here
}

Similarly, you can use the following code to execute client-side code:

1
2
3
if (typeof window !== 'undefined') {
// Client-side code here
}

It’s important to note that we use the typeof operator because we can’t detect the value of window to be undefined in any other way. If we were to use if (window === undefined), a “window is not defined” runtime error would occur.

Additionally, Next.js optimizes the code during the build process. Any code wrapped in the if (typeof window === 'undefined') {} block is removed from the client-side bundle.

tags: [“Next.js”, “server-side rendering”, “code optimization”]