Replies: 3 comments 6 replies
-
I’m not sure if it will help, but I think it would be good to refer to this docs Additionally, I recommend considering using |
Beta Was this translation helpful? Give feedback.
-
I can answer for quetions 1 and 2. Recommend to refer stateless session authentication. link anyway, your problem is seemed that |
Beta Was this translation helpful? Give feedback.
-
Ok I understood the problem.I've found a solution to it and now I'm writing a medium article in order to provide a simple working approach to everyone!Il 9 Mag 2025 10:43, Sylvester ***@***.***> ha scritto:
Yeah, you're right — NextAuth does use stateless session management when configured with JWT. However, you still need to properly configure it in your route handler (e.g., src/app/api/auth/[...nextauth]/route.ts).
The issue I encountered was that the token couldn’t be accessed from a client-side component and passed to a server action. I might have been retrieving the token incorrectly — I was using getSession from next-auth/react, which works only on the client side.
I noticed that Axios interceptors were able to get the token when making API calls from the client, but not from within a server action.
To make it work, I ended up removing 'use server' from the top of the file, which allowed the session to be accessed — but that feels more like a workaround than a proper solution. That’s why I’m currently exploring a better approach.
—Reply to this email directly, view it on GitHub, or unsubscribe.You are receiving this because you commented.Message ID: ***@***.***>
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
The Problem
I recently encountered a challenging authentication issue when working with Next.js Server Actions connecting to a NestJS backend API.
When making authenticated requests from client components everything works fine, but when using Server Actions (with the
"use server"
directive), the authentication token wasn't being passed to my external API, resulting in 401 Unauthorized errors.Context
My architecture:
Client-side Code
Server Action
Usage in Components
Server Logs
The key issue is visible in the logs:
"authorization":""
- the token is missing when the request is made from the server action.Solutions I'm Considering
Pass Token as Parameter: Update all server actions to accept a token parameter
Token Store: Create a shared token store accessible to server actions
Remove "use server": Convert server actions to client-side functions (works but loses server benefits)
Use getServerSession: Retrieve session directly in server actions (if next-auth is properly configured)
Questions
Looking forward to hearing how others are solving this common challenge!
Additional information
No response
Example
No response
Beta Was this translation helpful? Give feedback.
All reactions