I do use it in a plugin that wraps the basic $fetch to always send the authentication headers along with it like follows:
import type { LoginResponse } from '~/utils/types';
export default defineNuxtPlugin(() => {
const runtimeConfig = useRuntimeConfig();
const baseURL = runtimeConfig.public.apiBaseUrl || 'localhost:8000/api';
const $api = $fetch.create({
baseURL,
retryStatusCodes: [401],
retry: 1,
onRequest({ options }) {
const authStore = useAuthStore();
if (authStore.isLoggedIn && authStore.accessToken) {
options.headers = {
...options.headers,
Authorization: `Bearer ${authStore.accessToken}`,
};
}
},
onResponseError: ({ response }) => {
const authStore = useAuthStore();
if (response.status === 401) {
return $fetch<LoginResponse>('/auth/refresh', {
method: 'POST',
baseURL,
credentials: 'same-origin',
headers: {
'Authorization': `Bearer ${authStore.refreshToken}`,
'Access-Control-Allow-Origin': '*',
},
body: {
refresh_token: authStore.refreshToken,
},
}).then((response) => {
authStore.signIn(response);
}).catch(async () => {
authStore.logout();
await navigateTo('/login');
});
}
},
});
return {
provide: {
api: $api,
},
};
});
Considering your point, I assume this is not SSR safe than?😅 Is there another way I should call useAuthStore()?