Create custom request response interceptor for native fetch
Unanswered
AM posted this in #help-forum
AMOP
Hello, does anyone manage to create custom interceptor for native fetch? I readed this article https://www.adios-axios.com/#why and on bottom is saying:
but has anyone manage to do it cuz tbh i have no idea how to proceed with it ðŸ™
Additionally, other features you might consider migrating include interceptors, which can be easily implemented as small, reusable functions that you can apply to response objects.but has anyone manage to do it cuz tbh i have no idea how to proceed with it ðŸ™
1 Reply
AMOP
So far i have created something like this but i'm not sure if this is this the right dirrection:
import { getSession } from 'next-auth/react';
export * from './auth';
export * from './movies';
export const fetchApi = async (url: RequestInfo | URL, data?: any) => {
const session = await getSession();
const init = data
? {
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${session?.user.accessToken}`
}
}
: undefined;
const response = await fetch(url, { ...init });
if (!response.ok) {
if (response.status === 401) {
throw new Error('Unauthorized');
}
throw new Error('Request Failed');
}
return response.json();
};