Trying to implement own cookie-based authentication in the next 14, and I want to refresh the token and retry the request if it returns a 401, whether it’s a server or client request. On the client, everything is simple, but i can’t set refreshed cookies in server component.
Since you can’t set cookies in the server component, I created a route handler that acts as a proxy between my refresh endpoint and supposed to set cookies:
app/api/refresh/route.ts
export async function GET(request: NextRequest) {
const response = await fetch('http://localhost:3000/api/v1/auth/refresh', {
method: 'POST',
credentials: 'include',
headers: request.headers,
});
const responseCookies = response.headers.getSetCookie();
responseCookies.forEach((cookie) => {
cookies().set(parseSetCookie(cookie));
});
console.log('COOKIES IN ROUTE HANDLER >>> ', cookies().getAll()); // refreshed cookies
return response;
}
All cookies are present in the route handler log, but they are not passed to the server component where request was made:
const response = await fetch('http://localhost:4200/api/refresh', {
method: 'GET',
credentials: 'include',
...{
headers: isServer
? (await import('next/headers')).headers()
: undefined,
},
});
if (isServer) {
const { cookies } = await import('next/headers');
console.log('COOKIES IN SERVER COMPONENT >> ', cookies().getAll()); // old cookies
}
Log in server component returns set of old, unrefreshed cookies, even though they are present and refreshed in the response from http://localhost:4200/api/refresh itself.