Verify Authentication Middleware
The Verify Authentication Middleware protects private routes by validating user authentication using JWT access tokens and refresh tokens.
It automatically:
- Verifies access tokens from cookies
- Refreshes expired access tokens using refresh tokens
- Re-attaches authenticated user data to the request
- Responds with standardized API errors when authentication fails
This middleware is designed for secure, session-like authentication in REST APIs.
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:
MVC: src/configs/env.ts
Feature: src/shared/configs/env.ts
To ensure the authentication middleware functions correctly, your project must define a User model with a structure similar to the following.
MVC: src/models/user.model.ts
Feature: src/shared/modules/user/user.model.ts
To access authenticated user data inside request handlers, define a custom request type.
src/types/user.ts
Basic Implementation
1. MVC Structure
src/middlewares/verify-auth.ts
2. Feature Structure
src/shared/middlewares/verify-auth.ts
Usage Example
src/routes/user.routes.ts
Error Responses
Authentication failures return standardized responses: