mediumCWE-942A05:2021

Open CORS in Next.js API Routes

Next.js API routes configured with Access-Control-Allow-Origin: * allow any website to make authenticated cross-origin requests, enabling CSRF-like attacks.

How It Works

When API routes set Access-Control-Allow-Origin to *, any website can make requests to your API from the user's browser. If the API also allows credentials (cookies), an attacker's website can make authenticated requests on behalf of logged-in users. This enables cross-site data theft: the attacker hosts a malicious page that fetches data from your API using the victim's session cookies. Even without credentials, open CORS exposes API responses to any origin, leaking data that should only be accessible from your frontend.

Vulnerable Code
// pages/api/user/profile.ts
export default function handler(req, res) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.setHeader('Access-Control-Allow-Headers', '*');
  const user = await getUser(req);
  res.json(user);
}
Secure Code
// pages/api/user/profile.ts
const ALLOWED_ORIGINS = [process.env.NEXT_PUBLIC_APP_URL];

export default function handler(req, res) {
  const origin = req.headers.origin;
  if (ALLOWED_ORIGINS.includes(origin)) {
    res.setHeader('Access-Control-Allow-Origin', origin);
    res.setHeader('Access-Control-Allow-Credentials', 'true');
  }
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  const user = await getUser(req);
  res.json(user);
}

Real-World Example

In 2019, a misconfigured CORS policy on a banking API allowed researchers to demonstrate cross-origin data exfiltration of account balances and transaction history by hosting a proof-of-concept page on an attacker-controlled domain.

How to Prevent It

  • Never use Access-Control-Allow-Origin: * on authenticated API routes
  • Validate the Origin header against an allowlist of trusted domains
  • Avoid Access-Control-Allow-Credentials: true with wildcard origins
  • Use Next.js middleware to centralize CORS configuration

Affected Technologies

ReactNext.jsNode.js

Data Hogo detects this vulnerability automatically.

Scan Your Repo Free

Related Vulnerabilities