I am trying to use next-auth
with relay-nextjs
. I setup next-auth
per a hasura jwt example , and relay-nextjs
per the official docs . I want to pass a next-auth
jwt Bearer token in the relay-nextjs
Authorization header sent to the GraphQL endpoint.
next-auth
provides a getSession
method. Under the hood , this requests a server endpoint.
relay-nextjs
provides a serverSideProps
property of a withRelay
HoC. You pass your page component to withRelay
. You add a function to serverSideProps
that will send a token to the page's Relay environment.
My problem is getSession
is null inside serverSideProps
:
serverSideProps: async (ctx) => {
const { getSession } = await import('next-auth/client');
// This is an example of getting an auth token from the request context.
// If you don't need to authenticate users this can be removed and return an
// empty object instead.
const token = await getSession();
return { token };
}
If I can get the token here, it works in relay-nextjs
. Returning a string works fine, adds it to the header.
There's a next-auth
cookie with the app page request. I checked it against the endpoint called by getSession
. The cookies don't match. They do, until this part after the last dot, which changes on each request.
session-token=xxxx.xxxxxxxx.xxxxx
I ran it through the debugger, and it looks like relay-nextjs
executes before the next-auth
callback.
One approach I'm trying now is store the next-auth
token in a database, and run a prisma query instead of getSession
. Any input is welcomed.
ok this is a lot easier than I thought. Just do:
serverSideProps: async (ctx) => {
// This is an example of getting an auth token from the request context.
// If you don't need to authenticate users this can be removed and return an
// empty object instead.
return { token: ctx.req.cookies['next-auth.session-token'] };
}
I traced through the next-auth code here:
https://github.com/nextauthjs/next-auth/blob/main/src/server/lib/cookie.js#L142
https://github.com/nextauthjs/next-auth/blob/main/src/server/index.js#L66
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.