Home > Software engineering >  NextJS next-auth get session always null
NextJS next-auth get session always null

Time:06-01

Can't get the session data using getSession({req}) on a api call? useSession() on a component is working fine.

package versions: [email protected], [email protected]

issue: api/lists.ts:

import prisma from "../../../lib/prisma";
import { getSession } from "next-auth/react"
    
export default async (req: NextApiRequest, res: NextApiResponse) => {
  
     const session = await getSession({ req });
     console.log('session data is always null', session);

nexuauth.js config file:

callbacks: {
        session: async ({ session, user, token }) => {
            if (session?.user) {
                session.user.id = user.id;
            }
            // console.log('session callback', session);
            return session;
        },
    },
    session: { strategy: "database" },

_app.js file:

function MyApp({ Component, ...pageProps }) {
  return (
    <SessionProvider session={pageProps.session} refetchInterval={5 * 60}>
      <Main>
        <Component {...pageProps} />
      </Main>
    </SessionProvider>
  )
}

export default MyApp

on a login.js file (working fine):

export default function Login() {

    const { data: session } = useSession()

CodePudding user response:

Session depends on cookies, your browser automatically sends the cookies. So useSession(), which is on client side/browser always work. But when you use getSession cookies are not present automatically, we need to set them manually (github issue)-

const response = await fetch(url, {
  headers: {
    cookie: req.headers.cookie || "",
  },
});

To add these automatically you can perhaps plug into interceptors (axios, fetch) or make a wrapper function.

  • Related