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.
"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:
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.
