Middleware executes many times
Unanswered
Arthur posted this in #help-forum
17 Replies
ArthurOP
I can't even show how many requests Im getting after just clicking 1 button to open a page.
I think you'll need to share the code that calls the middleware to get any help
ArthurOP
sure
and the middleware itself
ArthurOP
export async function validateToken(token: string, fromMiddleware?: boolean): Promise<SessionAPI> {
const cacheKey = `cache_${token}`;
// Try to get data from cache
if (!fromMiddleware) {
const cachedData = cookies().get(cacheKey)?.value;
if (cachedData) {
const cachedDataParsed = JSON.parse(cachedData);
return cachedDataParsed;
}
}
try {
const res = await fetch(`${process.env.API_ENDPOINT}/session/validate/${token}`, {
cache: 'no-store',
headers: {
Authorization: `Basic ${process.env.API_SECRET}`,
},
});
const data = await res.json();
const apiParsed = {
...data,
expires_at: new Date(data.expires_at),
};
// Store the data in cache and add expires option
if (!cookies().get(cacheKey)?.value) {
cookies().set(cacheKey, JSON.stringify(apiParsed), {
expires: new Date(data.expires_at),
});
}
return apiParsed;
} catch (error) {
if (isAxiosError(error)) console.log(error.response);
throw error;
}
}I can't read through it all properly right now, but maybe you have circular dependencies on the client side with all those
useEffects?ArthurOP
how can I test that if this is the case?
console.logs 😄
ArthurOP
cant I just use 1 useEffect?
like merge them
ArthurOP
@josh it seems that the middleware is called like 6 or 7 times
but I dont know how I can find out why this happends
this is the matcher
Im trying to load this page:
/admin/logs/dbArthurOP
it seems to be an issue everywhere
https://stackoverflow.com/questions/76164152/why-is-next-js-middleware-running-multiple-times
https://stackoverflow.com/questions/76164152/why-is-next-js-middleware-running-multiple-times