Antonio
Antonio

Reputation: 70

Next Auth getSession not working in api routes

So basically I use getServerSideProps to call some APIs. when I call getSession in getServerSideProps() I get a valid object.

export async function getServerSideProps({ req }) {
   const session = await getSession({ req }); // works

But when I call it in the API that is called in that getServerSideProps() function, I get null.

import { getSession } from "next-auth/react";

export default async (req, res) => {
  const { db } = await connectToDatabase();

  const session = await getSession({ req }); // returns null

Here is NextAuth documentation for reference:

enter image description here

Upvotes: 5

Views: 12373

Answers (2)

zergcore
zergcore

Reputation: 49

have you tried with

import { getServerSession } from "next-auth/next"
import { authOptions } from './api/auth/[...nextauth]'

...

export async function getServerSideProps({ req, res }) {
  return {
    props: {
      session: await getServerSession(req, res, authOptions)
    }
  }
}

This worked for me when I was having the same problem. You can find more in the docs

Upvotes: 0

lanxion
lanxion

Reputation: 1430

This is very late, but I found the section in the docs where you can get the appropriate session object in API in this section.

  1. Using unstable_getServerSession()
import { unstable_getServerSession } from "next-auth/next"
import { authOptions } from "./api/auth/[...nextauth]"

export default async (req, res) => {
  const session = await unstable_getServerSession(req, res, authOptions)
  if (session) {
    // Signed in
    console.log("Session", JSON.stringify(session, null, 2))
  } else {
    // Not Signed in
    res.status(401)
  }
  res.end()
}
  1. Using getToken()
// This is an example of how to read a JSON Web Token from an API route
import { getToken } from "next-auth/jwt"

export default async (req, res) => {
  // If you don't have NEXTAUTH_SECRET set, you will have to pass your secret as `secret` to `getToken`
  const token = await getToken({ req })
  if (token) {
    // Signed in
    console.log("JSON Web Token", JSON.stringify(token, null, 2))
  } else {
    // Not Signed in
    res.status(401)
  }
  res.end()
}

The most important part is to pass the authOptions that is imported from /api/[...nextauth]

NOTE: getSession is a client API, as in it will only work on getStaticProps

Upvotes: 4

Related Questions