I am implementing NextAuth authentication with google as provider. I am also integrating MongoDB as the DB.
I the api endpoints, I am getting session using getSession
. But the session is coming to be null in the POST methods and works fine with GET requests.
**getDocs.js **
import { getSession } from "next-auth/react"
export default async function handler(req,res){
if(req.method!="GET") res.status(400).json({status:"error",msg:"Cannot fulfil GET API request"})
const session = await getSession({req})
console.log(session) // session is there. Works fine
// further code
}
updateDoc.js
import { getSession } from "next-auth/react"
import connectDB from "../../../lib/dbconnect/dbconnect"
import Document from "../../../lib/models/document"
import clientPromise from "@/lib/mongodb"
connectDB()
export default async function handler(req,res){
console.log(req.body)
if(req.method !== "POST") res.status(400).json({status: "error", msg: "Cannot fulfill GET API request"})
const session = await getSession({req})
console.log(session) // session is null. Works fine
// further code
}
api/auth/[...nextauth].js
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"
import clientPromise from "../../../lib/mongodb"
import { MongoDBAdapter } from "@next-auth/mongodb-adapter"
export const authOptions = {
providers: [
GoogleProvider({
clientId: process.env.NEXTAUTH_GOOGLE_CLIENT_ID,
clientSecret: process.env.NEXTAUTH_GOOGLE_CLIENT_SECRET,
}),
],
pages:{
signIn:'/signin'
},
adapter: MongoDBAdapter(clientPromise),
}
export default NextAuth(authOptions)
I found out it works fine for get request because I tried making a get request to the updateDoc.js after removing the if condition to check the method type, and it works fine.
What should I do?
Found the solution to the question
Use getServerSession instead getSession