ReferenceError: localStorage is not defined during server rendering
ReferenceError: localStorage is not definedShort answer
Client components in Next.js are also rendered once on the server, where there is no browser storage. Code that touches localStorage while rendering fails there. Read it inside useEffect or an event handler, which run only in the browser, and render a fallback until the value is loaded.
Fix it fast
1Find out which cause you have
Find the line that reads localStorage and check whether it runs while the component renders (top level, in useState's initial value, or in the body).
grep -rn "localStorage" app/ src/ components/2Match what you see, then jump to its fix
- 1
The error appears in the terminal running next dev or next build, not in the browser console.localStorage is read while rendering, and the render runs on the serverFix - 2
The page flashes or logs a hydration mismatch after you read the stored value directly in state.The first render differs between server and browser (hydration warning after the fix)Fix - 3
The error is a DOMException rather than a ReferenceError, on a recent Node.js version.Node.js 26 and later throw instead of leaving localStorage undefinedFix
- 1
What does the error look like?
ReferenceError: localStorage is not definedDOMException when reading localStorage on Node.js 26 and later
Cause 1 of 3
localStorage is read while rendering, and the render runs on the server
1Check
Next.js documents that Client Components are prerendered on the server for the first load. The browser-only APIs (such as localStorage and window) therefore do not exist during that pass.
grep -rn "useState(.*localStorage\|^const .*= localStorage" app/ src/2Fix
Move the read into an effect. React's reference says effects do not run during server rendering, so the code runs only in the browser.
'use client';
import { useEffect, useState } from 'react';
export default function Theme() {
const [theme, setTheme] = useState('light');
useEffect(() => {
setTheme(localStorage.getItem('theme') ?? 'light');
}, []);
return <p>Theme: {theme}</p>;
}3Verify
Run the production build; no prerender error.
npm run buildConfirmed by nextjs.org
Cause 2 of 3
The first render differs between server and browser (hydration warning after the fix)
1Check
The server renders without the stored value, so the first browser render must match it. React's docs recommend an initial render that matches the server, then a switch after an effect sets a flag.
npm run dev2Fix
Start with the same fallback the server used, and update it in an effect (as in the code above), instead of reading storage in the initial state.
const [didMount, setDidMount] = useState(false);
useEffect(() => setDidMount(true), []);
if (!didMount) return <p>Loading</p>;3Verify
No hydration warning in the console.
npm run devConfirmed by react.dev
Cause 3 of 3
Node.js 26 and later throw instead of leaving localStorage undefined
1Check
The Node.js docs list localStorage as a global from v22.4, and from v26 reading it without the --localstorage-file flag throws a DOMException. Code that guards with typeof localStorage can therefore behave differently across Node.js versions.
node --version2Fix
Do not touch localStorage on the server at all. Keep every access inside an effect or event handler, which only run in the browser.
useEffect(() => {
localStorage.setItem('theme', theme);
}, [theme]);3Verify
The build passes on your Node.js version.
npm run buildConfirmed by nodejs.org
How do I stop it coming back?
- Treat localStorage, window and navigator as browser-only: use them in effects and event handlers.
- Wrap storage access in one small hook so the rule lives in one place.
- Pin the Node.js version in .nvmrc so builds behave the same everywhere.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- WorkforceA field app, an admin console and a self-hosted Node.js server for push and reconciliation.
Related fixes
Web apps
Reading localStorage inside an iframe throws a SecurityError
Uncaught DOMException: Failed to read the 'localStorage' property from 'Window'
localStorage throws a SecurityError when the document has no usable origin or the browser blocks storage for it.
4 causes, each with a fixWeb apps
Upgrading to Next.js 16: middleware becomes proxy, and the other things that break
Missing Required default.js for Parallel Route
Next.js 16 renames middleware.ts to proxy.ts and its exported function to proxy.
6 causes, each with a fixWeb apps
Warning: Extra attributes from the server in the console
Text content does not match server-rendered HTML
React found attributes on an element in the server HTML that its own render did not produce.
3 causes, each with a fixWeb apps
Next.js stops with 'document is not defined' while it renders on the server
ReferenceError: document is not defined
Next.js renders your components on the server first, where there is no document.
3 causes, each with a fixWeb apps
A custom error from the server arrives at the client as a generic message
error.digest holds a hash instead of your message
Next.js hides the message of errors thrown in Server Components in production, to avoid leaking details.
3 causes, each with a fixWeb apps
useState fails in a child component in the Next.js App Router
React client hook in Server Component
In the App Router every component is a Server Component unless a file above it is marked otherwise, and Server Components cannot use state or effects.
3 causes, each with a fix