Home > Software design >  How to access window object within _app.tsx in Nextjs
How to access window object within _app.tsx in Nextjs

Time:12-25

I am using NextJS/React framework for my application, and currently implementing Auth0. Since I need to handle the multiple path (localhost & actual address), I want to access window object like so.

_app.tsx

function MyApp({ Component, pageProps }: AppProps) {

  return (
    <Auth0Provider
      domain={process.env.AUTH0_DOMAIN ?? ''}
      clientId={process.env.AUTH0_CLIENT_ID ?? ''}
      redirectUri={getAuth0RedirectURL()}
    >
      <Component {...pageProps} />
    </Auth0Provider>
  )
}

In my getAuth0RedirectURL function, I simply trying to access window object and handle if the current environment is dev or production.

export const getAuth0RedirectURL = (): string => {
  const url = new URL(window.location.origin) // here, I got error because window is not defined
  url.pathname = process.env.AUTH0_PATH

  return url.toString()
}

I do think the current code does not work ( window is undefined ) because it doesn't handle client-side so no window object yet appears.

I am not sure how I can correctly access the window object in _app.tsx so I can securely access window.location.origin path?

CodePudding user response:

You are right in saying that the code does not work because window is a browser object while you are trying to access window on the server, hence you are getting undefined.

  1. What you can do is use an if statement to check if window is undefined or not.
if (typeof window === "undefined") return null;
return (
  <Auth0Provider
    domain={process.env.AUTH0_DOMAIN ?? ''}
    clientId={process.env.AUTH0_CLIENT_ID ?? ''}
    redirectUri={getAuth0RedirectURL()}
  >
    <Component {...pageProps} />
  </Auth0Provider>
)
  1. Another way to achieve this would be to use dynamic imports which is provided by NextJS.
import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(() => import('../components/List'), {
  ssr: false
})

export default () => <DynamicComponentWithNoSSR />
  1. Alternatively, and this is my recommendation as well, you can find the recommended solution by the Auth0 team which is to not use their SPA SDK but instead do authentication server-side. Which is the NextJS way of doing things to.

CodePudding user response:

@Ansh's answer is right.

But why not using node env directly?

redirectUri={process.env.AUTH0_PATH}

If you need to check current environment:

process.env.NODE_ENV

In case, you still want to access window, you can use:

global?.window && window.location.origin
  • Related