Verify Authentication Middleware
The Verify Authentication Middleware protects private routes by validating user authentication using JWT access tokens and refresh tokens.
How Authentication Works
The middleware follows this sequence:
- Read
accessTokenandrefreshTokenfrom cookies - If access token is valid → allow request
- If access token is expired:
- Verify refresh token
- Validate user existence
- Issue new access & refresh tokens
- Set new cookies automatically
- If all checks fail → reject the request
This ensures seamless token rotation without forcing the user to re-login.
Installation Guide
npx servercn-cli add verify-auth-middlewarePrerequisites
Ensure the following environment variables are defined in .env:
Ensure the following configuration are defined:
To ensure the authentication middleware functions correctly, your project must define a User model with a structure similar to the following.
To access authenticated user data inside request handlers, define a custom request type.
Basic Implementation
Usage Example
Error Responses
Authentication failures return standardized responses: