Authentication and Session Management in Next.js 14 with Microservices Architecture

Hi, I'm developing a web application using Next.js 14, where the frontend is served independently, and the backend API is deployed as a separate microservice. Authentication is handled via JSON Web Tokens (JWTs) obtained from the backend upon user login. These tokens are then used for subsequent requests to the backend to maintain user sessions and authenticate the user. I'm exploring the best practices for implementing authentication and session persistence in this architecture, especially considering Next.js 14's new features like the App Router. Here are my specific questions: Persisting User Sessions: In previous versions, I might have used a context wrapped around my app in the layout page to manage authentication state. However, with authentication actions (e.g., logging in) possibly happening in server components where context might not be accessible, what's the recommended approach to persist the user session across the application? Handling Token Invalidity (e.g., Password Change): If a user changes their password, implying that all previously issued JWTs should be invalidated, what's the best practice to ensure the user is logged out across all devices/sessions? Should the JWT validity be checked on every request, potentially in middleware, to ensure the session is still valid? How would this be efficiently implemented? State Management for Authentication: Since context might not be a viable option for server components, what are alternative strategies for managing and sharing authentication state (e.g., whether the user is logged in) across different components of the application, like headers or navigation bars? I'm looking for insights and best practices on managing user sessions, handling authentication state across the application, and ensuring secure and efficient authentication flows in a microservices architecture with Next.js 14.
1 Reply
alan
alan3mo ago
for auth, have you checked this out: https://www.youtube.com/watch?v=DJvM2lSPn6w
Lee Robinson
YouTube
Next.js App Router Authentication (Sessions, Cookies, JWTs)
Learn the foundations of session based authentication through cookies in the Next.js App Router, and how community libraries like Auth.js build on top of this model. Auth is a deep topic, so let me know what else you want to see here! ◆ Basic: https://github.com/balazsorban44/auth-poc-next ◆ NextAuth: https://github.com/vercel/next.js/tree/cana...