Next.js window is not defined: Find the Cause, Then Pick the Right Fix
A component marked "use client" is still rendered on the server, which is why window is not defined appears in files that look safe. This guide matches each symptom to its cause and shows which fix worked. Every case was reproduced in a test project on Next.js 16.3.5, on Node.js 24 and 26.
Ali RehmanFreelance Web Developer
On this page 17 sections
The build worked yesterday. Today it stops with ReferenceError: window is not defined, or the page loads and the server’s terminal prints that line on every request. The code is correct in a browser. The trouble is that it also ran somewhere that is not a browser.
"use client". Node.js has no window, document or localStorage, so code that reads them while rendering, or while a file is being imported, fails there. Move the read into useEffect or an event handler. For a package that needs the browser as soon as it is imported, load it with next/dynamic and ssr: false from inside a Client Component. Be careful with typeof window checks in the markup you return: they stop this error and cause a hydration error instead.Every case in this guide comes from a throwaway project that was built 9 times on Next.js 16.3.5 on 18 November 2026, with 51 recorded checks. The same build was also started with Node.js 26, because the newer Node.js releases change two of the error messages. How the test was run, and what it did not cover, is set out at the end. Only the App Router was tested.
First, find where the error is thrown
The same mistake produces different symptoms depending on when Next.js renders the page. Find yours first, because it tells you which file to open.
- During
next build. The build stops with “Error occurred prerendering page”, then the error, then the file and line, and it ends with “Export encountered an error on /page: /, exiting the build.” This happens for pages that are prerendered at build time. - On a request. Pages that are rendered on each request build without complaint. The request then answers with status 500, and the terminal that runs the server prints
⨯ ReferenceError: window is not definedwith adigestnumber. - In development.
next devhas no build step, so the page fails on the request and the error overlay shows the message. - In the browser console only. A message about hydration, or “Minified React error #418” in production, is a different problem with the same root. Go to section 6.
What you see
→ section: most likely cause
Build fails, your own file is named
→ 1 or 2: read during a render
Build fails at module evaluation
→ 3: a package reads window
ssr: false is not allowed
→ 4: used in a Server Component
localStorage is not defined
→ 5: read before the browser
React error #418 in the console
→ 6: typeof window in markup
Cannot read properties of undefined
→ 7 or 8: navigator, or Node.js 26
Works from a link, 500 on reload
→ 9: direct visits use the server
Tested on Next.js 16.3.5.Read the trace before you change anything. When the failing line is in your own component, the output names the file, the line and the column. When a package is responsible, that line starts with at module evaluation, and the fix is a different one.
Why Next.js runs browser code on the server
Next.js has two kinds of components. Server Components run only on the server. Client Components, the ones in files that start with "use client", run in the browser, and that is where the name misleads: on a direct visit they are rendered on the server too. The Server and Client Components page says Client Components and the RSC Payload are used to prerender HTML. The boundary guide puts it in one sentence: on a direct visit, a Client Component “renders on the server and again in the browser during hydration”.
That first render happens in Node.js, where the browser’s objects do not exist. In the test, a Server Component on Node.js 24 saw window, document, location, localStorage and sessionStorage as undefined. Any code that touches one of them during that render throws.
Three places are safe, because they only ever run in the browser: the function you pass to useEffect, event handlers such as onClick, and a component loaded with ssr: false. Everything else in a component file can run on the server: the body of the component, the initial value passed to useState, and any code at the top of the file, which runs when the file is imported.
This is the main practical difference from a React app that renders only in the browser, where the same code never meets a server. The comparison of Next.js and plain React covers what that server render buys you.

1. A Server Component reads window
Pages and layouts are Server Components unless the file starts with "use client". A page that put window.innerWidth straight into its markup stopped the test build. The output, shortened:
Error occurred prerendering page "/".
ReferenceError: window is not defined
Export encountered an error on /page: /,
exiting the build.The first line links to a Next.js page about prerender errors, which lists “Using browser-only APIs in components without proper checks” among the causes.
The same code behaves differently on a page that is rendered on each request. The test page called connection(), which makes Next.js wait for a request; a page that reads cookies or headers is in the same group. That build passed. Each request answered 500, and the browser showed Next.js’s error page, “This page couldn’t load”, with an error number. The number matched the digest printed next to the error in the server’s terminal. That is how you find the real message when a visitor sends you a screenshot.
The fix is to move the browser code out of the Server Component. Put it in its own file that starts with "use client", then follow the next section, because the directive on its own is not enough.
2. A Client Component reads window while rendering
This is the case that surprises people. The component is marked "use client", the error says the server ran it, and both are true. In the test, a Client Component that read window.innerWidth in the markup it returned failed the build with the same prerender error as the Server Component. The code frame in the output showed "use client"; on line 1 and the failing read on line 3.
Reading the value in useEffect fixes it:
"use client";
import { useEffect, useState } from "react";
export default function Width() {
const [width, setWidth] =
useState<number | null>(null);
useEffect(() => {
setWidth(window.innerWidth);
}, []);
return <p>{width ?? "Measuring"}</p>;
}With that version the HTML sent by the server contained the placeholder, the browser replaced it with the real value after loading, and React reported no error. The visitor does see the placeholder for a moment, so give it the same size as the final content.
Event handlers need nothing. A button whose onClick read window.innerWidth worked without any check, because a click can only happen in a browser.
3. A package reads window when it is imported
Map, chart and editor packages often touch window or document at the top of their files. That code runs when the file is imported, before any of your component code, so no check inside your component can prevent it. The test used a small stand-in module whose first line reads window.innerWidth, not a real package. Importing it from a Client Component failed the build, and the trace said where: at module evaluation, followed by the module’s file name.
That phrase is the thing to look for. If the trace says module evaluation or points into node_modules, the import is the problem, and there are two ways to keep it off the server.
Load the component with ssr: false. The lazy loading guide gives this option as the way to disable prerendering for a Client Component.
// components/map-loader.tsx
"use client";
import dynamic from "next/dynamic";
const Map = dynamic(() => import("./map"), {
ssr: false,
loading: () => <p>Loading map…</p>,
});
export default function MapLoader() {
return <Map />;
}In the test, the server’s HTML contained only the loading text, and the browser then showed the component with no React error. Remember what that means for anything other than a visitor’s browser: whatever the component displays is not in the HTML. Keep the option for parts that do not have to be in the first response, such as a map or an editor. The Next.js performance guide has more on what to load late.
Import the package inside useEffect. When you need a function from the package and not a whole component, a dynamic import() in an effect keeps the module out of the server render. This worked in the test as well. The package name below is a placeholder.
useEffect(() => {
import("some-map-library").then((library) => {
library.draw(ref.current);
});
}, []);4. ssr: false is not allowed in a Server Component
Many tutorials put the dynamic() call from the last section directly in app/page.tsx. A page is a Server Component, and in the test that build stopped during compilation, before any page was rendered:
`ssr: false` is not allowed with
`next/dynamic` in Server Components.
Please move it into a Client Component.The lazy loading guide documents the same rule. The fix is the wrapper file shown above: a small Client Component that owns the dynamic() call, which the page then imports like any other component. Marking the page itself with "use client" would also satisfy the rule, but it turns the page and everything it imports into client code, so the wrapper is the smaller change.
5. localStorage is not defined
Storage errors usually come from the initial value of a state. This line looks harmless, and it stopped the test build with ReferenceError: localStorage is not defined:
const [theme, setTheme] = useState(
localStorage.getItem("theme") ?? "light",
);The initial value is calculated during the first render, and the first render is on the server. The other browser objects fail the same way under their own names. On pages rendered per request, the test recorded document is not defined, sessionStorage is not defined and location is not defined, each with status 500.
The simple fix is to start with a default and read storage in useEffect, exactly like the width example. In the test the server sent the default, the browser switched to the stored value, and React reported nothing.
React also has a hook made for this, useSyncExternalStore. Its third argument is the value to use on the server, which is what makes it safe:
"use client";
import { useSyncExternalStore } from "react";
function subscribe(onChange: () => void) {
window.addEventListener("storage", onChange);
return () =>
window.removeEventListener(
"storage",
onChange,
);
}
export function useTheme() {
return useSyncExternalStore(
subscribe,
() => localStorage.getItem("theme") ?? "light",
() => "light", // used on the server
);
}With dark saved in the browser, this version showed the saved value and produced no error. One limit to know: the storage event fires when another document changes the storage, so a change made in the same tab needs its own notification.
Both fixes show the default first and the saved value a moment later. If that flash matters, as it does for a dark theme, Next.js has a guide to preventing flash before hydration with a small inline script. The alternative is to keep the preference in a cookie, which the server can read with the cookies function. That makes the page render on each request, and the flash guide warns that reading a cookie in the root layout takes the whole app out of static prerendering.
6. The typeof window check that causes a hydration error
The most common advice for this error is to wrap the code in if (typeof window !== "undefined"). It does stop the error. Whether it is a fix depends on where the check sits.
Inside a function that only runs in the browser anyway, or in a helper that returns nothing visible, the check is harmless. Inside the markup a component returns, it makes the server and the browser produce different output. The test rendered one sentence on the server and another in the browser this way. The build passed, the page loaded, and the browser console showed “Minified React error #418”. React’s page for that error gives a server/client branch written with exactly this check as its first cause, and the Next.js hydration error page lists it too. The React message also says what happens next: the tree is regenerated on the client. The visitor ended up with the right text, after React had thrown the server’s version away.

The storage version of the same mistake is harder to catch:
const [theme] = useState(() =>
typeof window !== "undefined"
? localStorage.getItem("theme") ?? "light"
: "light",
);With nothing saved, the server and the browser both produced the default and there was no error. With dark saved, the same page reported error 418. Code like this passes every check on a fresh browser profile and fails for returning visitors. A server-only environment variable read in a Client Component produces the same error number for a related reason, which the environment variables guide covers.
suppressHydrationWarning is not the way out either. In the test it removed the error, and the text from the server stayed on screen: the browser’s own value never appeared. The React documentation calls the attribute an escape hatch that only works one level deep. It is meant for content that is expected to differ, such as a timestamp, and the Next.js flash guide states the rule in three words: the DOM wins.
7. navigator exists on the server
Guides often list navigator next to window as something the server lacks. On current Node.js that is no longer true. The Node.js globals documentation lists a navigator object added in version 21, and in the test it was an object on both Node.js 24 and 26. Its userAgent starts with Node.js.
Two things follow. A typeof navigator !== "undefined" check passes on the server. A test component that used it to choose its text was prerendered with the Node.js branch, and the browser then reported error 418. And the parts of navigator that pages actually use are missing: geolocation, clipboard and onLine were all undefined. Reading navigator.clipboard.readText during a render did not say that navigator is not defined. It said TypeError: Cannot read properties of undefined (reading 'readText').
So treat navigator like window: use it in useEffect or in an event handler. The message navigator is not defined belongs to Node.js 20 and older, which this test did not run.
8. Node.js 26 changes the storage errors
Node.js 26 became the long-term support line in October 2026, according to the Node.js release schedule, and it treats web storage differently from Node.js 24. The test started the same build with Node.js 26.13.1 and recorded three differences.
sessionStorageexists on the server. The page that failed withsessionStorage is not definedon Node.js 24 answered 200 on Node.js 26 and rendered the default value. With a value saved in the browser’s session storage, that page then reported error 418. The crash had turned into a hydration error.localStoragefails with a different message. Without the--localstorage-fileoption,localStoragewas undefined, and Node.js printed “localStorage is not available because --localstorage-file was not provided.” An unguarded read failed withTypeError: Cannot read properties of undefined (reading 'getItem'), both in the build and on a request.- A
typeof localStoragecheck still worked. The guarded component rendered its default on both Node.js versions.
The Node.js documentation describes a different history. It says version 25 returned an empty object for localStorage when that option was missing, and that version 26 throws an exception. An empty object would explain the reports of localStorage.getItem is not a function from projects on Node.js 25, a release line that ended in June 2026 and was not part of this test. On 26.13.1 nothing was thrown in the test; the value was undefined.
Do not treat the server’s storage as a place to keep anything. The same documentation says server-side localStorage is not stored per user or per request and is shared across all users and requests. The practical rule does not change with the Node.js version: read storage in useEffect or through useSyncExternalStore, and build with the Node.js version you deploy on, so that the message you see locally is the one production would give.
9. It works from a link and fails on reload
Client Components are only rendered on the server for a direct visit. When a visitor arrives through a link inside the app, the Server and Client Components page says they are “rendered entirely on the client, without the server-rendered HTML”. A component that reads window while rendering therefore works when you click your way to it and fails when you reload.
The test showed how well this can hide. In development, the page worked after a click; after a reload the request answered 500 and the overlay showed window is not defined. In a production build of a page rendered per request, the click worked and the server logged nothing. The reload answered 500 and logged the error, and the browser still displayed the working page, because React rendered it in the browser after the server had failed. The response itself was an error document that did not contain the page’s text.
A visitor may never notice that. A crawler, a link preview or an uptime check receives a 500 with no content. A Suspense boundary around the component changes the picture again: the response was 200 with the fallback in the HTML, the server still logged the error, and the browser console showed React error 419, which ends with “Switched to client rendering”. On a page prerendered at build time, the boundary did not help: the build failed as before.
If your server log contains window is not defined while the site appears to work, this is why. Find the address from the request that logged it and reload that address directly.
Which fix to use
- A value you need after the page has loaded, such as a width, a scroll position or a media query: read it in
useEffect. - A saved preference shown in the interface:
useSyncExternalStorewith a server value, oruseEffect. Use a cookie when the server has to know the value. - A component from a package that needs the browser:
next/dynamicwithssr: false, called inside a Client Component. - A package you only need after an action:
import()inside the handler or the effect. - Code in an event handler: no change.
For modules that must never be imported by server code, the client-only package turns a late runtime error into an early, readable one. In the test, a module that started with import "client-only" and was imported by a Server Component stopped the build with a message that client-only cannot be imported from a Server Component module, followed by an import trace that named both files. It marks the mistake. It does not stop a Client Component from being rendered on the server, so the fixes above are still needed. The Server and Client Components page notes that installing the package is optional in Next.js.
Fixes that create new problems
- Adding
"use client"and stopping there. The directive does not move the first render to the browser. The build failed with it in place. - Wrapping a whole page in
ssr: false. The error goes away and so does the page’s HTML. In the test the server sent only the loading text. - A
typeof windowcheck in returned markup. It replaces a build error with React error 418 in the visitor’s browser. suppressHydrationWarningon the mismatch. The error disappears and the server’s text stays.- A Suspense boundary to make the 500 go away. On a page rendered per request it turned the 500 into a 200 with a fallback, and the server kept logging the error.
- Defining a fake
windowon the server. Packages that test forwindowto detect a browser will then take the browser path on the server. This was not part of the test; the reasoning follows from how thenavigatorcheck behaved in section 7. - Changing the Node.js version until the message goes away. The unguarded read is still there, and section 8 shows it coming back under another name.
Check the fix on a production build
- 1Run
next buildwith the Node.js version you deploy on. It should finish without “Error occurred prerendering page”. - 2Start it with
next startand request the page directly, not through a link. The status should be 200. - 3Look at the HTML of that response. It should contain the page’s real text or your placeholder, not an error document.
- 4Watch the server’s terminal while you reload. No line should start with
⨯. - 5Open the browser console on the production build. There should be no React error 418 or 419.
- 6Repeat the reload with a value saved in
localStoragethat differs from your default.
# Status of a direct request
curl -s -o /dev/null -w "%{http_code}\n" \
https://example.com/dashboard
# Expect: 200When to bring in a developer
Most single cases take minutes once you know which of the nine it is. It becomes real work when the error comes from a package you cannot change, when it appears only on the host and not on your machine, when a design depends on browser-only values across many components, or when the server log shows 500s on pages that seem fine and you need to know what search engines receive. Those cases usually involve the hosting setup and the Node.js version as well as the code.
Have these ready for the person who investigates: the Next.js and Node.js versions, the complete error with its trace, where it shows up (build, request or browser) and the component the trace names. This is work I do as part of my Next.js development service; send the details through the contact page. If you are choosing a developer instead, start with the questions in how to hire a Next.js developer.
Frequently asked questions
Why do I get window is not defined in a file with use client?
Because "use client" does not mean browser-only. On a direct visit a Client Component is rendered on the server first and then again in the browser. Code in the component body, in a useState initial value or at the top of the file runs in both places. Move browser reads into useEffect or an event handler.
Is a typeof window check a safe fix?
It is safe in code that produces no visible output on the server, such as a helper called from an effect. In markup that a component returns it caused React error 418 in the test, because the server and the browser rendered different text.
Can I use ssr: false in page.tsx?
Not directly. A page is a Server Component, and the build fails with a message that ssr: false is not allowed with next/dynamic in Server Components. Put the dynamic() call in a small Client Component and render that from the page.
Why does the error only appear when I refresh the page?
A reload is a direct visit, so the server renders the Client Components. Arriving through a link renders them only in the browser, where window exists. Test every fix with a reload.
Why did the localStorage error change after a Node.js upgrade?
Newer Node.js versions define web storage globals. In the test, Node.js 24 gave localStorage is not defined and Node.js 26.13.1 gave a TypeError about getItem, while sessionStorage existed on the server. The cause is the same unguarded read, and so is the fix.
Does ssr: false hide content from search engines?
It keeps that component out of the HTML the server sends. In the test the response contained only the loading text. Whether a particular crawler runs the JavaScript afterwards was not tested, so do not use it for content that has to be in the first response.
Sources, test and review scope
Where this guide attributes a rule to documentation, it comes from one of these pages: Next.js on Server and Client Components, the server and client boundary, lazy loading, preventing flash before hydration and the cookies function; the two Next.js message pages for prerender and hydration errors; the React reference for useSyncExternalStore and hydrateRoot; React’s pages for errors 418 and 419; the Node.js 26 globals documentation; the Node.js release schedule; and MDN’s page on the storage event. Each was read on 18 November 2026. Error messages in quotation marks or code type are copied from the test’s own output.
A fresh App Router project was created for the test. Versions: Next.js 16.3.5, React 19.2.4, Turbopack as the bundler and Node.js 24.12. It was built 9 times: one build per failing case, one of them with Node.js 26.13.1, and one main build with twenty test pages. That main build was then served three ways: with Node.js 24, with Node.js 26.13.1 downloaded from nodejs.org and checked against its published checksum, and in development. Server output was read from the HTML of a plain request, server messages from the server’s terminal, and browser results from Microsoft Edge after the page had hydrated. The run recorded 26 steps and 51 expectations, and every expectation matched. Among them:
- 1A Server Component and a Client Component that read
windowwhile rendering both failed the build of a prerendered page. A Suspense boundary did not change that. - 2On pages rendered per request the build passed and the request answered 500. For the Server Component the browser showed an error page; for the Client Component it still showed the working page.
- 3A module that reads
windowwhen imported failed the build at module evaluation. Loading it withssr: falsefrom a Client Component, or withimport()in an effect, worked. - 4
ssr: falsein a Server Component and aclient-onlymodule imported by a Server Component each stopped the build with their own message. - 5Reads in
useEffectand throughuseSyncExternalStoreproduced no React error, with or without a saved value. - 6A
typeof windowcheck in returned markup, atypeof navigatorcheck and a guarded storage read in a state’s initial value each produced React error 418 when the browser’s value differed from the server’s. - 7
suppressHydrationWarningremoved the error and left the server’s text on screen. - 8On Node.js 26.13.1,
sessionStorageexisted on the server, and an unguardedlocalStorageread failed with a TypeError instead of a ReferenceError.
Limits: everything ran on one Windows computer using the Node.js server that ships with Next.js. Hosting platforms such as Vercel, Docker, the Edge runtime, the Pages Router, webpack builds, Next.js versions before 16, Node.js versions other than 24.12 and 26.13.1, and real map, chart or editor packages were not tested. Every component in the project was a small synthetic example. AI tools assisted with the research and the test runs for this guide, and I compared the results with the linked sources before it was published.
Written by
Ali Rehman - Freelance Web Developer
I work on WordPress websites, practical fixes and scoped web applications. Read my background and skill scope, or send a project brief to discuss a written plan and quote - start here.
More articles by Ali Rehman →