Next.js Discord

Discord Forum

"window" is not defined

Unanswered
Masai Lion posted this in #help-forum
Open in Discord
Masai LionOP
code :

via dymanic didn't work either
import dynamic from "next/dynamic";

export default async function Home() {
    const Dash = dynamic(() => (
        <h1>welcome, {window.client.getUser().username}</h1>
    ), {ssr: false})
    return <Dash/>
}

nor conditional rendering works
export default async function Home() {
    if (typeof window !== "undefined") {
        return <h1>welcome, {window.client.getUser().username}</h1>
    }
}

14 Replies

// welcome.tsx
export default function Welcome() {
  return  <h1>welcome, {window.client.getUser().username}</h1>
}

// page.tsx
import dynamic from "next/dynamic";

const Dash = dynamic(() => import("./welcome"), {ssr: false})

export default async function Home() {
    return <Dash/>
}
you should do this
Original message was deleted
Masai LionOP
&752637460550385834 seems like there isn't slash command named "Mark Solution" as given in the replied post
you need to right click the message and use the dropdown, it's in Apps and Mark Solution (probably last option)
Given that you control the code next/dynamic is probably not suited
reposting here what I've posted 2 posts below because someone had a similar question ^^
Detailed answer on stack overflow: https://stackoverflow.com/a/77556387/5513532
What you need here is a "useClient" hook to check if the component is mounted
and then only you can use "window" during render
next/dynamic is to be used when the component is really big, or involve a pure JS lib that can't support SSR like leaflet or jquery
for other use case you'd want to favour using React logic