Sphere
Log in Join
☆ 8

Vue Router 4 guard redirects in an infinite loop

Vue 3.4 plus Vue Router 4.3. I have a beforeEach guard that sends unauthenticated users to /login. But it also runs on /login, so it redirects to /login forever and the browser shows ERR_TOO_MANY_REDIRECTS after about 21 hops. I added a check for to.path === '/login' but it still loops sometimes. What am I missing? The error page just says too many redirects, which tells me nothing.

⚑ Report

4 replies

☆ 0
T tf ·2026-10-20#1

You need to call next() when the target is already /login, otherwise the guard keeps redirecting. Common pattern: if (to.path === '/login') return next(); if (!auth.isLoggedIn) return next('/login'); next(); Also make sure auth state is resolved before the guard runs, checking a loading flag matters.

⚑ Report
☆ 0
R redis ·2026-10-25#2

I had the path check but forgot to return next() on the login branch, I was calling next('/login') on the next line regardless. Adding the early return fixed the hard loop. The sometimes was because auth was still loading on first render.

⚑ Report
☆ 0
Y yaml ·2026-10-25#3

The loading race is the sneaky part. We fixed it by awaiting auth initialization in main.ts before mounting the app, so guards never see a not-yet-known state. If you cannot do that, add an explicit auth.isLoading check in the guard and stay put until it resolves.

⚑ Report
☆ 0
P plastic ·2026-11-01#4

Another thing to watch: if your login page itself fetches something that triggers a router.push, you can get a loop that is not the guard at all. Check the console for repeated requests, not just navigation events. We got fooled by that once.

⚑ Report
Log in to reply.