From 86f9127acc50a55329b531bd002e23e8707ce510 Mon Sep 17 00:00:00 2001 From: lehuygiang28 Date: Sat, 15 Jun 2024 01:54:36 +0700 Subject: [PATCH] chore: :zap: update axios options --- apps/fe/src/hooks/useAxiosAuth.ts | 13 ++++++++++--- apps/fe/src/libs/next-auth/options.ts | 8 ++++---- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/apps/fe/src/hooks/useAxiosAuth.ts b/apps/fe/src/hooks/useAxiosAuth.ts index 629fda2..5b55e42 100644 --- a/apps/fe/src/hooks/useAxiosAuth.ts +++ b/apps/fe/src/hooks/useAxiosAuth.ts @@ -1,9 +1,13 @@ import { useSession } from 'next-auth/react'; import { useEffect } from 'react'; import { useRefreshToken } from './useRefreshToken'; -import axiosInstance from '~/libs/axios'; +import { axiosInstance } from '~/libs/axios'; -export function useAxiosAuth() { +export type UseAxiosAuthPayload = { + baseURL?: string; +}; + +export function useAxiosAuth({ baseURL }: UseAxiosAuthPayload) { const { data: session, status } = useSession(); const refreshToken = useRefreshToken(); @@ -12,6 +16,9 @@ export function useAxiosAuth() { return; } + if (!axiosInstance.defaults?.baseURL) { + axiosInstance.defaults.baseURL = baseURL ?? process.env.NEXT_PUBLIC_API_URL; + } const requestIntercept = axiosInstance.interceptors.request.use( (config) => { if (!config.headers['Authorization']) { @@ -40,7 +47,7 @@ export function useAxiosAuth() { axiosInstance.interceptors.request.eject(requestIntercept); axiosInstance.interceptors.response.eject(responseIntercept); }; - }, [session, refreshToken, status]); + }, [session, refreshToken, status, baseURL]); return axiosInstance; } diff --git a/apps/fe/src/libs/next-auth/options.ts b/apps/fe/src/libs/next-auth/options.ts index 04cfdf4..05d8c82 100644 --- a/apps/fe/src/libs/next-auth/options.ts +++ b/apps/fe/src/libs/next-auth/options.ts @@ -4,7 +4,7 @@ import GithubProvider from 'next-auth/providers/github'; import CredentialsProvider from 'next-auth/providers/credentials'; import { AuthValidatePasswordlessDto, LoginResponseDto } from '~be/app/auth/dtos'; import { AxiosError } from 'axios'; -import axios from '../axios'; +import { axiosInstance } from '~/libs/axios'; export const authOptions = { providers: [ @@ -28,7 +28,7 @@ export const authOptions = { hash: credentials?.hash || '', }; - return axios + return axiosInstance .post(path, payload) .then((response) => { return response.data as unknown as User; @@ -44,7 +44,7 @@ export const authOptions = { async signIn({ user, account }: { user: User; account: Account | null }) { if (account?.provider === 'google') { try { - const { data: userData } = await axios.post( + const { data: userData } = await axiosInstance.post( '/auth/login/google', { idToken: account.id_token, @@ -71,7 +71,7 @@ export const authOptions = { } } else if (account?.provider === 'github') { try { - const { data: userData } = await axios.post( + const { data: userData } = await axiosInstance.post( '/auth/login/github', { accessToken: account.access_token,