Next.js Discord

Discord Forum

"window" is not defined when rendering client component

Answered
Transvaal lion posted this in #help-forum
Open in Discord
Transvaal lionOP
Even though this component is marked with "use client", I get an error when trying to log the window object.

"use client";

export default function App() {
    console.log(window);

    return <div>my app</div>;
}


The error:
ReferenceError: window is not defined
    at window (app\page.tsx:4:16)
  2 |
  3 | export default function App() {
> 4 |     console.log(window);
    |                ^
  5 |
  6 |     return <div>my app</div>;
  7 | } {
  digest: '1400661120'
}


It does get successfully logged to the console, but this error still shows up. Why?
Answered by B33fb0n3
when you add 'use client' on top, it will be still rendered on the serverside (SSR) and only hydrated on the client. On server there is no window and like that the error is thrown. Either remove the function, add it to a use effect or skip SSR loading (maybe there are other options as well. We come back to them when needed)
View full answer

2 Replies

Answer