import {appendResponseHeader, H3Event} from "h3";
const refreshCredentials = async (event: H3Event) => {
const refreshToken = getCookie(event, 'X-Refresh-Token');
const response = await $fetch.raw<any>('<my api url>/auth/refresh', {
method: "POST",
baseURL: baseUrl,
headers: {
'X-Refresh-Token': refreshToken,
}
}
const { accessToken, refreshToken } = response._data
appendResponseHeader(event, 'set-cookie', 'X-Access-Token=' + newAccessToken + '; Path=/;')
setCookie(event, 'X-Access-Token', newAccessToken)
appendResponseHeader(event, 'set-cookie', 'X-Refresh-Token=' + newRefreshToken + '; Path=/;')
setCookie(event, 'X-Refresh-Token', newRefreshToken)
return {
accessToken,
}
}
export default defineEventHandler(async (event) => {
const route = getRouterParam(event, 'route');
const url = '<my api url>' + route;
const accessToken = getCookie(event, 'X-Access-Token');
return $fetch(url, {
method: event.node.req.method,
headers: {
...event.node.req.headers,
Authorization: `Bearer ${accessToken}`
},
retry: 1,
retryStatusCodes: [401],
body,
onResponse: async (context) => {
if (context.response.status === 401) {
const { accessToken } = refreshCredentials(event)
context.options.headers = {
...context.options.headers,
Authorization: `Bearer ${accessToken}`,
}
}
},
});
})