Reputation: 99
I am using next-auth to handle authentication along with a custom backend that handles login which returns access and refresh tokens, and refresh endpoint to fetch new access token upon expiration. My code goes like this:
export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
async authorize(credentials: Credentials) {
const result = await postAPI(
`${process.env.NEXT_PUBLIC_API_URL}${ApiRoutes.Login}`,
{
email: credentials?.email,
password: credentials?.password,
},
);
if (result.status === 401) {
throw Error(result.data.errors[0].message);
}
return result.data;
},
credentials: undefined,
}),
],
secret: process.env.JWT_SECRET,
callbacks: {
async jwt({ token, user, trigger, session }) {
if (trigger === 'update') {
return {
...token,
...session.user,
};
}
return { ...token, ...user };
},
async session({ session, token }) {
session.user = token;
return session;
},
},
};
In jwt and session callbacks I am passing the access and refresh token information since I need to access them later via useSession hook in my axios interceptors . My question is I keep seeing a network request called "session" which exposes my token information and I don't understand where this request is coming from... Is this a normal behaviour since I am passing down the tokens info? or have I done something wrong on my setup?
Upvotes: 0
Views: 1079
Reputation: 11
Not sure if it's the correct behavior either, but you're seeing the access_token in session request because access_token is part of your token object in the session callback, you could break it apart and to access the token info you might be able to use getToken instead.
And the session request is from session re-fetching. https://next-auth.js.org/getting-started/client
async session({ session, token }) {
session.user.id = token.user.id;
session.user.name = token.user.name;
return session;
},
Here's some posts related to this.
Is it safe to save jwt accessToken on session in Next.js next-auth? Then using useSession hook to access it on client side?
https://github.com/nextauthjs/next-auth/issues/7976
Upvotes: 0