Struggling with refresh token strategy in middleware for server components #78604
Replies: 1 comment 1 reply
-
I happen to be working on this at this exact moment. Here are a couple thoughts: First, you probably don't want to do this in middleware. There are reasons, but the shortest is NextJS docs advise against session management in middlware. Theo has a video on youtube that goes into more detail. Second, are your refresh tokens rotating or static? I.e. when you use a refresh token, is it expended (not reusable), or can it be used again for its duration? If it's not rotating, you can create a slim wrapper around fetch just for fetching your endpoints. You can get the session via // rough idea...
let refreshingLockByUserId = {}; // keyed by userId so server-side refreshes don't block each other
if (shouldRefresh) {
refreshingLockByUserId[userId] = refreshTheToken() // returns a promise
}
await refreshingLockByUserId[userId]; // now all promises will wait until the first is resolved
fetch(thingYouWanted) The reason this doesn't work for rotating refresh tokens is you could have a race where client and server try to refresh at the same time. If you only use one environment, that makes things easier. I ended up creating a wrapper that works on both client and server, since I make requests from both, but there's that possible race that I don't like :( If you figure out how to do it with rotating refresh tokens, without a shared memory storage like redis, let me know! |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi everyone,
I've spent many days trying to implement a proper token refresh mechanism in Next.js 14 for an application that heavily uses Server Components fetching data during the page render.
Despite trying multiple strategies, I keep facing serious race conditions that invalidate the whole authentication flow and result in users being redirected to login even when their session should be extendable.
Problem Summary
/api/refresh
endpoint.Detailed Flow
/api/refresh
./api/refresh
calls at once.Question
Is there any Next.js 14+ recommended strategy to handle token refresh?
Relevant Code
Middleware (
middleware.ts
)Refresh API Route (/api/auth/refresh/route.ts)
Project Setup
Beta Was this translation helpful? Give feedback.
All reactions