CORS Setup

Configure Cross-Origin Resource Sharing (CORS) to allow your API to be accessed from different domains.

Basic CORS Setup

1. Enable CORS in Environment

Add CORS configuration to your .env file:

# Enable CORS
CORS_ENABLED=true

# Allow specific origins
CORS_ALLOWED_ORIGINS=https://baseapp.com,https://baseapp.dev

# Configure allowed methods and headers
CORS_ALLOWED_METHODS=GET, POST, PUT, DELETE, OPTIONS
CORS_ALLOWED_HEADERS=Content-Type, Authorization, X-Requested-With

# Enable credentials if needed
CORS_ALLOW_CREDENTIALS=true

# Cache preflight for 24 hours
CORS_MAX_AGE=86400

2. Router Handles CORS Automatically

The Router automatically handles CORS when enabled. No additional code needed:

CORS Configuration Examples

Development Setup

Allow localhost and development domains:

Production Setup

Restrict to specific production domains:

Wildcard Subdomain Setup

Allow all subdomains of a domain:

Frontend Integration

JavaScript Fetch API

Axios Configuration

CORS Headers Explained

Response Headers Set by Base

When CORS is enabled, Base automatically sets these headers:

Preflight Request Flow

  1. Browser sends OPTIONS request:

  1. Base responds with CORS headers:

  1. Browser makes actual request:

Security Considerations

Origin Validation

Always specify exact origins in production:

Credentials Handling

Only enable credentials when necessary:

Header Restrictions

Limit allowed headers to what you actually need:

Troubleshooting CORS

Common Issues

  1. CORS not working:

    • Check CORS_ENABLED=true in .env

    • Verify origin is in CORS_ALLOWED_ORIGINS

    • Ensure no trailing slashes in origins

  2. Preflight failing:

    • Check OPTIONS is in CORS_ALLOWED_METHODS

    • Verify all request headers are in CORS_ALLOWED_HEADERS

  3. Credentials not working:

    • Set CORS_ALLOW_CREDENTIALS=true

    • Cannot use wildcard origin with credentials

    • Frontend must set credentials: 'include'

Debug CORS Issues

Add debug logging to see CORS processing:

Browser Developer Tools

Check the Network tab for:

  • Preflight OPTIONS request

  • CORS headers in response

  • Console errors about CORS policy

Testing CORS

Manual Testing with cURL

Test preflight request:

Test actual request:

Automated Testing

Last updated