Middleware runs before every request, at the edge. It's the ideal place for authentication checks, redirects, and request modification. Middleware Setup Secure JWT Login (httpOnly Cookies) Logout Auth Best Practices Practice Reason httpOnly cookies XSS-proof — tokens never accessible via JavaScript secure: true (production) Only sent over HTTPS sameSite: 'lax' Prevents CSRF on cross-origin requests Middleware auth check Runs at the edge — fast redirects Server-side token validation Never trust client-side auth state