Repeated calls to the NextJS middleware while accessing an Incremental Static Regeneration (ISR)

I am currently working on a NextJS application that includes an ISR page fetching data from Supabase. There is a middleware in place to record a page visit before the page is rendered.

export async function middleware(
  request: NextRequest,
  fetchEvent: NextFetchEvent
) {
  console.log('request.nextUrl.pathname', request.nextUrl.pathname);
  if (request.nextUrl.pathname.split('/').length === 2) {
    return linkVisitMiddleware(request, fetchEvent);
  }
}

However, I've noticed that the middleware gets called 2 or 3 times (the numbers seem to fluctuate for some unknown reason).

Whenever this happens, the following entries are logged on the server:

request.nextUrl.pathname /slug
request.nextUrl.pathname /slug
request.nextUrl.pathname /slug

Interestingly, this behavior only occurs in the production environment when using the command next start. When running the application locally with next serve, it only runs once as expected.

I have read about the reactStrictMode but implementing it did not resolve the issue.

Noteworthy mentioning, I have tested this on NextJS versions 13.1.1, 13.1.6 & 13.3.0

Answer №1

Finally, after hours of troubleshooting, I uncovered the source of the issue.

The ISR page was set to use the fallback strategy {fallback: true}, which led to it attempting to request the HTML page first. If the HTML page was not available, it would then revisit the same route to retrieve the data.

To address this issue, I discovered that NextJS utilizes headers to distinguish between different types of requests. Here is the solution I implemented:

import { linksMiddleware } from 'middleware/links';
import { NextFetchEvent, NextRequest, NextResponse } from 'next/server';

export async function middleware(
  request: NextRequest,
  fetchEvent: NextFetchEvent
) {
  // These methods are used when accessing locale routes, so we discard them
  if (request.method === 'OPTIONS' || request.method === 'HEAD') {
    return NextResponse.next();
  }

  //Capture URL locale (if any) and id. For example: /ar/random-id or /random-id
  const pathParams = request.nextUrl.pathname.split('/');

  if (pathParams.length === 2 && isDataRequest(request)) {
    // This means that we are accessing the entity homepage
    return linksMiddleware(request, fetchEvent, 'entity');
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    // This is to prevent the middleware from running on the API routes and during development
    '/((?!api|_next/static|_next/image|favicon.ico|favicon.svg).*)',
  ],
};

/**
 * Check if the request is a data request for cases of fallback pages
 * This header is absent in the initial request
 */
const isDataRequest = (request: NextRequest): boolean =>
  request.headers.get('x-nextjs-data') === '1' ||
  // The header is absent in development mode since there's no fallback logic (SSR-like)
  process.env.NODE_ENV === 'development';

Additionally, I included a check for the HTTP method to handle cases of locale routing excluding OPTIONS and HEAD.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular is programmed to detect any alterations

Upon detecting changes, the NgOnChanges function triggers an infinite service call to update the table, a situation that currently perplexes me. Any assistance on this matter would be greatly appreciated. Many thanks. The TableMultiSortComponent functions ...

The type is lacking the property onAuxClickCapture and onAuxClick

When utilizing forwardRef from React, an unexpected type error occurs: The type '{ children: ReactNode; }' is lacking the properties specified in 'Pick<ILinkProps, "className" | "children" | "accept" | "acceptCharset" | "action" | ... 34 ...

Currently in the process of creating a carousel displaying images, I have encountered an issue stating: "An optional property access cannot be on the left-hand side of an assignment expression."

I am currently working on an Angular Image Carousel that utilizes a model to iterate through the images. However, I am encountering an error when attempting to access the first position. An error message stating "The left-hand side of an assignment expres ...

Issue TS2339: The object does not have a property named 'includes'

There seems to be an issue that I am encountering: error TS2339: Property 'includes' does not exist on type '{}'. This error occurs when attempting to verify if a username is available or not. Interestingly, the functionality works ...

Resetting the timer of an observable in Angular 2

I have a unique service that automatically calls a method every 30 seconds. There is also a button that allows the user to reset the timer, preventing the method from being called for another 30 seconds. How can I make sure that the method does not get cal ...

Transforming the data type of a variable

Recently, I decided to switch my file name from index.js to index.ts. Here's an example of the issue I'm facing: let response = "none" let condition = true if(condition){ response = {id: 123 , data: []} } console.log(response) Howev ...

Changing the fill color of externally imported SVGs from a CDN: A simple guide

While working on a website project using Next JS, I came across the challenge of displaying SVG icons stored in Sanity and dynamically changing their fill color. Is it possible to achieve this feature, such as changing the color when hovering over the icon ...

Can you explain the distinction between the server component and client component in Nextjs 14?

export default function CustomLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="ko-KR"> <link rel="icon" href="/favicon.ico" sizes="any" /> <body> ...

"Adjusting the position of an Ionic Menu on-the-fly

As I strive to update the Ionic 3 Menu side dynamically when the user changes the language, a challenge arises for RTL languages where the menu needs to be on the right instead of the default left. To tackle this issue, I have subscribed to the TranslateS ...

Next-Auth: Access Session in _app.js Directly Without Using getServerSideProps

When working with React.js and React-Auth, it's important to note that calling server-side functions such as getServerSideProps can prevent you from exporting your project using next export. Below is the content of my pages/_app.js, which I structured ...

Securing Angular 2 routes with Firebase authentication using AuthGuard

Attempting to create an AuthGuard for Angular 2 routes with Firebase Auth integration. This is the implementation of the AuthGuard Service: import { Injectable } from '@angular/core'; import { CanActivate, Router, Activated ...

Is it possible to use both MUI makeStyles and Theming in the _app.js file?

I've been working on a complex navigation component using MUI Persistent Drawers within a React + Next.js setup. To achieve the desired content shrinking effect based on state changes, I ended up placing the entire navigation system inside the _app.js ...

The httpClient post request does not successfully trigger in an angular event when the windows.unload event is activated

Is there a way to send a post request from my client to the server when the user closes the tab or browser window? I have tried using the 'windows.unload'or 'windows.beforeunload' event, but the call doesn't seem to be successful a ...

Utilize useState in a versatile modal component for enhanced functionality

Currently, I am working on implementing a reusable modal component that will be used to collect user input for updating their personal information. The modal's content is dynamically set using a useReducer hook in the following way; const [modalState ...

Angular 2 forms, popping the chosen item in the `<select>` element

Check out the FormBuilder: let valuesArray = fb.array([ fb.group({ name: 'one' }), fb.group({ name: 'two' }), fb.group({ name: 'three' }), fb.group({ name: 'four' }) ]); this.for ...

Encountering an error with the Angular 2 SimpleChanges Object during the initial npm start process

Within my Angular 2 application, there exists a component that holds an array of objects and passes the selected object to its immediate child component for displaying more detailed data. Utilizing the "SimpleChanges" functionality in the child component a ...

Managing onChange in a ReactJs project

Currently, my React tsx page features input boxes like the following: <textarea value={this.state.myData!.valueOne} onChange={(e) => this.handleValueOneChange(e)}/> <textarea value={this.state.myData!.valueTwo} onChange={(e) => thi ...

Access Denied - NextJS and Azure: "Unauthorized access to this directory or page."

Despite going through various guides and watching YouTube tutorials, I still can't seem to figure out what's missing. My current setup involves using Azure DevOps for building and deploying an Azure App Service. Thankfully, the deployment process ...

Leveraging Next.js for "client-side rendering" in React Encapsulations

My dilemma involves a component housing content crucial for SEO optimization. Here is an excerpt from my code: <AnimatedElement className="flex flex-col justify-start items-center gap-4 w-full" duration={500}> <h2 class ...

Attempting to retrieve a URL using Angular/Typescript is generating an Unknown Error instead of the expected successful response

I'm trying to make a simple HTTP function call through TypeScript (Angular) to an API hosted as a function in Azure. When I call the URL through Postman or directly in the browser, everything works perfectly. However, when I try to call the URL usin ...