Category: Next.js, React and TypeScript

Next.js Middleware creates a redirect loop on /login

Read this guide in Polish

The browser informs about too many redirections and the login route does not open. Matcher or auth condition can also capture the login page or the resources needed to make the redirection.

How to determine the source of the error

Check the Network status sequence of 307 and Location addresses by saving the first URL and end URL.

Compare matchr with /login, /api/auth and resources next; check if the session is actually read.

What to do step by step

1. Disable the public log-in route from redirecting to it itself and separate rules for the guest and user logged in.

2 . Instead of comparing the presence of cookies itself, check the session on the site of the appropriate server, taking into account the expiration.

How to check the score

From the incognito window the entrance to the protected route ends with one redirection, and the entry to the login works without a loop.

What to do

Do not set a matchr to control all static resources.