Automated summary
This skill explains how to configure CORS headers for web APIs, with ready-to-use examples for Express, Next.js, and a framework-agnostic middleware.
Strengths
- Three concrete recipes covering Express, Next.js API routes, and a portable middleware for any HTTP server.
- Explicit handling of OPTIONS preflight with a 204 response and preflight caching via maxAge, a step that is often missed.
- Origin whitelist through a callback, with support for requests lacking an Origin header and a dev/prod split.
- Correct debugging advice: inspect the OPTIONS request in the Network tab rather than only the follow-up request.
Limitations
- Examples are TypeScript/JavaScript only: no Fastify variant despite the stated compatibility, and nothing for nginx or API gateways.
- Skips common pitfalls such as the Vary: Origin header, the incompatibility of the '*' wildcard with credentials, and per-subdomain dynamic origins.
- Assumes a known static origin list; multi-tenant or subdomain-based allowlisting is not covered.
Use it when a CORS error blocks a frontend, or when you need to add or tighten the CORS configuration of an HTTP API.
Avoid it for non-browser flows (mTLS, server-to-server OAuth) or for proxy/CDN-level configuration that never touches application code.
Security analysis
SafeThis is a documentation-only skill: it contains CORS configuration snippets for Express, Next.js, and generic HTTP middleware, with no commands executed, no network calls, no file writes, and no credential handling. The guidance is security-positive (avoid wildcard origin with credentials, whitelist origins, note that CORS is browser-enforced). The closest thing to a risk is that the Express snippet reflects the request origin after validation and the manual middleware omits a `Vary: Origin` header, which are correctness/caching concerns rather than a listing risk. No prompt-injection or instruction-manipulation attempts are present in the content.
No concerns found
How this analysis is madeExamples
Our React app on app.billing-portal.io is blocked when it calls our Express API in production — the browser shows a CORS error. Configure the Express CORS middleware with that origin whitelisted and credentials enabled for our auth cookie.My Next.js API route under /api works in Postman but fails in the browser with a preflight error. Set up the CORS headers in next.config.ts for our single production origin and explain why Postman works.Our Node HTTP server isn't Express or Next.js. Write a middleware that allows https://myapp.com and https://admin.myapp.com, handles OPTIONS preflight with a 204, and caches it for 24 hours.name: cors description: >- Configure CORS for web APIs. Use when a user asks to fix CORS errors, allow cross-origin requests, configure CORS headers, handle preflight requests, or secure API access from different domains. license: Apache-2.0 compatibility: 'Express, Fastify, Next.js, any HTTP server' metadata: author: terminal-skills version: 1.1.0 category: devops tags: "cors, security, headers, api, browser"
CORS (Cross-Origin Resource Sharing)
Overview
CORS controls which websites can call your API from a browser. Without proper CORS headers, browsers block cross-origin requests. Misconfigured CORS is either too restrictive (breaks your frontend) or too permissive (security risk). This skill covers correct configuration for common setups.
Instructions
Step 1: Express
// server.ts — CORS configuration for Express
import cors from 'cors'
import express from 'express'
const app = express()
// Production: whitelist specific origins
const allowedOrigins = [
'https://myapp.com',
'https://admin.myapp.com',
process.env.NODE_ENV === 'development' && 'http://localhost:3000',
].filter(Boolean) as string[]
app.use(cors({
origin: (origin, callback) => {
// Allow requests with no origin (mobile apps, curl, server-to-server)
if (!origin) return callback(null, true)
if (allowedOrigins.includes(origin)) return callback(null, true)
callback(new Error(`Origin ${origin} not allowed by CORS`))
},
credentials: true, // allow cookies/auth headers
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
maxAge: 86400, // cache preflight for 24h
}))
Step 2: Next.js API Routes
// next.config.ts — CORS via Next.js headers
const nextConfig = {
async headers() {
return [
{
source: '/api/:path*',
headers: [
{ key: 'Access-Control-Allow-Origin', value: 'https://myapp.com' },
{ key: 'Access-Control-Allow-Methods', value: 'GET,POST,PUT,DELETE,OPTIONS' },
{ key: 'Access-Control-Allow-Headers', value: 'Content-Type, Authorization' },
{ key: 'Access-Control-Allow-Credentials', value: 'true' },
{ key: 'Access-Control-Max-Age', value: '86400' },
],
},
]
},
}
Step 3: Manual Headers (Any Framework)
// middleware.ts — Manual CORS for any HTTP server
export function corsMiddleware(req, res, next) {
const origin = req.headers.origin
const allowed = ['https://myapp.com', 'https://admin.myapp.com']
if (allowed.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin)
res.setHeader('Access-Control-Allow-Credentials', 'true')
}
// Handle preflight (OPTIONS) requests
if (req.method === 'OPTIONS') {
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE')
res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization')
res.setHeader('Access-Control-Max-Age', '86400')
return res.status(204).end()
}
next()
}
Examples
Example 1: "Our React app on app.billing-portal.io gets blocked calling our Express API"
Add the Express middleware from Step 1 with app.billing-portal.io in allowedOrigins, keep credentials: true since the app sends an auth cookie, and confirm the browser's preflight OPTIONS request now returns 204 with the right Access-Control-Allow-* headers (check the Network tab, not just the follow-up GET/POST).
Example 2: "A Next.js API route works in Postman but not from the browser"
Postman does not send an Origin header, so it skips CORS entirely — that it works there proves nothing about the browser case. Use the next.config.ts headers() block from Step 2 if one static origin is always correct; headers() values are fixed per build, like vercel.json, so if the allowed origin needs to vary per request (a whitelist, a wildcard subdomain), set the headers in middleware instead, mirroring Step 3.
Guidelines
- NEVER use
Access-Control-Allow-Origin: *withcredentials: true— browsers reject this combination outright. *origin is only safe for truly public APIs with no authentication and no cookies.- Always set
Access-Control-Max-Ageto cache preflight responses (reduces repeatOPTIONSrequests). - CORS is enforced by the browser, not the server — server-to-server calls, curl and Postman ignore it, so testing from those tools cannot confirm a browser-facing fix.
- If using cookies across domains, also set
SameSite=None; Secureon the cookie, andcredentials: true/Access-Control-Allow-Credentials: trueon both sides. next.config.js/next.config.tsheaders()values are static at build time; use middleware when the allowed origin must be computed per request.
From the file to a first result
The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.
View the source and supporting filesThis download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.
1. Download the file
Download SKILL.mdFrom the root of a test project, save the file as .skill-downloads/configure-cors-for-web-apis-mwirmdvd/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.
Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.
mkdir -p '.skill-downloads/configure-cors-for-web-apis-mwirmdvd' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/configure-cors-for-web-apis-mwirmdvd/download' --output '.skill-downloads/configure-cors-for-web-apis-mwirmdvd/SKILL.md.part' && mv '.skill-downloads/configure-cors-for-web-apis-mwirmdvd/SKILL.md.part' '.skill-downloads/configure-cors-for-web-apis-mwirmdvd/SKILL.md'2. Check prerequisites
Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.
Environment declared by the author: Express, Fastify, Next.js, any HTTP server
No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.
The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.
3. Load the skill
After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.
Claude Code
test -f '.skill-downloads/configure-cors-for-web-apis-mwirmdvd/SKILL.md' && test -s '.skill-downloads/configure-cors-for-web-apis-mwirmdvd/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/cors' && cp -R '.skill-downloads/configure-cors-for-web-apis-mwirmdvd' '.claude/skills/cors'Cursor
test -f '.skill-downloads/configure-cors-for-web-apis-mwirmdvd/SKILL.md' && test -s '.skill-downloads/configure-cors-for-web-apis-mwirmdvd/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/cors' && cp -R '.skill-downloads/configure-cors-for-web-apis-mwirmdvd' '.cursor/skills/cors'Codex
test -f '.skill-downloads/configure-cors-for-web-apis-mwirmdvd/SKILL.md' && test -s '.skill-downloads/configure-cors-for-web-apis-mwirmdvd/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/cors' && cp -R '.skill-downloads/configure-cors-for-web-apis-mwirmdvd' '.agents/skills/cors'OpenSkills
OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.
Official OpenSkills installationopenskills install './.skill-downloads/configure-cors-for-web-apis-mwirmdvd'openskills read 'configure-cors-for-web-apis-mwirmdvd'Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.
For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.
openskills syncManual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.
4. Try a first task
Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:
Read .skill-downloads/configure-cors-for-web-apis-mwirmdvd/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.
Configure a Chat Channel with SecretRefs
DevOps
Set up chat channels using non-interactive commands, with secrets only as SecretRefs. Covers gather, mutate, repair, and prove steps for reliable delivery.
Investigate ClickHouse CI Failures
DevOps
Investigate a ClickHouse CI failure end-to-end from a PR or S3 report URL. Fetches failed tests, classifies flaky vs real regression, and checks for existing issues/fixes.
Ansible PR Review
DevOps
Reviews an Ansible PR following the project's standardized process, including changelog checks, test coverage validation, and feedback tracking.