ERR_TOO_MANY_REDIRECTS in a Next.js and Supabase app: find the loop and fix it

By AI App Medic · Updated · Next.js · Supabase · Auth · Vercel

You open your app, or log in, and Chrome shows:

This page isn't working
your-app.vercel.app redirected you too many times.
ERR_TOO_MANY_REDIRECTS

Firefox says The page isn't redirecting properly, Safari says Too many redirects occurred. Sometimes it only happens on the dashboard, sometimes only after an hour, sometimes only on the custom domain. Clearing cookies fixes it for one user, and then it comes back.

A redirect loop always means two rules send the browser to each other, or one rule sends a page to itself. In Next.js apps built with Cursor or v0 on Supabase, the rules live in three places: the auth redirect in proxy.ts or middleware.ts, the session checks in layouts and pages, and the hosting setup (Vercel domains, Cloudflare, the registrar). The fix is quick once you know which one loops, so find that first.

Step 1: trace the loop with curl

Run this against the failing URL. It follows up to 8 redirects and prints only the status and the target of each hop:

curl -sIL --max-redirs 8 https://your-app.com/dashboard | grep -iE '^(HTTP/|location:)'

Read the location lines:

curl sends no cookies, so it shows the logged-out path. For the logged-in path, copy the cookie request header of a failing request from the browser Network tab and add -H "cookie: ...". That header contains your session, so do not paste it anywhere public. In the browser, tick Preserve log in the Network tab to see the same chain.

Step 2: the proxy redirects pages that must stay public

Most AI-generated auth code starts like this:

if (!user) {
  return NextResponse.redirect(new URL('/login', request.url))
}

With a matcher that runs on every route, a logged-out visitor asking for /login has no user, so they get redirected to /login, forever. The same happens to /auth/callback or /auth/confirm, the routes that turn the link from a login email or Google into a session. If those are redirected before they run, the user never gets a session at all.

Make the public paths explicit. On Next.js 16 the file is proxy.ts with a proxy function; on Next.js 15 and earlier it is middleware.ts with a middleware function. The logic is the same:

// proxy.ts (Next.js 16) or middleware.ts (Next.js 15 and earlier)
import { type NextRequest } from 'next/server'
import { updateSession } from '@/utils/supabase/proxy'

export async function proxy(request: NextRequest) {
  return updateSession(request)
}

export const config = {
  matcher: [
    // everything except Next.js internals and static files
    '/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|ico|txt|xml)$).*)',
  ],
}

And in the helper, decide what is public before you redirect:

const PUBLIC_PATHS = ['/', '/login', '/signup', '/auth', '/api/webhooks', '/pricing']

function isPublic(pathname: string) {
  return PUBLIC_PATHS.some((p) => pathname === p || pathname.startsWith(p + '/'))
}

Notice startsWith(p + '/') rather than startsWith(p): a plain prefix check also makes /authors or /login-help public by accident. Do not include API routes that should require a user, but do exclude webhook routes (Stripe and others never have a session cookie and do not follow a redirect to your login page).

Step 3: keep the refreshed cookies when you redirect

This is the cause behind loops that start an hour after login. The Supabase server client refreshes an expired session inside the proxy and writes the new tokens with setAll onto the response it was given. If your code then returns a brand new NextResponse.redirect(), those cookies are dropped. The browser keeps the old, now useless refresh token, the next request fails the check again, and you go around.

The full helper, with the cookies copied onto every redirect:

// utils/supabase/proxy.ts
import { createServerClient } from '@supabase/ssr'
import { NextResponse, type NextRequest } from 'next/server'

export async function updateSession(request: NextRequest) {
  let response = NextResponse.next({ request })

  const supabase = createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
    {
      cookies: {
        getAll() {
          return request.cookies.getAll()
        },
        setAll(cookiesToSet) {
          cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value))
          response = NextResponse.next({ request })
          cookiesToSet.forEach(({ name, value, options }) =>
            response.cookies.set(name, value, options)
          )
        },
      },
    }
  )

  // Do not put code between createServerClient and this call.
  const { data } = await supabase.auth.getClaims()
  const user = data?.claims
  const { pathname } = request.nextUrl

  const redirectTo = (path: string) => {
    const url = request.nextUrl.clone()
    url.pathname = path
    url.search = ''
    const redirect = NextResponse.redirect(url)
    // keep any refreshed session cookies
    response.cookies.getAll().forEach((cookie) => redirect.cookies.set(cookie))
    return redirect
  }

  if (!user && !isPublic(pathname)) return redirectTo('/login')
  if (user && (pathname === '/login' || pathname === '/signup')) return redirectTo('/dashboard')

  return response
}

Two details matter here. The setAll body must really write the cookies; an empty setAll, added to silence a TypeScript error, guarantees this bug. And the function must return response, not a new NextResponse.next(). Older code that uses get, set and remove instead of getAll and setAll comes from the deprecated auth helpers; replace it with a current @supabase/ssr. Related session errors on the server are covered in Auth session missing and JWT expired (PGRST303).

Step 4: two session checks that disagree

The ping-pong between /dashboard and /login needs two places that redirect: the proxy sends a logged-in user from /login to /dashboard, and the dashboard layout decides the user is not logged in and sends them back. Look for what makes the second check fail:

If you want only one source of truth, keep the redirect logic in the proxy and use layouts only to read the user, not to redirect.

Step 5: loops in the hosting setup

If the curl output alternates between http and https, or between the apex domain and www, your code is not involved.

Custom domain setup, including the DNS records and the Supabase redirect URLs that go with it, is covered in custom domain not working. If login sends people to localhost instead of looping, see login redirects to localhost after deploy.

Lovable and other Vite apps: the client-side version

A Vite single-page app has no proxy, so the browser never shows ERR_TOO_MANY_REDIRECTS. The same mistake shows up as a page that flickers between login and dashboard, or a login page that never stays. The usual cause is a route guard that redirects before Supabase has read the stored session:

function ProtectedRoute({ children }: { children: React.ReactNode }) {
  const [session, setSession] = useState<Session | null | undefined>(undefined)

  useEffect(() => {
    supabase.auth.getSession().then(({ data }) => setSession(data.session))
    const { data: sub } = supabase.auth.onAuthStateChange((_event, s) => setSession(s))
    return () => sub.subscription.unsubscribe()
  }, [])

  if (session === undefined) return <div>Loading...</div> // not known yet
  if (!session) return <Navigate to="/login" replace />
  return <>{children}</>
}

undefined means "not checked yet" and null means "checked, logged out". A guard that treats both the same sends every logged-in user to /login on page load, and a login page that redirects logged-in users bounces them back.

Prevention

FAQ

Why does clearing cookies fix it for a while?

The loop depends on a cookie: an old or half-written Supabase session cookie that one part of the app accepts and another rejects. Clearing cookies removes the bad session, so the user is simply logged out. The next time a session gets into that state, the loop comes back. Fix the cookie handling in the proxy instead.

Is it middleware.ts or proxy.ts?

On Next.js 16 the file is proxy.ts and the exported function is called proxy. Next.js 15 and earlier use middleware.ts with a middleware function. The file belongs in the project root, or inside src if you use one. Having both, or one in the wrong folder, is a common reason a fix seems to do nothing.

Can Supabase Auth settings cause a redirect loop?

Not by themselves. The Site URL and redirect URLs decide where Supabase sends the user after login. If the callback route that receives that link is caught by your proxy and sent to /login before it exchanges the code, the user never gets a session and keeps bouncing. Exclude the callback route.

The loop only happens on my custom domain, not on vercel.app. Why?

Then the app code is fine and the loop is in DNS or a proxy in front of Vercel: Cloudflare SSL set to Flexible, or a redirect from apex to www at one provider and from www to apex at another. Check the Location headers with curl to see which host each hop goes to.

My Lovable app flickers between login and dashboard but never shows this error. Is that the same thing?

It is the client-side version. A Vite app has no proxy, so the browser does not count redirects; the route guard just keeps navigating. The cause is a guard that redirects before Supabase has finished loading the session. Show a loading state until the first session check finishes.

Related guides