next.js

Does Next.js middleware run again after redirect / rewrite?


I have read all I could find on the topic and was still unable to answer the following:

Assuming Next.js middleware runs on all routes, does it run again after itself has returned a redirect / rewrite response to the client, or does it somehow only run once for a particular request?

The question came up as I encountered an infinite loop of redirects, leading me to wonder if it does in fact run again after it returned a NextResponse.redirect / NextResponse.rewrite.


Solution

  • Since middleware runs code before a request is completed, it is bound to run again if the middleware itself redirects to a different path in the app.

    The middleware does not run twice in itself. This change introducing the middleware shows that.

      //inside renderToHTML
    
      if (typeof DocumentMiddleware === 'function') {
        await DocumentMiddleware(ctx)
      }
    

    Now coming to NextResponse.redirect, the doc says that it returns a response which redirects.

    The method is defined like:

      public redirect(destination: string, statusCode: number) {
        this.setHeader('Location', destination)
        this.statusCode = statusCode
    
        // Since IE11 doesn't support the 308 header add backwards
        // compatibility using refresh header
        if (statusCode === RedirectStatusCode.PermanentRedirect) {
          this.setHeader('Refresh', `0;url=${destination}`)
        }
    
        return this
      }
    

    This sets the Location header, which means the browser is told to redirect to another URL.

    This would trigger a request again and hence, run the middleware again.