getServerSession Is Always Null #7062
-
EnvironmentSystem: Reproduction URLhttps://github.com/Apestein/dev-clubhouse/tree/bug-branch Describe the issuegetServerSession always return null. Furthermore, it will logout if I refresh the page while logged in. And while getServerSession does not work, getSession does work as expect and session is returned. I'm not 100% sure this is a bug or if I'm missing something extremely obvious, but as I followed the docs I'm not sure what I did wrong if any. import { NextApiRequest, NextApiResponse } from "next"
import dbConnect from "lib/dbConnect"
import Message from "@/models/Message"
import { authOptions } from "pages/api/auth/[...nextauth]"
import { getServerSession } from "next-auth/next"
import { getSession } from "next-auth/react"
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
await dbConnect()
// const session = await getSession({ req })
const session = await getServerSession(req, res, authOptions)
console.log(session)
const { method } = req
switch (method) {
case "GET":
try {
// const messages = session
// ? await Message.find({}, { __v: 0 })
// : await Message.find({}, { __v: 0, author: 0 })
const messages = await Message.find({}, { __v: 0 })
res.status(200).json(messages)
} catch (error) {
res.status(400).json({ success: false })
}
break
case "POST":
try {
const message = await Message.create(req.body)
res.status(201).json(message)
} catch (error) {
res.status(400).json({ success: false })
}
break
case "PUT":
try {
const { _id, update } = req.body
const message = await Message.updateOne(
{ _id: _id },
{ $set: { content: update } }
)
res.status(200).json({ success: message })
} catch (error) {
res.status(400).json({ success: false })
}
break
case "DELETE":
try {
const id = req.body._id
const message = await Message.deleteOne({ _id: id })
res.status(200).json({ success: message })
} catch (error) {
res.status(400).json({ success: false })
}
break
default:
res.status(400).json({ success: false })
}
} How to reproduce
Update: I managed to fix it somehow but I don't know why. The bug is now in the bug-branch, and the main branch is now fixed and works. Expected behaviorreturn the logged in user session |
Beta Was this translation helpful? Give feedback.
Replies: 28 comments 21 replies
-
Yes, I've run into the same problem today during migration to Next13. The problem is somewhere in JWT decode, it just fails, and I was not able to debug it as all my Long story short - The code is very bad as I had to copy-paste some internal variables, but it does work import { fetchData } from "next-auth/client/_utils";
import { cookies, headers } from "next/headers";
// next-auth/utils is not listed in export, next will not let you import it
// duplicating
function parseUrl(url: string | undefined) {
let _url2;
const defaultUrl = new URL("http://localhost:3000/api/auth");
if (url && !url.startsWith("http")) {
url = `https://${url}`;
}
const _url = new URL(
(_url2 = url) !== null && _url2 !== void 0 ? _url2 : defaultUrl,
);
const path = (
_url.pathname === "/" ? defaultUrl.pathname : _url.pathname
).replace(/\/$/, "");
const base = `${_url.origin}${path}`;
return {
origin: _url.origin,
host: _url.host,
path,
base,
toString: () => base,
};
}
// local variable in `next-auth/react`
const __NEXTAUTH = {
baseUrl: parseUrl(process.env.NEXTAUTH_URL ?? process.env.VERCEL_URL).origin,
basePath: parseUrl(process.env.NEXTAUTH_URL).path,
baseUrlServer: parseUrl(
process.env.NEXTAUTH_URL_INTERNAL ??
process.env.NEXTAUTH_URL ??
process.env.VERCEL_URL,
).origin,
basePathServer: parseUrl(
process.env.NEXTAUTH_URL_INTERNAL ?? process.env.NEXTAUTH_URL,
).path,
_lastSync: 0,
_session: undefined,
_getSession: () => {
// nope
},
};
const logger = {
error: console.error,
warn: console.warn,
debug: console.log,
};
export const getServerSession = async () => {
// code from `next-auth/next` for RSC
const req: any = {
headers: Object.fromEntries(headers()),
cookies: Object.fromEntries(
cookies()
.getAll()
.map((c) => [c.name, c.value]),
),
};
// the old `next-auth/react` getSession
const session = await fetchData("session", __NEXTAUTH, logger, { req });
return session;
}; |
Beta Was this translation helpful? Give feedback.
-
@thearnica |
Beta Was this translation helpful? Give feedback.
-
Please tell me you can track it down, It's not behaving as expected on Next 13, despite implementing it per the documentation and various guides. |
Beta Was this translation helpful? Give feedback.
-
So the stack trace:
Later I've put my token into token.dev and it was also not able to parse it, the error is "alg A256GCM is not supported". All other online JWT decodes I was able to find also failed me. https://dinochiesa.github.io/jwt/ worked the best, but still was not able to help. Something is not right there |
Beta Was this translation helpful? Give feedback.
-
I think I figured out the problem. Trying adding the NEXTAUTH_SECRET environment variable. |
Beta Was this translation helpful? Give feedback.
-
Yes, setting |
Beta Was this translation helpful? Give feedback.
-
Ok, glad it worked. But that was not mentioned anywhere in the docs. It should be mentioned in getServerSession ideally. |
Beta Was this translation helpful? Give feedback.
-
I'm new to NextJS and Next-Auth. I'm trying to write a secure api route that is only available if a user is logged in. I successfully accessing the session on the client side using Here is my route in src/pages/api/test.ts:
Here is my authOptions in src/pages/api/auth/[...nextauth].ts:
Also, I have |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
If I'm not mistaken, this issue also affects the public example of next-auth / auth.js at https://next-auth-example.vercel.app/server. At least I don't see my session's details ever on the server-rendered example meaning it can only be null. Works fine on the client-rendered or api-based examples. In my case, also setting |
Beta Was this translation helpful? Give feedback.
-
Same here, I still get null session with Using: |
Beta Was this translation helpful? Give feedback.
-
I did some more digging and seems like this issue is already known over at the example app: nextauthjs/next-auth-example#81. It's not directly a next-auth issue but just confusing / accidental forwarding of the Therefore, the It's also worth noting this is already addressed in the examples project for nextjs within the main next-auth repo but for some reason not yet mirrored to the dedicated example repository. |
Beta Was this translation helpful? Give feedback.
-
This Work for me |
Beta Was this translation helpful? Give feedback.
-
Guys any luck? On the latest Next.js 13.2.4 when api fetch requested from server side component, the getServerSession on API route returns null. But works fine with client component. |
Beta Was this translation helpful? Give feedback.
-
setting NEXTAUTH_SECRET is working for me as well. I'm using next 13.3.0 and next auth 4.22.0 |
Beta Was this translation helpful? Give feedback.
-
I am trying to use
It only works using dev mode though, and returns |
Beta Was this translation helpful? Give feedback.
-
Here's the solution:You should send request to API routes from frontend which is authenticated and not from postman, thunderbolt or any Still not working?You also need to provide authOptions as an argument for getServerSession i.e getServerSession(authOptions) in your backend code. |
Beta Was this translation helpful? Give feedback.
-
Got everything set, but still don't get the session. |
Beta Was this translation helpful? Give feedback.
-
The versions are |
Beta Was this translation helpful? Give feedback.
-
I also have the same problem, "next-auth": "^4.22.1" and "next": "13.4.5". I believe this problem has to do with the creation of the new @auth/core that will have edge support (https://authjs.dev/reference/core). |
Beta Was this translation helpful? Give feedback.
-
I have the same issue that is not working on the new API route. Version "next": "13.4.5",
"next-auth": "^4.22.1", |
Beta Was this translation helpful? Give feedback.
-
I'm having the same problem! |
Beta Was this translation helpful? Give feedback.
-
I am having the same problem too: Tried (which didn't worked):
|
Beta Was this translation helpful? Give feedback.
-
For those that have this issue, are on NextJS 12, and NextAuth 4, a possible solution was to set either Without this variable, NextAuth will silently always return null when you call getServerSessions, which is the method widely used for securing API endpoints and server side props. You do get a cryptic error telling you to set this value, but it's hard to understand why you have to set this. If you dig all the way into the lib, it's bc the secret is used as the encrypt/decrypt key on the jwt token. Without it, NextAuth does not generate a 32-bit key by itself. |
Beta Was this translation helpful? Give feedback.
-
It always returns
|
Beta Was this translation helpful? Give feedback.
This comment was marked as off-topic.
This comment was marked as off-topic.
-
Facin the same issue with |
Beta Was this translation helpful? Give feedback.
-
This is not a bug. See an explanation in the pinned issue #7423 (comment) |
Beta Was this translation helpful? Give feedback.
This is not a bug. See an explanation in the pinned issue #7423 (comment)