CodexBloom - Programming Q&A Platform

Struggling with Refresh Token Logic in a Next.js App Using NextAuth.js and PostgreSQL

๐Ÿ‘€ Views: 17 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-19
next.js next-auth authentication javascript

I'm updating my dependencies and I'm working on a project and hit a roadblock. I'm implementing authentication in my Next.js app using NextAuth.js with PostgreSQL as my database. I have noticed that when my access token expires, my app isn't correctly refreshing it. Instead, I'm getting a `401 Unauthorized` response when I try to make an API call that requires authentication. I've followed the documentation but am unsure how to properly manage the refresh token flow. Hereโ€™s the relevant part of my NextAuth.js configuration: ```javascript import NextAuth from 'next-auth'; import Providers from 'next-auth/providers'; export default NextAuth({ providers: [ Providers.Credentials({ name: 'Credentials', authorize: async (credentials) => { const res = await fetch(`${process.env.NEXTAUTH_URL}/api/auth/signin`, { method: 'POST', body: JSON.stringify({ username: credentials.username, password: credentials.password, }), headers: { 'Content-Type': 'application/json' }, }); const user = await res.json(); if (res.ok && user) { return user; } return null; }, }) ], callbacks: { async jwt({ token, user }) { if (user) { token.accessToken = user.accessToken; token.refreshToken = user.refreshToken; } return token; }, async session({ session, token }) { session.accessToken = token.accessToken; session.refreshToken = token.refreshToken; return session; }, }, }); ``` I have verified that the `refreshToken` is stored correctly in the JWT but it seems that itโ€™s never utilized when the access token expires. I tried to implement a refresh mechanism in the API calls like this: ```javascript const fetchWithAuth = async (url, options) => { const session = await getSession(); const res = await fetch(url, { ...options, headers: { ...options.headers, Authorization: `Bearer ${session.accessToken}`, }, }); if (res.status === 401) { // Attempt to refresh the token const refreshedSession = await refreshAccessToken(session.refreshToken); if (refreshedSession) { // Retry original request with new access token const newRes = await fetch(url, { ...options, headers: { ...options.headers, Authorization: `Bearer ${refreshedSession.accessToken}`, }, }); return newRes; } } return res; }; ``` But, the `refreshAccessToken` function isn't defined yet, and Iโ€™m not sure how to implement it properly. I want the refresh token to be used seamlessly, and I noticed that I might need to make a request to a specific API endpoint to get a new access token using the refresh token. Has anyone successfully implemented a refresh token strategy with NextAuth.js? Whatโ€™s the best approach to handle this flow without causing too much performance overhead? The stack includes Javascript and several other technologies. What's the correct way to implement this?