Skip to content

Commit

Permalink
fix: use config.headers in axios interceptor
Browse files Browse the repository at this point in the history
  • Loading branch information
ooooorobo committed Oct 26, 2024
1 parent bf8c652 commit eac76c5
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
4 changes: 2 additions & 2 deletions src/app/entry.server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ axios.interceptors.response.use(
async (e) => {
console.error(e);

if (e.status !== 401 || e.request.url.includes('refresh') || e.request.config.sent || !e.config) return;
if (e.response.status !== 401 || e.config.url.includes('refresh') || e.config.sent) return;

const accessToken = await requestRefreshToken(e.request);
const accessToken = await requestRefreshToken(e.config.headers);
e.config.headers.Authorization = `Bearer ${accessToken}`;
e.config.sent = true;
return axios(e.config);
Expand Down
14 changes: 10 additions & 4 deletions src/app/server/authenticate.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { redirect } from '@remix-run/node';
import { destroySession, generateExpiredDate, getAuthSession, isDateExpired } from 'src/app/server/sessions';
import {
destroySession,
generateExpiredDate,
getAuthSession,
getAuthSessionFromHeaders,
isDateExpired,
} from 'src/app/server/sessions';
import { refreshToken } from 'src/types';

export const authenticate = async (request: Request) => {
Expand All @@ -20,7 +26,7 @@ export const authenticateWithoutRedirection = async (request: Request) => {
}

if (!expiredAt || isDateExpired(expiredAt)) {
const { data } = await requestRefreshToken(request);
const { data } = await requestRefreshToken(request.headers);

session.set('accessToken', data.accessToken);
session.set('refreshToken', data.refreshToken);
Expand All @@ -32,8 +38,8 @@ export const authenticateWithoutRedirection = async (request: Request) => {
return { accessToken };
};

export const requestRefreshToken = async (request: Request) => {
const session = await getAuthSession(request);
export const requestRefreshToken = async (headers: Headers) => {
const session = await getAuthSessionFromHeaders(headers);
try {
const { data } = await refreshToken({
accessToken: session.get('accessToken')!,
Expand Down
6 changes: 5 additions & 1 deletion src/app/server/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,8 @@ const getAuthSession = async (request: Request) => {
return await getSession(request.headers.get('Cookie'));
};

export { getAuthSession, commitSession, destroySession };
const getAuthSessionFromHeaders = async (headers: Headers) => {
return await getSession(headers.get('Cookie'));
};

export { getAuthSession, getAuthSessionFromHeaders, commitSession, destroySession };

0 comments on commit eac76c5

Please sign in to comment.