Skip to main content
Learn how to effectively manage the lifecycle of sessions and JWT tokens. Session management is an important topic that directly affects user experience and security.

Session Management Overview

Session Store

Redis, PostgreSQL Scalable storage

Session Expiration

Auto expiration Sliding expiration

Token Refresh

Refresh Token Access Token reissue

Logout

Session invalidation Token blacklist

Session-Based Authentication

How Sessions Work

Session-based authentication is a method where the server stores the user’s login state on the server side. Understanding how it works helps you better handle security and scalability issues. Session Authentication Flow:
  1. When user logs in, server generates a session ID
  2. Session data (user ID, etc.) is stored in session store
  3. Session ID is sent to client as a cookie
  4. Each subsequent request authenticates user via session ID in cookie
Advantages:
  • Server has full control over sessions (can invalidate anytime)
  • Sensitive information is not exposed to client
  • Simple to implement and well-proven method
Disadvantages:
  • Stores state on server, requiring scalability considerations
  • Session store can become a single point of failure (SPOF)

Session Store Configuration

Memory Store (Development Only): Memory store should only be used in development environments. All sessions are lost when the server restarts, and sessions cannot be shared across multiple server instances.
Problems with Memory Store: - All sessions lost on server restart - Cannot share sessions across multiple server instances - Memory usage growth can degrade performance - Never use in production
Redis Store (Production): Using Redis as a session store is the industry standard for production environments. Redis is fast, scalable, and supports session sharing across multiple server instances.
Redis Configuration Explained:
  • prefix: Prefix for session keys to distinguish from other data
  • ttl: Time To Live, automatic session expiration time (in seconds)
  • client: Redis client instance
Redis supports cluster mode for implementing high availability (HA). Using managed services like AWS ElastiCache or Azure Cache for Redis makes operations more convenient.
PostgreSQL Store (Alternative): If you’re already using PostgreSQL, you can use PostgreSQL as a session store without a separate Redis. However, performance is lower than Redis.

Session Expiration Strategies

Fixed Expiration: Session expires unconditionally after a set time from creation. High security but may result in poor user experience.
Sliding Expiration: Session expiration time is renewed with each user activity. Suitable for “Remember Me” functionality with good user experience.
Hybrid Strategy: Set short expiration time initially, and apply longer expiration when “Remember Me” is selected.

Session Data Management

Store only minimal information in sessions. Large session size degrades performance and increases storage costs.
Accessing Session Data:

JWT Token Management

How JWT Works

JWT (JSON Web Token) is a stateless authentication method. After the server creates a token, all information is contained within the token itself, so the server doesn’t need to store anything separately. JWT Structure:
  • Header: Token type and algorithm (e.g., {"alg": "HS256", "typ": "JWT"})
  • Payload: User information and claims (e.g., {"userId": 123, "role": "user"})
  • Signature: Signature to verify token integrity
JWT Advantages:
  • Good scalability as server doesn’t store state
  • Suitable for microservice environments
  • No separate lookup needed as information is contained in token itself
JWT Disadvantages:
  • Difficult to forcibly invalidate token from server
  • Token size is larger than cookies
  • If token is stolen, it can be used until expiration

Access Token and Refresh Token

Access Token is a short-lived token used for API requests. Usually has a short validity period of 15 minutes to 1 hour. Even if stolen, damage is minimized. Refresh Token is a long-lived token used to reissue Access Tokens. Usually has a validity period of 7 to 30 days and is stored on the server for management. Why use two tokens? If Access Token validity is set to 30 days:
  • If stolen, it can be abused for 30 days
  • User permission changes are not immediately reflected
With short Access Token and Refresh Token renewal:
  • Stolen Access Token is only valid for a short time
  • Permission changes can be reflected quickly
  • Refresh Token can be stored on server and invalidated
Security Notes: - Must use different secrets for Access Token and Refresh Token - Store Refresh Token on server to enable invalidation - To prevent XSS attacks, store tokens in httpOnly cookies instead of localStorage

Refresh Token Database Schema

Token Refresh Implementation

Refresh Token Rotation is a technique that issues a new Refresh Token each time one is used, enhancing security. Even if a token is stolen, only one of the thief or legitimate user can receive a new token, enabling quick detection of theft.

Token Invalidation (Logout)

JWT is valid until expiration by default, but can be forcibly invalidated using a blacklist.

Token Blacklist Middleware

Practical Patterns

Concurrent Login Restriction

How to restrict concurrent access from multiple devices with one account.

Cleanup Expired Sessions

Periodically delete expired Refresh Tokens to manage database size.

Cautions

Session/Token Management Cautions: 1. Manage Session Secret and JWT Secret via environment variables 2. External session store like Redis is required for production 3. Store Refresh Token in database to enable invalidation 4. Set Access Token short, Refresh Token long 5. Set secure: true only when using HTTPS 6. httpOnly: true is required for XSS prevention 7. Use Redis TTL feature for blacklist

Next Steps

Authentication Setup

Building authentication system

Protected Routes

Permission control with Guards

Context

Learn more about Context

Workflows

Task scheduling