---
title: "How do you fix \"window is not defined\" in Next.js?"
description: "Next.js renders components on the server where window does not exist. Read window in useEffect, guard with typeof, or load the component client-side only."
url: "https://bugsee.com/answers/nextjs/window-is-not-defined/"
---

# How do you fix "window is not defined" in Next.js?

Code that runs on the server has no `window`. Access it inside `useEffect` or an event handler, or load the component with `next/dynamic` and `ssr: false`.

Server rendering runs in Node.js, where `window`, `document` and `localStorage` are not defined. Any top-level code or render code that touches them throws.

```tsx
"use client";
import { useEffect, useState } from "react";

export function Width() {
  const [w, setW] = useState<number | null>(null);
  useEffect(() => setW(window.innerWidth), []); // browser only
  return <span>{w ?? "…"}</span>;
}
```

If a third-party library touches `window` while it is being imported, load the whole component only in the browser:

```tsx
import dynamic from "next/dynamic";

const Chart = dynamic(() => import("../components/chart"), { ssr: false });
```

In the App Router, `ssr: false` has to be used from a Client Component.

## Related questions

- [How do you fix a hydration error in Next.js?](https://bugsee.com/answers/nextjs/fix-hydration-error/)
