Refresh Token Rotation with NextJs

Hey everyone! We have been using better-fetch with a custom auth plugin to handle attaching a bearer token to each request to our backend, and it's working great. However, I was wondering if anyone has had to deal with setting up a refresh token rotation within a plugin? For example, if the request fails with a 401 status, how can I trigger only 1 call to my /refresh endpoint without race conditions to refresh the token and retry the request with the new token? Also, a related question is how would I sign out the user on the client if the refresh token was revoked / something else went wrong? Here's my current implementation (not working)
import { BetterFetchPlugin, createFetch } from '@better-fetch/fetch';
import { auth, signOut } from './auth';
import { BACKEND_URL } from './constants';

const authPlugin: BetterFetchPlugin = {
id: 'auth',
name: 'Auth Plugin',
init: async (url, options = {}) => {
try {
const session = await auth();
const token = session?.user?.accessToken;
if (!token) {
console.log('Token is missing, signing out');
await signOut();
throw new Error('Authentication token is missing');
}

options.headers = {
...(options.headers ?? {}),
Authorization: `Bearer ${token}`
};
return { url, options };
} catch (error) {
console.error('Error in auth plugin:', error);
throw error;
}
}
};

export const adminFetch = createFetch({
baseURL: `${BACKEND_URL}/admin`,
plugins: [authPlugin],
timeout: 10000,
throw: false
});
import { BetterFetchPlugin, createFetch } from '@better-fetch/fetch';
import { auth, signOut } from './auth';
import { BACKEND_URL } from './constants';

const authPlugin: BetterFetchPlugin = {
id: 'auth',
name: 'Auth Plugin',
init: async (url, options = {}) => {
try {
const session = await auth();
const token = session?.user?.accessToken;
if (!token) {
console.log('Token is missing, signing out');
await signOut();
throw new Error('Authentication token is missing');
}

options.headers = {
...(options.headers ?? {}),
Authorization: `Bearer ${token}`
};
return { url, options };
} catch (error) {
console.error('Error in auth plugin:', error);
throw error;
}
}
};

export const adminFetch = createFetch({
baseURL: `${BACKEND_URL}/admin`,
plugins: [authPlugin],
timeout: 10000,
throw: false
});
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?