K
Kinde5mo ago
Albert

[NextJS 14] User session returns null in API route, when user is already authenticated from caller

Trying to understand what I'm doing wrong here: I have a component that calls an api route on a button click, this component doesn't render unless the user is authenticated. I'm using the standard { getUser } = getKindeServerSession() and user = await getUser() methods to verify this. However, when I call the api route from the button click, these same methods seem to return null for me in the API route handler, the code I have so far is pretty simple: export const POST = async (req: NextRequest) => { const { getUser } = getKindeServerSession(); const user = await getUser(); const res = await req.json() if(!user) { console.log("no user") } It seems that I'm consisting hitting the "if(!user)" line - I'm wondering if there's any gotcha's that I should be aware of that could be causing this?
4 Replies
ooi cat
ooi cat5mo ago
Hey. Can you show your import
Albert
Albert5mo ago
in the API file its just: import { getKindeServerSession } from "@kinde-oss/kinde-auth-nextjs/server" import { NextRequest } from "next/server" what's highly odd is this seems to work ok on another API route - are there any known issues/differences with how this behaves in api route handlers vs regular server components?
Ariel
Ariel5mo ago
@Albert I think you might need to await the get kinde server session call, too
Oli - Kinde
Oli - Kinde5mo ago
It seems like you're doing everything correctly. The getKindeServerSession() and getUser() methods should work the same in API routes and server components. However, there are a few things you could check: 1. Make sure you're not calling the API route from a place where the user might not be authenticated. Even though the component doesn't render unless the user is authenticated, there might be other places in your code where the API route is being called. 2. Check if there are any differences between the API route where the user session is working and the one where it's not. There might be some configuration or setup that's missing in the problematic route. 3. Try to debug the issue by logging the entire req object in the API route. This might give you some clues about what's going wrong. 4. Make sure that the user session is not being cleared somewhere in your code before the API route is called. If the issue still persists, let me know. I can help you further.
Want results from more Discord servers?
Add your server
More Posts