# Add CORS to a Socket.IO Server

Yes. An agent replaces your Socket.IO server's hard-coded localhost origin with an allowlist from the environment, covers the websocket handshake too, in a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-cors/socket-io/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads where the origin list lives and who connects. In an app laid out like `examples/basic-crud-application` in socketio/socket.io, `server/lib/index.ts` creates an `http` server and calls `createApplication` with an `InMemoryTodoRepository` and `{ cors: { origin: ["http://localhost:4200"] } }`, which `server/lib/app.ts` passes straight into `new Server<ClientEvents, ServerEvents>(httpServer, serverOptions)`. The Angular client's `environment.development.ts` points at `http://localhost:3000` and its production `environment.ts` at `https://my-custom-domain.com`, and the Vue client's `socket.js` uses `http://localhost:3000` in development and the page's own origin in production. `server-postgres-cluster/lib/index.js` repeats the same literal list. So the first production deploy of the Angular client on its own domain is refused at the handshake: the polling request gets no `Access-Control-Allow-Origin`, the browser blocks it, and the client reports `xhr poll error` while the server logs nothing. `server/package.json` runs `nyc mocha --require ts-node/register test/**/*.ts`, and `test/todo-management/todo.tests.ts` connects two `socket.io-client` sockets to an ephemeral port and exercises every todo event.

The agent makes the allowlist configuration rather than code. `index.ts` reads `CORS_ORIGINS`, a comma-separated list, falls back to `http://localhost:4200` when the variable is unset so `npm start` keeps working for the Angular dev server, and passes `{ origin: origins, methods: ["GET", "POST"] }` as the `cors` option; `credentials` stays off because neither client sends cookies, and the pull request says what to set if a session cookie is added later. The same change goes into the cluster server's `index.js`, so the two entry points cannot drift again. Because the `cors` option governs only the HTTP requests of the polling transport and the upgrade, a client that opens a websocket directly is not subject to the browser's CORS at all; the agent adds an `allowRequest` that reads the handshake's `Origin` header against the same list and refuses a stray one, so both transports answer the same way, and explains in the pull request that a non-browser client sends no `Origin` and is let through as before.

Running the existing suite first turns up a break the change did not cause: `todo.tests.ts` imports `ClientEvents` and `ServerEvents` from `../../lib/events`, a file that does not exist, while `app.ts` imports them from `../../common/events`, so `npm test` fails under `ts-node` before any test runs. The agent fixes the import path, states that it did so to get a green baseline, and keeps that as one commit separate from the CORS change. It then adds `test/cors.tests.ts` that starts the application on an ephemeral port with `CORS_ORIGINS` set to two origins and sends plain HTTP requests to the handshake path, `/socket.io/?EIO=4&transport=polling`: with an allowed `Origin` the response carries `access-control-allow-origin` equal to that origin and `vary: Origin`; with another origin the header is absent; a preflight `OPTIONS` from an allowed origin answers with the allowed methods; and a websocket handshake from a stray origin is refused by `allowRequest` with a 403, which is tested with a raw upgrade request rather than through the client, because the Node client enforces no CORS and would connect regardless.

It runs `npm test` with the race-free sequence the existing tests use, `nyc` included, and `npx tsc --noEmit` against `server/tsconfig.json`, which is `strict`, so the `allowRequest` signature and the parsed environment are typed. The pull request shows the test output, the `curl -i` of the handshake path from an allowed and a stray origin, and a one-line note for each client: the Angular production `environment.ts` needs the server's real address and that address needs to be in `CORS_ORIGINS` on the server, and the Vue client in production needs nothing because it connects to its own origin.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add a configurable CORS allowlist to this Socket.IO server. Read server/lib/index.ts, server/lib/app.ts, server/package.json, server/tsconfig.json, server/test/todo-management/todo.tests.ts, common/events.ts, server-postgres-cluster/lib/index.js and the two clients' environment files first. Replace the hard-coded origin list with CORS_ORIGINS, a comma-separated environment variable, defaulting to http://localhost:4200 when unset, passed as the cors option with GET and POST and no credentials; make the same change in the cluster server. Add an allowRequest that checks the handshake's Origin header against the same list so a websocket-only client from another origin is refused too, and lets a request with no Origin through. Run the existing suite first; if it does not compile, fix only what blocks it in a separate commit and say so. Add test/cors.tests.ts that sends plain HTTP requests to /socket.io/?EIO=4&transport=polling and asserts the access-control-allow-origin and vary headers for an allowed origin, their absence for another, the preflight answer, and a 403 on a raw websocket upgrade from a stray origin. Run npm test and tsc --noEmit, and open a pull request with the output, the curl of the handshake from both origins, and what each client's production config needs.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request has two commits: one that fixes the `../../lib/events` import so the existing suite compiles, and one that changes `server/lib/index.ts`, `server-postgres-cluster/lib/index.js` and adds `server/test/cors.tests.ts`. Its description shows `npm test` with the todo suite and the four new tests passing under `nyc`, the `tsc --noEmit` run, and two `curl -i` transcripts of the handshake path, one carrying `access-control-allow-origin` and one without it.

Nothing changes for a developer running `npm start` with the Angular dev server on port 4200: the default list is the one that was hard-coded. A production deploy sets `CORS_ORIGINS` to the client's real origin and the Angular `environment.ts` to the server's real address, and the pull request names both lines. The todo handlers, the repository and the events are untouched.

Before merging, a reviewer decides whether the websocket-side `allowRequest` is wanted, since it refuses browsers from unknown origins but, like CORS, is no protection against a non-browser client, and whether `credentials` should be turned on now if a session cookie is planned, which the pull request shows as a one-line change with its matching client option.

## Run it on every new frontend origin

A team with several Socket.IO services starts one run per repository from its own server: a `POST /o/{org}/sessions` each, with the repository in `resources`, the front-end origins written into `input`, and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started. Each run reads its own entry point, so a server that already reads its origins from a config file gets the list extended there, and one with the `cors` option on an Express app in front of Socket.IO gets both kept in step.

Later, a Linear issue labelled `cors` in the Project can start a run through an automation with a `linear` trigger and the prompt "add the origin this issue names to the documented CORS_ORIGINS value, extend the handshake test to cover it, run npm test and open a pull request". The trigger adds the issue after the prompt, and the run reads it through the Linear connection, so a new front-end domain arrives as a reviewed change with a test.

## Why run it on Rush?

Socket.IO's CORS failure is silent on the server and cryptic on the client, `xhr poll error`, and the polling and websocket transports are governed by different rules, so a change that fixes one and not the other looks right in development and fails in a browser that happens to start with the other. The agent tests the handshake over plain HTTP in its own sandbox, where the headers are visible, and the upgrade with a raw request, rather than trusting a Node client that would connect from any origin.

The transcript keeps the test output and the `curl` headers, so a reviewer sees exactly what a browser at each origin would be told. Several services can be given the same allowlist at once, each in its own sandbox, and nothing merges until a person reads the diff.

## Frequently asked questions

### Why did the existing tests not compile?

`test/todo-management/todo.tests.ts` imports the event types from `../../lib/events`, which does not exist; the types live in `common/events.ts`, where `app.ts` imports them from. The agent fixed that one path in its own commit so the suite could run before and after the CORS change, and said so in the pull request rather than folding it into the change.

### Why test the handshake with plain HTTP instead of socket.io-client?

CORS is enforced by browsers, not by servers or Node clients: the server only adds or omits the `Access-Control-Allow-Origin` header, and a `socket.io-client` in Node connects whether or not the header is there. Requesting `/socket.io/?EIO=4&transport=polling` with an `Origin` and reading the headers is the only way to assert what a browser would see.

### What does allowRequest add that the cors option does not?

The `cors` option applies to the HTTP requests of the polling transport and the upgrade; a client that opens a websocket directly never makes a CORS-checked request, and a browser still sends `Origin` on it. `allowRequest` reads that header on the handshake and refuses an origin that is not on the list, so both transports give the same answer. A client that sends no `Origin`, such as a server-side client, is unaffected.

### Why is credentials off?

Neither client sends cookies or an `Authorization` header, so `credentials: true` would only widen what a cross-origin page may send. If a session cookie is added later, the server option and the client's `withCredentials` go on together, and the pull request shows both lines.

### What changes in the Angular and Vue clients?

Nothing in code. The Angular production `environment.ts` has to name the real server address, and that client's origin has to be in the server's `CORS_ORIGINS`; the Vue client connects to the page's own origin in production, so it needs no entry. The pull request lists both as deploy notes.

## More Socket.IO jobs

- [Add Dependabot to a Socket.IO App](https://getrush.ai/run/add-dependabot/socket-io/)
- [Add a Dockerfile to a Socket.IO Chat Server](https://getrush.ai/run/add-dockerfile/socket-io/)
- [Add Graceful Shutdown to a Socket.IO Server](https://getrush.ai/run/add-graceful-shutdown/socket-io/)

## The same job on other stacks

- [Add CORS to a tRPC API](https://getrush.ai/run/add-cors/trpc/)
- [Add CORS to a Vapor Server](https://getrush.ai/run/add-cors/vapor/)
- [Add CORS to an Actix Web API](https://getrush.ai/run/add-cors/actix/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
