How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Next.js · TypeScript/React

Fix Error: ERR_TOO_MANY_REDIRECTS: Redirect loop detected in middleware in Next.js

This error occurs when Next.js middleware creates an infinite redirect loop by redirecting to a URL that also triggers the middleware, which redirects again endlessly. Fix it by adding a condition to skip the redirect when the request already matches the target URL or by using a matcher config to exclude the redirect target.

Reading the Stack Trace

Error: ERR_TOO_MANY_REDIRECTS at middleware (/app/src/middleware.ts:12:14) at adapter (/app/node_modules/next/dist/server/web/adapter.js:97:16) at async DevServer.runMiddleware (/app/node_modules/next/dist/server/next-server.js:395:26) at async DevServer.handleRequest (/app/node_modules/next/dist/server/base-server.js:285:20) at async DevServer.run (/app/node_modules/next/dist/server/base-server.js:347:29) at async invokeRender (/app/node_modules/next/dist/server/lib/router-server.js:163:21) at async handleRequest (/app/node_modules/next/dist/server/lib/router-server.js:350:24) at async requestHandler (/app/node_modules/next/dist/server/lib/router-server.js:374:13)

Here's what each line means:

Common Causes

1. Middleware redirects to a path it also matches

The middleware redirects unauthenticated users to /login, but /login also triggers the middleware, causing another redirect.

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const token = request.cookies.get('auth-token');
  if (!token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
}

2. Missing matcher configuration

Without a matcher, the middleware runs on every route including static files, API routes, and the redirect target.

import { NextResponse } from 'next/server';

export function middleware(request) {
  if (!request.cookies.get('session')) {
    return NextResponse.redirect(new URL('/auth/signin', request.url));
  }
}

// No export const config = { matcher: [...] }

3. Locale redirect loop

Middleware redirects based on locale detection but the redirected URL triggers another locale check.

export function middleware(request) {
  const locale = request.headers.get('accept-language')?.split(',')[0];
  if (locale?.startsWith('fr')) {
    return NextResponse.redirect(new URL(`/fr${request.nextUrl.pathname}`, request.url));
  }
}

The Fix

Add a matcher configuration that excludes the /login path, static assets, and other public routes from middleware processing. This prevents the redirect loop because the middleware no longer runs on the redirect target.

Before (broken)
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const token = request.cookies.get('auth-token');
  if (!token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
}
After (fixed)
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const token = request.cookies.get('auth-token');
  if (!token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}

export const config = {
  matcher: ['/((?!login|_next/static|_next/image|favicon.ico).*)'],
};

Testing the Fix

import { NextRequest } from 'next/server';
import { middleware } from '@/middleware';

function createRequest(url: string, cookies: Record<string, string> = {}) {
  const req = new NextRequest(new URL(url, 'http://localhost:3000'));
  Object.entries(cookies).forEach(([k, v]) => req.cookies.set(k, v));
  return req;
}

describe('middleware', () => {
  it('redirects unauthenticated users to /login', () => {
    const res = middleware(createRequest('/dashboard'));
    expect(res?.status).toBe(307);
    expect(res?.headers.get('location')).toContain('/login');
  });

  it('allows authenticated users through', () => {
    const res = middleware(createRequest('/dashboard', { 'auth-token': 'valid' }));
    expect(res?.status).toBe(200);
  });
});

Run your tests:

npm test

Pushing Through CI/CD

git checkout -b fix/middleware-redirect-loop,git add src/middleware.ts src/__tests__/middleware.test.ts,git commit -m "fix: add matcher config to prevent middleware redirect loop",git push origin fix/middleware-redirect-loop

Your CI config should look something like this:

name: CI
on:
  pull_request:
    branches: [main]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
      - run: npm ci
      - run: npm test -- --coverage
      - run: npm run build

The Full Manual Process: 18 Steps

Here's every step you just went through to fix this one bug:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. Monitor production to confirm the error is resolved

Total time: 30-60 minutes. For one bug.

Or Let bugstack Fix It in Under 2 minutes

Every step above? bugstack does it automatically.

Step 1: Install the SDK

npm install bugstack-sdk

Step 2: Initialize

import { initBugStack } from 'bugstack-sdk'

initBugStack({ apiKey: process.env.BUGSTACK_API_KEY })

Step 3: There is no step 3.

bugstack handles everything from here:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. Deploys to production (or opens a PR for review)

Time from error to fix deployed: Under 2 minutes.

Human involvement: zero.

Try bugstack Free →

No credit card. 5-minute setup. Cancel anytime.

Deploying the Fix (Manual Path)

  1. Run the test suite locally to verify the middleware works without redirect loops.
  2. Open a pull request with the matcher configuration.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review and approve the PR.
  5. Merge to main and test authentication flow in staging.

Frequently Asked Questions

BugStack tests all middleware paths including the redirect target, verifies no loops exist, runs your test suite, and confirms the build succeeds before marking it safe.

Every fix is delivered as a pull request with full CI validation. Your team reviews and approves before anything reaches production.

The regex /((?!login|_next/static|_next/image|favicon.ico).*) uses a negative lookahead to exclude those paths from middleware. The middleware will not run for /login or static assets.

Yes, you can add if (request.nextUrl.pathname === '/login') return NextResponse.next() at the top. However, a matcher config is more performant because it avoids invoking middleware at all.