How to access the Window and Document object in Next.js 15?

How to access the Window and Document object in Next.js 15?

Short Next.js 15 Tutorial

To Fix The Error “window is not defined” in Next.Js 15

Most of the time, we didn’t need to access the window objects in Nextjs 15. We access Windows and Document objects in nextjs for rare or exceptional cases.

First of all, you cannot access the window in Server-Side Rendering (SSR); you can only access the window and document object inside the client side.

You must use the useEffect hook and use client directive for the access window and document object in Nextjs 15.

// app/page.tsx
export function Client() {
const [_window, setWindowObject] = useState<Window & typeof globalThis | null>(null);
const [_document, setDocumentObject] = useState<Document | null>(null);
useEffect(() => {
const _window = window;
const _document = document;
if (_document && _window) {
setWindowObject(_window);
setDocumentObject(_document);
}
}

After, with the help of useState, we can use the window and document object in jsx.

I selected the header in the first example and changed the background and text colour. In the second example, I add the onClick event on the button element and show an…

Leave a Reply