I need to make a API request to a downstream service from Remix, the request requires to pass JWT. If the service returns 401. we will need to use the refresh token and try to generate new JWT and make the request again.
I have tested the script below, it successfully generates a new token and made request to the downstream service, but when I want to update the session with the new JWT + refresh token, it doesn't seem to work. The subsequent requests still use the old token.
Here's my code:
export async function authoriseFetch(
request: Request,
url: RequestInfo,
init?: RequestInit
): Promise<Response> {
const session = await getSession(request.headers.get("Cookie"));
const token = session.get("token");
const refreshToken = session.get("refreshToken");
if (!token) {
throw redirect("/auth/login");
}
const fetchFn = (tk: string) => {
return fetch(url, {
...init,
headers: {
...init?.headers,
Authorization: `Bearer ${tk}`,
},
});
};
let response = await fetchFn(token);
// try to refresh the token if it's expired
if (response.status === 401) {
const { token, refresh_token } = await getRefreshToken(refreshToken);
// try to call again with the new token
response = await fetchFn(token);
if (response.status >= 400) {
throw redirect("/auth/login");
}
const cookieHeader = await setToken(token, refresh_token);
return new Response(response.body, {
...response,
headers: {
...response.headers,
"Set-Cookie": cookieHeader,
},
});
}
return response;
}
export const setToken = async (token: string, refreshToken: string) => {
const session = await getSession();
session.set("token", token);
session.set("refreshToken", refreshToken);
return commitSession(session);
};
ANy ideas?