Electron makes CORS weird in a very specific way: you’re building a desktop app, but a big chunk of your UI still runs inside Chromium. That means you get browser security rules in places you might not expect, and Node-style power in places you definitely need to treat carefully.

I’ve seen a lot of Electron apps “solve” CORS by disabling web security or turning on nodeIntegration everywhere. That works right up until you ship something that can load remote content, gets XSS’d, and suddenly your desktop app becomes a local file and credential exfiltration machine.

The better approach is to understand where CORS actually applies in Electron, and choose the right network path for each use case.

The short version

In Electron, CORS usually matters when:

  • your renderer uses fetch() or XMLHttpRequest
  • your app loads remote web content
  • your app embeds third-party pages in BrowserWindow or webview

CORS usually does not matter the same way when:

  • the main process makes HTTP requests with Node.js APIs
  • you proxy requests through your own backend
  • you use privileged app architecture to avoid direct cross-origin browser requests

That distinction is the whole game.

Why Electron still enforces CORS

Electron uses Chromium for renderer processes. If your renderer executes:

fetch('https://api.example.com/data')

Chromium applies the same-origin policy and CORS checks just like Chrome would.

So if your app UI is loaded from:

  • file://...
  • http://localhost:3000
  • app://my-app
  • https://your-app.example

…and it requests another origin, the server still needs to allow it with the right CORS headers.

A successful CORS response often looks like this:

Access-Control-Allow-Origin: https://your-app.example

Or sometimes:

Access-Control-Allow-Origin: *

For example, api.github.com returns:

access-control-allow-origin: *
access-control-expose-headers: ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Used, X-RateLimit-Resource, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type, X-GitHub-SSO, X-GitHub-Request-Id, Deprecation, Sunset, Warning

That second header matters more than many people realize. Without Access-Control-Expose-Headers, your renderer JavaScript can’t read most custom response headers even if the request itself succeeds.

A basic renderer example

Here’s a preload-safe pattern using contextBridge to expose a small API to the renderer.

main.js

const { app, BrowserWindow } = require('electron');
const path = require('path');

function createWindow() {
  const win = new BrowserWindow({
    width: 1000,
    height: 700,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
      nodeIntegration: false,
      sandbox: true
    }
  });

  win.loadFile('index.html');
}

app.whenReady().then(createWindow);

preload.js

const { contextBridge } = require('electron');

contextBridge.exposeInMainWorld('api', {
  getGitHubRoot: async () => {
    const res = await fetch('https://api.github.com/');
    const data = await res.json();

    return {
      ok: res.ok,
      status: res.status,
      allowOrigin: res.headers.get('access-control-allow-origin'),
      rateLimit: res.headers.get('x-ratelimit-limit'),
      requestId: res.headers.get('x-github-request-id'),
      data
    };
  }
});

index.html

<!doctype html>
<html>
  <body>
    <button id="load">Load GitHub API</button>
    <pre id="output"></pre>

    <script>
      document.getElementById('load').addEventListener('click', async () => {
        try {
          const result = await window.api.getGitHubRoot();
          document.getElementById('output').textContent =
            JSON.stringify(result, null, 2);
        } catch (err) {
          document.getElementById('output').textContent = err.message;
        }
      });
    </script>
  </body>
</html>

This works because GitHub allows cross-origin access with access-control-allow-origin: *, and exposes headers like X-RateLimit-Limit via access-control-expose-headers.

If the API did not expose those headers, res.headers.get('x-ratelimit-limit') would return null even though DevTools might show the header exists on the wire.

Preflight in Electron works like the browser

If your renderer sends non-simple requests, Chromium sends an OPTIONS preflight first.

Typical triggers:

  • Content-Type: application/json
  • Authorization header
  • PUT, PATCH, DELETE
  • custom headers like X-Client-Version

Example:

await fetch('https://api.example.com/profile', {
  method: 'PATCH',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer token123'
  },
  body: JSON.stringify({ displayName: 'Ada' })
});

The server must answer the preflight with something like:

Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Methods: PATCH, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization

If it doesn’t, your Electron renderer fails exactly like a browser tab would.

The file:// origin trap

A lot of Electron apps start by loading local HTML files. That means your renderer origin may be file://, which behaves awkwardly with many servers. Some backends don’t expect it. Some CORS middleware won’t match it cleanly. Some setups treat it as a null origin in certain flows.

If your renderer is making lots of authenticated API calls, I prefer one of these patterns:

  1. load the UI from a local dev/prod HTTP origin
  2. use a custom app protocol
  3. move network calls into the main process and expose only narrow IPC methods

That third option is usually the least painful.

The safest pattern: do API calls in the main process

Node.js HTTP requests in the main process are not governed by browser CORS rules in the same way, because they’re not renderer-originated web requests.

That makes the main process a good place to talk to strict APIs. But don’t just dump raw request capability into the renderer. Wrap specific actions.

main.js

const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');

ipcMain.handle('github:get-user', async (_event, username) => {
  const res = await fetch(`https://api.github.com/users/${encodeURIComponent(username)}`, {
    headers: {
      'User-Agent': 'my-electron-app'
    }
  });

  if (!res.ok) {
    throw new Error(`GitHub API failed: ${res.status}`);
  }

  const data = await res.json();

  return {
    login: data.login,
    id: data.id,
    public_repos: data.public_repos
  };
});

function createWindow() {
  const win = new BrowserWindow({
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
      nodeIntegration: false,
      sandbox: true
    }
  });

  win.loadFile('index.html');
}

app.whenReady().then(createWindow);

preload.js

const { contextBridge, ipcRenderer } = require('electron');

contextBridge.exposeInMainWorld('api', {
  getGitHubUser: (username) => ipcRenderer.invoke('github:get-user', username)
});

renderer

const user = await window.api.getGitHubUser('octocat');
console.log(user);

This avoids renderer CORS entirely while keeping the attack surface much smaller than exposing unrestricted ipcRenderer or Node APIs.

Don’t “fix” CORS by disabling web security

You can disable Chromium protections with webSecurity: false:

const win = new BrowserWindow({
  webPreferences: {
    webSecurity: false
  }
});

Yes, that often makes CORS errors disappear.

It also removes one of the few hard boundaries protecting your renderer. If any untrusted content gets loaded, or if you have an XSS bug, you’ve made lateral movement much easier.

I treat webSecurity: false as a debugging hack, never a production solution.

Intercepting headers inside Electron

Sometimes you control the Electron app but not the API, and you need a compatibility layer. Electron’s session APIs let you inspect and even modify response headers.

Example:

const { app, session } = require('electron');

app.whenReady().then(() => {
  session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
    const responseHeaders = details.responseHeaders || {};

    if (details.url.startsWith('https://internal-api.example.com/')) {
      responseHeaders['Access-Control-Allow-Origin'] = ['*'];
      responseHeaders['Access-Control-Allow-Headers'] = ['Content-Type, Authorization'];
      responseHeaders['Access-Control-Allow-Methods'] = ['GET, POST, PUT, PATCH, DELETE, OPTIONS'];
    }

    callback({ responseHeaders });
  });
});

This can work, but I’m wary of it. You’re teaching your app to trust responses the server didn’t actually mean to expose cross-origin. That’s okay in tightly controlled enterprise environments. It’s not something I’d casually use for internet-facing or mixed-content apps.

If you go down this path, scope it narrowly by URL and session.

Electron documents these APIs here: https://www.electronjs.org/docs/latest/api/web-request

Debugging CORS in Electron

My checklist is boring, but it works:

1. Check where the request originates

Renderer or main process?
If it’s renderer, CORS applies. If it’s main, usually not in the browser sense.

2. Inspect the actual Origin header

Your app may be sending:

  • file://
  • null
  • http://localhost:5173
  • a custom protocol origin

That origin has to match what the server allows.

3. Look for preflight

If the failing request is OPTIONS, your real problem is probably missing:

  • Access-Control-Allow-Methods
  • Access-Control-Allow-Headers

4. Check exposed headers

If the request succeeds but headers seem missing in JS, the server probably forgot Access-Control-Expose-Headers.

GitHub gets this right with:

access-control-expose-headers: ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Used, X-RateLimit-Resource, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type, X-GitHub-SSO, X-GitHub-Request-Id, Deprecation, Sunset, Warning

5. Keep DevTools open

Use Chromium network inspection inside Electron. It’s still the fastest way to spot missing headers and failed preflights.

Security rules I’d actually ship with

For most Electron apps, I’d stick to these:

  • contextIsolation: true
  • nodeIntegration: false
  • sandbox: true where possible
  • no remote content unless absolutely necessary
  • renderer gets narrow IPC methods, not general network or filesystem access
  • sensitive API calls happen in main process
  • never disable webSecurity in production

If you’re hardening beyond CORS, your next stop is Content Security Policy. Electron apps benefit from CSP just like web apps do. For CSP background, see https://csp-guide.com. For Electron-specific security guidance, use the official docs: https://www.electronjs.org/docs/latest/tutorial/security.

Practical rule of thumb

If your Electron renderer is acting like a website, expect browser CORS.

If your main process is acting like a backend client, expect backend-style networking.

That mental split clears up most confusion. Once you stop fighting Chromium in the renderer and stop overexposing power through IPC, CORS in Electron becomes much less mysterious—and your app gets a lot safer.