ScreenshotNeo

BlogHow-to

How to Fix CORS Errors in Puppeteer

Diagnose Puppeteer CORS failures, fix preflight and credentials correctly, and choose safe server, proxy, or request-level solutions.

By the ScreenshotNeo team30 September 20269 min read

How to Fix CORS Errors in Puppeteer

Short answer: Puppeteer does not have a special CORS permission. The page runs inside Chromium, so Chromium applies the same cross-origin rules that affect a normal browser page. Find the exact failed request, inspect its console and Network details, then fix the API response—especially the Access-Control-Allow-Origin header and, for preflighted requests, the OPTIONS response. Puppeteer can shape outgoing requests, but it cannot grant a server permission to expose a response.

The reliable order is:

  1. Reproduce the error with Chromium DevTools information available.
  2. Identify whether the request is simple or preflighted.
  3. Check whether cookies or other credentials are involved.
  4. Correct the server’s CORS response.
  5. Use Puppeteer’s headers or interception APIs only for request-level behavior.
  6. If you do not control the API, call it through a proxy you operate.

This guide covers browser-page requests made by scripts running in Puppeteer. A Node.js request made outside the page, such as fetch() in your test process, is not subject to browser CORS; it still needs normal authentication, TLS, DNS, and server-side access controls.

What the CORS error means

Cross-Origin Resource Sharing (CORS) is a browser protocol. A page has an origin made from its scheme, host, and port. If JavaScript at https://app.example reads a response from https://api.example, the API must explicitly allow that requesting origin. The browser sends the request, but it hides the response from page JavaScript unless the response headers authorize the read.

Open Chromium’s console and Network panel and record:

  • the page origin and request URL;
  • the method and status;
  • request headers, especially Origin, authorization, cookies, and custom headers;
  • response headers;
  • whether an OPTIONS request happened first; and
  • the exact console wording, such as a missing or mismatched Access-Control-Allow-Origin.

MDN’s CORS error guidance explains that most CORS errors can only be resolved on the server because the server controls whether cross-origin access is allowed. The visible failure may mention the final GET, but the actual defect can be an unhandled preflight.

Diagnose the failing request in Puppeteer

Use a visible browser while diagnosing. Headless mode follows the same CORS policy, but a visible window makes DevTools inspection easier.

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch({ headless: false });
const page = await browser.newPage();

page.on('console', message => {
  console.log(`[browser:${message.type()}] ${message.text()}`);
});

page.on('requestfailed', request => {
  console.log('request failed', request.url(), request.failure());
});

page.on('response', async response => {
  const request = response.request();
  if (request.url().includes('/api/')) {
    console.log('API response', response.status(), request.method(), request.url());
    console.log('response headers', response.headers());
  }
});

await page.goto('https://app.example', { waitUntil: 'networkidle2' });
// Keep the browser open while inspecting the Network panel.
// await browser.close();

Do not infer a CORS problem from a generic net::ERR_FAILED alone. A DNS failure, certificate error, blocked mixed-content request, server 5xx response, or a page JavaScript exception can look similar. The console’s CORS reason and the request’s headers are the evidence you need.

Simple requests versus preflighted requests

A simple cross-origin request can be sent without a preflight when its method and headers fit the browser’s safelist. A preflight is commonly triggered by methods such as PUT, PATCH, or DELETE, by custom headers such as X-API-Key, or by a non-safelisted content type such as JSON.

A preflight checks the method and headers before the browser exposes the response to page code.
A preflight checks the method and headers before the browser exposes the response to page code.

For a preflighted request, the browser sends an OPTIONS request containing headers such as:

Origin: https://app.example
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type, x-api-key

The server must answer that OPTIONS request with values covering the actual request:

HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example
Access-Control-Allow-Methods: POST, OPTIONS
Access-Control-Allow-Headers: content-type, x-api-key
Vary: Origin

The exact method and header names must match your contract. Fixing only the POST response while the OPTIONS route returns 404, a redirect, or missing headers leaves the browser blocked.

Fix the API response

Public, anonymous endpoint

For a genuinely public endpoint that does not use credentials, the server may return:

Access-Control-Allow-Origin: *

This allows any origin to read the response. It does not make a private endpoint safe; authentication and authorization still belong on the server.

Allowlisted application with credentials

If the page sends cookies, client certificates, or other credentials, the response must name the requesting origin. A wildcard is incompatible with a credentialed read.

Access-Control-Allow-Origin: https://app.example
Access-Control-Allow-Credentials: true
Vary: Origin

When selecting an origin dynamically, compare the incoming Origin against a fixed allowlist. Never blindly reflect arbitrary origins. Add Vary: Origin so a cache does not reuse one origin’s response for another.

Example Express middleware

import express from 'express';

const app = express();
const allowedOrigins = new Set([
  'https://app.example',
  'https://staging.app.example'
]);

app.use((req, res, next) => {
  const origin = req.get('Origin');
  if (origin && allowedOrigins.has(origin)) {
    res.set('Access-Control-Allow-Origin', origin);
    res.set('Vary', 'Origin');
    res.set('Access-Control-Allow-Credentials', 'true');
    res.set('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
    res.set('Access-Control-Allow-Headers', 'Content-Type, X-API-Key');
  }
  if (req.method === 'OPTIONS') return res.sendStatus(204);
  next();
});

app.get('/api/data', (req, res) => res.json({ ok: true }));
app.listen(3000);

Place the OPTIONS handling before authentication middleware that rejects an unauthenticated preflight. A preflight generally does not include the same credentials as the eventual request.

Use Puppeteer APIs for request shaping

page.setExtraHTTPHeaders() adds headers to every request initiated by the page. Puppeteer’s documentation describes these as extra headers sent with every page request. This can satisfy an API’s authentication requirement, but it does not create a CORS grant.

await page.setExtraHTTPHeaders({
  'x-api-key': process.env.API_KEY
});

If the new header makes the request preflighted, the API must list x-api-key in Access-Control-Allow-Headers. Do not add Access-Control-Allow-Origin as a request header. That is a response header supplied by the server.

Intercept, continue, abort, or respond

await page.setRequestInterception(true);
page.on('request', request => {
  if (request.isInterceptResolutionHandled()) return;

  if (request.url().includes('/telemetry')) {
    return request.abort();
  }

  return request.continue({
    headers: {
      ...request.headers(),
      'x-test-run': 'puppeteer'
    }
  });
});

Every intercepted request must be completed with continue(), abort(), or respond(). Interception is useful for test fixtures, blocking unwanted resources, and adding request metadata. It cannot override the remote server’s response policy.

Credentials, cookies, and origin details

Set the page’s cookie and authentication state deliberately. A request that unexpectedly includes a cookie changes the CORS requirements.

await page.setCookie({
  name: 'session',
  value: process.env.SESSION_COOKIE,
  domain: 'app.example',
  path: '/',
  secure: true,
  httpOnly: true
});

await page.goto('https://app.example');

Check whether the page uses fetch(..., { credentials: 'include' }) or XMLHttpRequest with credentials enabled. The server must return Access-Control-Allow-Credentials: true and a specific allowed origin. Also verify that cookie SameSite, Secure, and domain attributes permit the request; a cookie that is not sent is a cookie problem, while a sent cookie combined with * is a CORS problem.

When you cannot change the API: use a controlled proxy

If the remote server does not include Access-Control-Allow-Origin, MDN notes that you cannot fix the error on that server side. Put a server you control between the page and the remote API. Your proxy makes the server-to-server request, validates the target and caller, then returns a carefully designed response with your own CORS policy.

import express from 'express';

const app = express();
app.use(express.json());

app.get('/proxy/data', async (req, res) => {
  const target = new URL('https://remote.example/data');
  // Authenticate the caller and validate any user-supplied parameters.
  const upstream = await fetch(target, {
    headers: { Authorization: `Bearer ${process.env.REMOTE_TOKEN}` }
  });

  const body = await upstream.text();
  res.status(upstream.status);
  res.type(upstream.headers.get('content-type') || 'text/plain');
  res.set('Access-Control-Allow-Origin', 'https://app.example');
  res.set('Vary', 'Origin');
  res.send(body);
});

app.listen(8080);

Restrict destinations, authenticate callers, apply rate limits, cap response sizes, and avoid an open proxy. If the proxy accepts an arbitrary URL and fetches it, attackers can use it to reach internal services.

Why no-cors usually does not fix Puppeteer

mode: 'no-cors' can allow a limited request to be sent, but the browser returns an opaque response. Page JavaScript cannot read its body or most headers, so parsing JSON, checking an application status, or reading a token fails by design.

const response = await fetch('https://public.example/pixel', {
  mode: 'no-cors'
});
console.log(response.type); // opaque
// response.json() is not available for useful application data

Use this only when you need a write-like side effect or a resource whose response is intentionally unread. It is not a solution for an API that your script must inspect.

Common errors and fixes

Symptom Cause Fix
Missing Access-Control-Allow-Origin The API response does not authorize the page origin. Add a narrow allowlist or * for a public anonymous endpoint.
Wildcard with credentials * cannot authorize a credentialed read. Return the exact origin, Access-Control-Allow-Credentials: true, and Vary: Origin.
OPTIONS returns 404 or 401 The preflight route is missing or protected by normal authentication. Handle OPTIONS early and return allowed methods and headers.
Method not allowed The requested method is absent from Access-Control-Allow-Methods. List the actual method, such as POST, in the preflight response.
Request header not allowed A custom header triggered preflight but is not listed. Add its lowercase name to Access-Control-Allow-Headers, or remove the header if unnecessary.
Added allow-origin in Puppeteer The permission belongs in the response, not the request. Configure the API or use a controlled proxy.
no-cors response cannot be parsed The response is intentionally opaque. Use a server-side proxy or fix CORS on the API.
Interception hangs navigation An intercepted request was never resolved. Call exactly one of continue, abort, or respond for every request.
Works in Node, fails in page Node is not enforcing browser CORS; Chromium is. Fix the browser-visible API response or move the call to your backend.

Performance, reliability, and security considerations

  • Reduce preflights where appropriate: Avoid unnecessary custom headers and non-safelisted content types, but never remove authentication or integrity controls merely to avoid OPTIONS.
  • Cache safely: If the response varies by origin, send Vary: Origin. Set an explicit preflight cache lifetime with Access-Control-Max-Age only when your deployment can tolerate delayed policy changes.
  • Keep retries bounded: Retry transient upstream failures in your proxy with timeouts and a small limit. Do not retry authorization failures or malformed requests.
  • Observe both legs: Log the browser request and proxy-to-upstream response separately, with secrets redacted. Record OPTIONS status, allowed origin, and allowed headers.
  • Protect credentials: Do not expose service tokens through page JavaScript or broad extra headers. Scope cookies and API keys to the smallest audience.
  • Do not weaken Chromium globally: Browser extensions and launch flags that disable web security weaken isolation and are unsuitable production fixes.

Or skip the browser setup

If your goal is to capture a page rather than run a browser test, ScreenshotNeo handles the capture server side. Its API accepts one GET request and returns PNG, JPEG, WebP, or PDF. See the ScreenshotNeo documentation for all options.

ScreenshotNeo removes common consent banners, popups, and chat widgets before capture.
ScreenshotNeo removes common consent banners, popups, and chat widgets before capture.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Before the capture, cookie and consent banners are accepted and removed, along with more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing status. ScreenshotNeo also provides an MCP server so Claude, Cursor, and other MCP clients can use take_screenshot, get_page_info, and capture_pdf. The Free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Frequently asked questions

Does Puppeteer bypass CORS?

No. Page JavaScript runs under Chromium’s browser security model. A server response or controlled proxy must authorize the read.

Should I use --disable-web-security?

No for production. It weakens the browser’s isolation and hides the configuration problem. Fix the API or proxy instead.

Can adding an API key with setExtraHTTPHeaders() solve CORS?

It can authenticate the request, but it cannot authorize the response. The server must allow the page origin and the custom header during preflight.

Why does a request work with curl but fail in Puppeteer?

curl is not a browser and does not enforce CORS. Compare the browser’s Origin, preflight, credentials, and response headers with the curl request.

Is a proxy always necessary?

No. If you control the API, correct its CORS policy directly. Use a proxy when the remote API cannot be changed and your application needs to read its response.

How do I tell whether the issue is CORS or a server failure?

Inspect the Network entry and console together. A CORS error includes a cross-origin policy reason; a 5xx, DNS error, TLS error, or timeout needs its own server or connectivity fix.