Configure CORS properly for different environments
✓Works with OpenClaudeYou are a backend API security expert. The user wants to configure CORS (Cross-Origin Resource Sharing) correctly for development, staging, and production environments.
What to check first
- Check your current framework:
npm list expressornpm list fastify(or equivalent for your stack) - Review your current server file to identify where middleware is initialized
- List your environment variables:
echo $NODE_ENVor check your.envfile
Steps
- Install the CORS middleware package:
npm install corsfor Express/Node, or check if your framework has built-in CORS support - Identify your environment configuration file (usually
config.js,.env, orenvironment.ts) - Define allowed origins as an array based on
NODE_ENV: development getslocalhost:3000, staging gets your staging domain, production gets only your production domain - Create a CORS options object with
origin,credentials,methods, andallowedHeadersproperties matching your environment - Apply the CORS middleware to your Express app using
app.use(cors(corsOptions))before route definitions - For preflight requests, ensure
OPTIONSmethod is handled by addingapp.options('*', cors(corsOptions)) - Test with
curl -H "Origin: http://localhost:3000" -H "Access-Control-Request-Method: POST" -X OPTIONS http://localhost:3001to verify preflight - Verify response headers include
Access-Control-Allow-Origin,Access-Control-Allow-Methods, andAccess-Control-Allow-Credentials
Code
const express = require('express');
const cors = require('cors');
const app = express();
// Environment-based CORS configuration
const corsConfig = {
development: {
origin: ['http://localhost:3000', 'http://localhost:3001'],
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
maxAge: 3600,
},
staging: {
origin: ['https://staging.example.com', 'https://api-staging.example.com'],
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
maxAge: 86400,
},
production: {
origin: 'https://example.com',
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
allowedHeaders: ['Content-Type', 'Authorization'],
maxAge: 86400,
},
};
// Select config based on NODE_ENV
const env = process.env.NODE_ENV || 'development';
const corsOptions = corsConfig[env];
// Apply CORS
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Not validating request bodies before processing — attackers will send malformed payloads to crash your service
- Returning detailed error messages in production — leaks internal architecture to attackers
- Forgetting CORS headers — frontend will silently fail with cryptic browser errors
- Hardcoding API keys in code — use environment variables and secret management
- No rate limiting — one client can DoS your entire API
When NOT to Use This Skill
- When a single shared library would suffice — APIs add network latency and failure modes
- For internal-only data flow within the same process — use direct function calls
- When you need transactional consistency across services — APIs can't guarantee this without distributed transactions
How to Verify It Worked
- Test all CRUD operations end-to-end including error cases (404, 401, 403, 500)
- Run an OWASP ZAP scan against your API — catches common security issues automatically
- Load test with k6 or Artillery — verify your API holds up under realistic traffic
- Verify rate limits actually trigger when exceeded — they often don't due to misconfiguration
Production Considerations
- Version your API from day one (
/v1/) — breaking changes are inevitable, give yourself a path - Set request size limits — prevents memory exhaustion attacks
- Add structured logging with request IDs — trace every request across your stack
- Document your API with OpenAPI — generates client SDKs and interactive docs for free
Related API Development Skills
Other Claude Code skills in the same category — free to download.
REST API Scaffold
Scaffold a complete REST API with CRUD operations
GraphQL Schema Generator
Generate GraphQL schema from existing data models
API Documentation
Generate OpenAPI/Swagger documentation from code
API Versioning
Implement API versioning strategy
Rate Limiter
Add rate limiting to API endpoints
API Error Handler
Create standardized API error handling
Request Validator
Add request validation middleware (Zod, Joi)
API Response Formatter
Standardize API response format
Want a API Development skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.