How to access the current user session data through api routes using NextJS

Viewed 197

I'm trying to access data from the current user session after user authentication in a file inside the Api routes from NextJS, but in the console.log(session.user.email) returns null even after the authentication. Does someone know how to do it?

import { NextApiRequest, NextApiResponse } from "next";
import connectDb from "../../services/mongo";
import connectToDatabase from "../../services/mongo";
import {getSession} from 'next-auth/client'

connectToDatabase();

export default async (
  req: NextApiRequest,
  res: NextApiResponse
): Promise<void> => {
  const { db } = await connectDb();

  switch (req.method) {
    case "GET":
      try {
        const session = await getSession()
        console.log(session.user.email)
        const favorites = await db.collection("users").findOne({  email: session.user.email})
        res.status(200).json({ favorites });
      } catch (error) {
        console.log(error);
      }
      break;
    default:
  }
};
0 Answers
Related