Security Middleware
CSRF Protection
Protect your application against Cross-Site Request Forgery (CSRF) attacks with built-in token validation and secure cookie handling.
Basic CSRF Protection
MoroJS provides built-in CSRF protection middleware that automatically validates CSRF tokens for state-changing requests.
Enable CSRF Protection
typescript
How CSRF Protection Works
- Generates a unique CSRF token for each session
- Stores token in secure, httpOnly cookie
- Validates token on state-changing requests (POST, PUT, DELETE, PATCH)
- Ignores safe methods (GET, HEAD, OPTIONS)
- Returns 403 Forbidden if token is missing or invalid
Advanced Configuration
Custom CSRF Configuration
typescript
Client-Side Integration
Fetching and Using CSRF Token
typescript
Best Practices
Do
- Enable CSRF for all state-changing requests
- Use httpOnly cookies for token storage
- Set secure flag in production
- Use sameSite: 'strict' for maximum security
- Validate token on server-side
- Regenerate token after use for sensitive operations
Don't
- Disable CSRF for state-changing requests
- Store CSRF token in localStorage or sessionStorage
- Skip CSRF validation for sensitive endpoints
- Use predictable or static tokens
- Trust client-side validation only
- Expose CSRF token in error messages