How can I access the HTTP request from a server component? #52006
-
|
Hi, How can I access the http request from my server component (using app router)? My goal is to be able to get the JWT token from next auth. The util method to get the JWT token in next auth requires the request passed in as parameter.
But how to get that request ("req"), from the server component? I appreciate any help with this. Thanks |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 4 replies
-
|
You should use the With this you can access all the infromations about the user through SSR and Server Components. |
Beta Was this translation helpful? Give feedback.
-
|
Thanks @nicksan222 For that to work I would need to attach the access token to the session. That would expose the access token client side. I'm not sure if it's a good idea? See my other question - nextauthjs/next-auth#7886 My idea was to NOT attach the access token to the session, keep the access token server side only, and read the access token (on the server) using this utility function:
The problem is, I don't have access to the request when I'm in a server component. So I can't call |
Beta Was this translation helpful? Give feedback.
-
|
@leodip There is a section in the documentation about this: https://next-auth.js.org/configuration/nextjs#in-app-directory It appears, however, that |
Beta Was this translation helpful? Give feedback.
-
|
Perhaps something like const { headers, cookies } = require("next/headers")
req = {
headers: Object.fromEntries(headers() as Headers),
cookies: Object.fromEntries(cookies().getAll().map((c) => [c.name, c.value])),
}
const token = await getToken({ req }); |
Beta Was this translation helpful? Give feedback.
That is because
getServerSession()calls thesession()callback which calls thejwt()callback with the decoded token.While
getToken()simply returns the decoded token.That means that
getServerSession()is able to return a value based on a call tojwt()within the same request, although you have to go throughsession().However, this should not be a concern at all. Ask yourself what should happen if the browser initiates 2 API requests in parallel, but one of them refreshes the token? Or if the second request starts later but before the response to the first one was received?
The answer is that you refresh tokens a bit ahead of time. There will be a short window when two tokens are vali…