Search code examples
javascripttypescriptnext.jsnext-auth

[next-auth]: `useSession` must be wrapped in a <SessionProvider />


I keep getting this error. Tried for a few hours now and had no luck, I got a feeling that it's the placement of the _app.tsx that's messing the project up.

[next-auth]: `useSession` must be wrapped in a <SessionProvider />

enter image description here

This is how my file tree looks like

tree folder view

Navbar.tsx

"use client"
import React from 'react'
import Link from 'next/link'
import { NavLinks } from '@/constants'
import { signIn, signOut, useSession } from 'next-auth/react'

const Navbar = () => {
    const { data: session, status } = useSession()
    return (
        <nav className="flex items-center justify-between p-6 lg:px-8" aria-label="Global">
            <div className="hidden lg:flex lg:flex-1 lg:justify-end">
                {status === 'authenticated' ? (
                    <a href="#" onClick={() => signOut()} className="text-sm font-semibold leading-6 text-gray-900">Sign out {session.user?.email}<span aria-hidden="true">&rarr;</span></a>
                ) : (
                    <a href="#" onClick={() => signIn('spotify')} className="text-sm font-semibold leading-6 text-gray-900">Log in <span aria-hidden="true">&rarr;</span></a>
                )}
            </div>
        </nav>
    )
}
export default Navbar

_app.tsx

import { SessionProvider } from "next-auth/react"
import type { AppProps } from "next/app"
import type { Session } from "next-auth"
import "./globals.css"

export default function App({ Component, pageProps: { session, ...pageProps }}: 
  AppProps<{ session: Session }>) {
  return (
    <SessionProvider session={session} refetchInterval={5 * 60}>
      <Component {...pageProps} />
    </SessionProvider>
  )
}

Anyone out there who might know what I'm missing here?


Solution

  • The reason you are getting this error is that you are using app directory which uses App Router a mechanism that allows you to use Server components (This was introduced with Next 13). Inside the app directory _app.tsx will not be called. There are two ways to mitigate this issue

    1. Use the old pages directory and everything should be good
    2. Check whether the next-auth supports Next 13 and implement it accordingly

    Hope this helps!