Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next-Auth: getSession returns null

API request for the below code through a browser works fine i.e. returns {"success":true,"data":{"user": ...}} but using cURL or REST-Client VS Code extension return null i.e. {"success":true,"data":null}. Below is the code where I return the session object through /api/query endpoint:

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

export default async (req, res) => {
  const session = await getSession({ req });
  res.status(200).json({ success: true, data: session });
};

I tried getting the session using the endpoint /api/auth/session too. The endpoint returns the session using the browser but returns null using cURL. Here is the cURL request curl http://localhost:3000/api/auth/session.
What's the reason for the behavior?

P.S. : I am using Google OAuth for authentication.

like image 498
falcon lover Avatar asked May 20 '26 03:05

falcon lover


2 Answers

Auth depends on cookies, your browser automatically sends the cookies. But when you use cURL cookies are not present, hence auth cannot authenticate. Next-Auth cookies

like image 195
Ivan V. Avatar answered May 22 '26 20:05

Ivan V.


In next-auth v4, getting the clients session in a Middleware is currently not supported. You can use the built in Middleware methods (which will eventually hit the getToken method) - or use getToken yourself.

I myself feel that this should be highlighted more in the documentation.

Source: This reddit post with an approved comment from lrobinson, VP of Developer Experience @ Vercel

like image 29
Tanckom Avatar answered May 22 '26 20:05

Tanckom