Need help with implementing access token refresh
Unanswered
Dan posted this in #help-forum
DanOP
I am trying to implement refresh of access token when it expires, given that a refresh token exists. Here is my middleware code
I have 2 issues here
1. when navigating between pages it seems to work properly and set a new access token the first time, but 2nd and 3rd time it gives me this error "Cannot read properties of undefined (reading 'split')". It's because for some reason the cookie isn't being sent from the fetch. I console.logged the cookie from the response and it just gives empty array
2. When I execute a server action, the server action executes before the refresh of the token, which isn't what I want
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getRefreshToken } from "./utils/getCookie";
export async function middleware(request: NextRequest) {
if (request.cookies.has("refresh_token")) {
if (request.cookies.has("access_token")) {
return NextResponse.next();
}
const token = getRefreshToken()!;
console.log(token);
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/auth/refresh`,
{
method: "POST",
headers: {
Cookie: token,
},
},
);
// if (!res.ok) {
// throw new Error(`Status code: ${res.status}, Message: ${res.statusText}`);
// }
console.log(res.headers.getSetCookie());
const accessToken = res.headers.getSetCookie()[0].split("access_token=")[1];
const accessTokenValue = accessToken.split("; ")[0];
const accessTokenMaxAge = accessToken.split("; ")[1].split("=")[1];
const response = NextResponse.next();
response.cookies.set({
name: "access_token",
value: accessTokenValue,
httpOnly: true,
maxAge: +accessTokenMaxAge,
path: "/",
secure: true,
});
return response;
}
return NextResponse.next();
}I have 2 issues here
1. when navigating between pages it seems to work properly and set a new access token the first time, but 2nd and 3rd time it gives me this error "Cannot read properties of undefined (reading 'split')". It's because for some reason the cookie isn't being sent from the fetch. I console.logged the cookie from the response and it just gives empty array
2. When I execute a server action, the server action executes before the refresh of the token, which isn't what I want
2 Replies
DanOP
export function getRefreshToken() {
const token = cookies().get("refresh_token")?.value;
return token ? `refresh_token=${token}` : token;
}DanOP
This what I see with just the fetch request
https://i.imgur.com/ZZacnrM.png
idk what is going on there and why there's 2 arrays with one of them being empty
https://i.imgur.com/ZZacnrM.png
idk what is going on there and why there's 2 arrays with one of them being empty