Overview
Thecors2 middleware provides enhanced Cross-Origin Resource Sharing handling with additional features like pattern-based origin matching, preflight response caching, and more granular control.
Use it when you need:
- Wildcard subdomain matching
- Advanced preflight caching
- More control over CORS behavior
Installation
Quick Start
Configuration
Options
Examples
Wildcard Subdomains
Combined Exact and Pattern
Full Configuration
API Reference
Functions
Pattern Syntax
*matches any sequence of charactershttps://*.example.commatcheshttps://app.example.com,https://api.example.com- Patterns are matched against the full origin including protocol
Technical Details
Implementation Overview
The cors2 middleware implements a simplified CORS handling mechanism with the following key components: Origin Matching:- Supports wildcard (
*) for all origins - Implements exact origin matching with case-insensitive comparison
- The
matchOriginfunction handles both wildcard and exact match scenarios
- Sets
Access-Control-Allow-Originbased on the request origin and configured options - Conditionally sets
Access-Control-Allow-Credentialswhen credentials are enabled - Applies
Access-Control-Expose-Headersfor custom headers that should be exposed to the browser
- Detects OPTIONS requests for preflight handling
- Responds with
Access-Control-Allow-MethodsandAccess-Control-Allow-Headers - Sets
Access-Control-Max-Ageto cache preflight responses (when configured) - Returns HTTP 204 (No Content) for preflight requests
- Origin:
*(all origins) - Methods:
GET, POST, PUT, DELETE, OPTIONS - Headers:
Content-Type, Authorization - Credentials:
false - MaxAge:
0(no caching)
Helper Functions
The middleware provides convenience functions:New(): Creates middleware with default settingsWithOptions(opts): Creates middleware with custom configurationAllowOrigin(origin): Quick setup for a specific originAllowAll(): Permissive setup with extended methods and headersAllowCredentials(origin): Enables credentials for a specific origin
Best Practices
- Use exact origins when possible for security
- Use patterns only for known subdomain structures
- Set appropriate MaxAge to reduce preflight requests
- Be cautious with credentials and wildcards