Next.js + NextAuth.js — SSO Security Hardening and Best Practices
Next.js + NextAuth.js — SSO Security Hardening and Best Practices
This final post in the Next.js Frontend SSO series focuses on security and best practices for production-grade SSO. Even with a working authentication flow, neglecting security can lead to token leaks, session hijacking, or unauthorized access.
1️⃣ Secure session cookies
NextAuth.js stores session information in cookies (JWT or database sessions). Configure cookies properly:
- httpOnly: prevents JavaScript access to cookies
- secure: ensure cookies are sent only over HTTPS
- SameSite: protect against CSRF (use "lax" or "strict")
cookies: {
sessionToken: {
name: `__Secure-next-auth.session-token`,
options: {
httpOnly: true,
sameSite: 'lax',
path: '/',
secure: process.env.NODE_ENV === 'production'
}
}
}
2️⃣ Refresh token rotation
Refresh tokens should be rotated to prevent replay attacks.
NextAuth.js allows you to implement token refresh in the jwt callback:
async jwt({ token }) {
if (Date.now() > token.expires) {
const refreshed = await refreshAccessToken(token);
token.accessToken = refreshed.accessToken;
token.refreshToken = refreshed.refreshToken;
token.expires = refreshed.expires;
}
return token;
}
> Always propagate the refreshed tokens to the session.
3️⃣ Minimum scope / least privilege
- Only request the scopes your app actually needs
- For API calls, never use a long-lived access token with excessive permissions
- Limit manager or admin privileges to dedicated flows (like popup login)
4️⃣ Handle token expiration and logout
- Always check token expiration before making API calls
- Use automatic logout if a refresh fails or token is invalid
- Clear cookies and session on logout to prevent stale sessions
5️⃣ Debugging and monitoring
Monitoring authentication flows helps detect anomalies early:
- Log all login attempts and role verification failures
- Enable
DEBUG="next-auth:*"in development for detailed logs - Monitor refresh token failures and session expirations
6️⃣ CSRF and CORS considerations
- NextAuth.js has built-in CSRF protection for sign-in requests
- Always configure your backend APIs with proper CORS headers
- For manager approval flows or popups, ensure
postMessageonly accepts trusted origins
7️⃣ Summary
By following these practices, your Next.js SSO flows become production-ready:
- Secure session cookies
- Refresh token rotation and propagation
- Least privilege scopes
- Token expiration handling and forced logout
- Logging and monitoring
- CSRF and CORS protections
This concludes the Next.js Frontend SSO Series. With these 7 posts, you now have a complete guide from basic setup to advanced flows, role management, popup approval, token handling, and security hardening.
Part of the Next.js Frontend SSO Series
❤️ Support This Blog
If this post helped you, you can support my writing with a small donation. Thank you for reading.
Comments
Post a Comment