Next.js Discord

Discord Forum

how can I access the window object from within a helper function called via component?

Unanswered
Oak rough bulletgall wasp posted this in #help-forum
Open in Discord
Oak rough bulletgall waspOP
I've got something like:
const myHelper = () => {
  return window.location.origin + '/somewhere';
}

...

return (
  <>
    <Link href={myHelper()}></Link>
  </>
)


but I am getting ReferenceError: window is not defined

I tried passing it to the helper like:
<Link href={myHelper(window)}></Link>


but that made no difference... How can I do this?

10 Replies

1. i think you mean to use onClick instead of Link href, nvm you just using it to get full url (see next point)
2. next/link can work with relative urls starting with/
3. window isnt defined during ssr when its pre renderd on server: https://nextjs-faq.com/browser-api-client-component
Yes, as @riský you just need to do this:

return (
  <>
    <Link href="/somewhere"></Link>
  </>
)
Oak rough bulletgall waspOP
My example was simplified.. My helper function is constructing a complex OKTA url that requires a callback url being constructed with the current window.location.origin to know how to get back to the site after authentication.
So, i can't just do "/somewhere" in the link like that.
As ssr is too fun
Other option is to just hardcode the option for Dev and prod
Black carp
Is the helper required to be done on the server? In the end you do not have the window so you could return a string and then stream it as a prop to this component where you could make it a client component and do your concatenation there?
1. Generate path on server
2. Create client component and pass this path as prop
3. This client component (“use client”) and takes the prop for concatenation and put it in the link?