Next.js middleware for auth gating

2377
0

Protecting routes at the middleware layer prevents a whole class of ‘oops, we forgot to check auth on one page’ bugs. middleware.ts runs before rendering, so unauthenticated users get redirected early and you don’t waste work. I keep the logic simple: if the path matches a protected prefix, require a session cookie and redirect to /login. I also exclude public assets and the login route itself so I don’t create redirect loops. Middleware isn’t a replacement for server-side authorization checks on APIs, but it’s a great UX improvement and it reduces accidental exposure in UI routes.