Next.js Discord

Discord Forum

Middleware executes many times

Unanswered
Arthur posted this in #help-forum
Open in Discord

17 Replies

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
sure
and the middleware itself
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?
how can I test that if this is the case?
console.logs 😄
cant I just use 1 useEffect?
like merge them
@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/db