Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

364
Views
Context in nextjs is undefined (0 , react__WEBPACK_IMPORTED_MODULE_0__.useContext)

I am creating an authentication for every route and I wanted to have the value of the user available in every route, that's why I used context.

I made a layout component which I import in the app right after the context like this:

function MyApp({ Component, pageProps }) {
  const router = useRouter()
  useEffect(() => {
    if (router.pathname == '/' || router.pathname == '/_error') {
      router.push('/login')
    }
  }, [])
  return (
    <AuthProvider>
      <Layout>
        <Component {...pageProps} />
      </Layout>
    </AuthProvider>
  )
}

export default MyApp

Here's my layout component:

const Layout = ({ children }) => {
  const {loggedInUser} = useContext(AuthContext)
  const router = useRouter()
  useEffect(() => {
    if (router.pathname == '/' || router.pathname == '/_error') {
      ...
    }
  }, [])

  return <div>{children}</div>
}

export default Layout

Here's my context:

export const AuthContext = React.createContext()

function AuthProvider(props) {
  const [loggedInUser, setUserLoggedIn] = useState()

  useEffect(() => {
    onAuthStateChanged(auth, (currentUser) => {
      if (!currentUser) {
        setUserLoggedIn(currentUser)
      } else {
      }
    })
  }, [])

  return <AuthContext.Provider value={{
    loggedInUser,
    setUserLoggedIn
  }}>{props.children}</AuthContext.Provider>
}

export default AuthProvider

When I try to enter a route I get this error TypeError: Cannot destructure property 'loggedInUser' of '(0 , react__WEBPACK_IMPORTED_MODULE_0__.useContext)(...)' as it is undefined.

I hope you can help me!

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!