Next.js › Authentication & Authorization in Next.js

What are best practices for securely storing and validating authentication tokens in a Next.js app?

Advanced

Answer

Store authentication tokens in secure, httpOnly cookies so they cannot be accessed by client side JavaScript, always use HTTPS in production, set a reasonable expiration time, and verify token signatures on the server for every protected request rather than trusting client provided data.
res.setHeader('Set-Cookie', `session=${token}; HttpOnly; Secure; SameSite=Lax; Path=/`);
Real-world example A banking application stores its session token in an httpOnly secure cookie, preventing malicious scripts from stealing the token even if they somehow get injected into the page.

Common follow-ups: What is the difference between storing a token in a cookie versus local storage?;How often should authentication tokens be refreshed or rotated?