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:
/loginsends you to/login, or/login?next=%2Flogin...keeps growing: the proxy protects the login page itself. Step 2./dashboardand/loginalternate: two session checks disagree. One says logged out and sends you to login, the other says logged in and sends you back. This needs a session cookie to reproduce; see step 4.http://andhttps://alternate, oryour-app.comandwww.your-app.comalternate: the loop is in the hosting setup, not your code. Step 5.
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:
- Different Supabase URLs. The auth cookie name contains the project ref,
sb-<project-ref>-auth-token. If the proxy readsNEXT_PUBLIC_SUPABASE_URLand the layout reads a different variable that points at another project, or one of them isundefinedin production, they look for different cookies. Search the repo for everycreateServerClient(andcreateBrowserClient(and make them read the same variables. - Different checks. The proxy uses
getClaims()and the layout callsgetSession()on a client built without the request cookies, or a client created withcreateClientfrom supabase-js, which cannot see cookies at all. Use the cookie-based server client andgetClaims()(orgetUser()) in server code. - A layout check on the login page. A root
layout.tsxthat redirects logged-out users also wraps/login. Move protected pages into a route group such asapp/(app)/layout.tsxand keep/loginoutside it. - A client-side redirect racing the cookie. The login form calls
signInWithPasswordand immediately doesrouter.push('/dashboard'). Do the sign-in in a server action, or wait for it to resolve and then callrouter.refresh()before navigating, so the server sees the new cookie.
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.
- Cloudflare in front of Vercel or Netlify with SSL/TLS set to Flexible. Cloudflare talks to the host over plain HTTP, the host redirects to HTTPS, Cloudflare asks over HTTP again. Set SSL/TLS to Full (strict), or switch the record to DNS only (grey cloud). Vercel recommends DNS only for domains it serves.
- Opposite redirects. Vercel's domain settings redirect
your-app.comtowww.your-app.com, while a redirect rule at Cloudflare or the registrar sendswwwback to the apex. Pick one direction and set it in one place, usually the Vercel domain settings. - Your own redirects. A
redirects()entry innext.config.js, a rule invercel.jsonor a_redirectsfile that forces a host or a trailing slash, fighting another rule. Remove duplicates and keep one.
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
- Keep the list of public paths in one constant, next to the proxy, and add new public pages there.
- Every
NextResponse.redirectin the proxy goes through one helper that copies the cookies. - One set of Supabase variables, read by every client in the project.
- Before each deploy, run the curl check on
/,/loginand one protected page, logged out and logged in. - After adding a custom domain, run the same check on the apex and on
www, overhttpandhttps.
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
- Supabase "AuthSessionMissingError: Auth session missing!": find where the session went
- Supabase "JWT expired" (PGRST303 or PGRST301): why it starts after an hour and how to fix it
- Lovable custom domain not working: fix DNS, SSL, and the sign-in redirect
- Supabase login redirects to localhost (or the preview URL) after deploy: how to fix it
- Supabase AuthApiError: Invalid Refresh Token: Refresh Token Not Found