CORS Configuration for Web APIs

VerifiedSafe

Configure CORS headers, handle preflight requests, and secure cross-origin API access. Covers Express, Next.js, and any HTTP server.

Sby Skills Guide Bot
SecurityIntermediate
8/5/2026
Claude CodeCursorWindsurfCopilotCodex
#cors#http-headers#api-security#browser#preflight

Recommended for

Automated summary

This skill explains how to configure CORS headers for a web API in Express, Next.js, or any HTTP server, including handling of preflight requests.

Strengths

  • Provides complete code samples for Express, Next.js, and a generic manual approach
  • Demonstrates an environment-aware origin whitelist instead of a wildcard
  • Calls out common pitfalls: wildcard with credentials, preflight caching, and cookie SameSite settings

Limitations

  • Examples are JavaScript/TypeScript only, with no coverage of other languages
  • Does not address advanced cases like dynamic multi-tenant origins or proxy/CDN setups
  • Assumes a known list of origins without guidance on managing that configuration
When to use it

Use it when a frontend is blocked by CORS errors or when an API's cross-origin headers need to be tightened up correctly.

When not to use it

Do not use it for server-to-server calls, where CORS does not apply at all.

Security analysis

Safe
Quality score90/100

The skill only provides CORS configuration examples and security guidance. It does not execute commands, access secrets, modify files, or instruct unsafe behavior.

No concerns found

How this analysis is made

Examples

Fix a browser CORS error
My React app on https://myapp.com gets 'blocked by CORS policy' when calling https://api.myapp.com. Configure CORS correctly with Express.
Secure production CORS
Audit my Express CORS setup: it currently uses origin '*' with credentials true. Fix it with a proper origin whitelist.
Next.js API preflight
Add CORS headers to my Next.js API routes so preflight OPTIONS requests are cached 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.0.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()
}

Guidelines

  • NEVER use Access-Control-Allow-Origin: * with credentials: true — browsers reject this.
  • * origin is only safe for truly public APIs with no authentication.
  • Always set Access-Control-Max-Age to cache preflight responses (reduces OPTIONS requests).
  • CORS only applies to browser requests — server-to-server calls ignore CORS entirely.
  • If using cookies across domains, also set SameSite=None; Secure on cookies.

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 files

This 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.md

From the root of a test project, save the file as .skill-downloads/cors-configuration-for-web-apis-msfn1979/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/cors-configuration-for-web-apis-msfn1979' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/cors-configuration-for-web-apis-msfn1979/download' --output '.skill-downloads/cors-configuration-for-web-apis-msfn1979/SKILL.md.part' && mv '.skill-downloads/cors-configuration-for-web-apis-msfn1979/SKILL.md.part' '.skill-downloads/cors-configuration-for-web-apis-msfn1979/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/cors-configuration-for-web-apis-msfn1979/SKILL.md' && test -s '.skill-downloads/cors-configuration-for-web-apis-msfn1979/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/cors' && cp -R '.skill-downloads/cors-configuration-for-web-apis-msfn1979' '.claude/skills/cors'

Cursor
test -f '.skill-downloads/cors-configuration-for-web-apis-msfn1979/SKILL.md' && test -s '.skill-downloads/cors-configuration-for-web-apis-msfn1979/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/cors' && cp -R '.skill-downloads/cors-configuration-for-web-apis-msfn1979' '.cursor/skills/cors'

Codex
test -f '.skill-downloads/cors-configuration-for-web-apis-msfn1979/SKILL.md' && test -s '.skill-downloads/cors-configuration-for-web-apis-msfn1979/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/cors' && cp -R '.skill-downloads/cors-configuration-for-web-apis-msfn1979' '.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 installation
openskills install './.skill-downloads/cors-configuration-for-web-apis-msfn1979'

openskills read 'cors-configuration-for-web-apis-msfn1979'

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 sync

Manual 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/cors-configuration-for-web-apis-msfn1979/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.

Related skills