# Convert a Socket.IO Chat Server to TypeScript

Yes. An agent moves your Socket.IO server to TypeScript with typed events for both directions, a strict tsconfig, a build script and a CI check, and opens a PR.

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

## What the agent does

The agent starts by reading the one server file, because the whole conversion is deciding what types it already implies. In a project like socketio/chat-example, `index.js` is an ES module (`"type": "module"` in `package.json`) that forks one worker per CPU with `node:cluster`, calls `setupPrimary()` from `@socket.io/cluster-adapter` in the primary, and in each worker opens `chat.db` with `sqlite` over `sqlite3`, creates a `messages` table, builds an Express app, and creates a `Server` with `connectionStateRecovery` and `createAdapter()`. The one event, `chat message`, arrives with a string, a client offset and an acknowledgement callback, is inserted with the offset as a unique key, and is broadcast back with the row id. On a connection that was not recovered, rows after `socket.handshake.auth.serverOffset` are replayed. `package-lock.json` pins socket.io 4.7.2, express 4.18.2, sqlite 5.0.1 and sqlite3 5.1.6. There is no tsconfig, no test and no CI.

It adds `typescript`, `@types/node` and `@types/express` as dev dependencies; `socket.io`, `sqlite`, `sqlite3` and the cluster adapter ship their own types. The `tsconfig.json` uses `module` and `moduleResolution` set to `NodeNext`, `target` `ES2022` so the top-level `await` in the worker branch stays legal, `strict`, `rootDir` of `src` and `outDir` of `dist`. `index.js` becomes `src/index.ts`, and since the compiled file now runs from `dist/`, the `res.sendFile` path goes up one directory to reach `index.html`, which stays where it is.

The types that matter are the event maps. `ServerToClientEvents` declares `chat message` as `(msg: string, serverOffset: number) => void` and `ClientToServerEvents` declares it as `(msg: string, clientOffset: string, callback: () => void) => void`, and `new Server<ClientToServerEvents, ServerToClientEvents>(server, …)` makes `socket.on`, `io.emit` and the acknowledgement checked against them. `open` is called as `open<sqlite3.Database, sqlite3.Statement>` so `db.run` returns a typed result, which is where strictness bites: `result.lastID` is optional, the `errno` check in the `catch` sees an `unknown`, `handshake.auth.serverOffset` is `any` and `process.env.PORT` is a string or missing. The agent narrows each one explicitly, keeps the `19` constraint check for a duplicate offset, and parses the port with a fallback so the worker still binds where the primary told it to.

`package.json` gets `build` as `tsc` and `start` as `node dist/index.js`, so `npm start` never compiles in production, `dist/` joins `node_modules/` and `chat.db` in `.gitignore`, and a `.github/workflows/ci.yml` runs `npm ci` and `npm run build` on push and pull request, since a type error is now the one check this repository has. The agent runs the build, starts the server, opens `http://localhost:3000` twice in the sandbox's browser, sends a message from one tab and reads it in the other, then restarts the server and watches the earlier messages replay from the offset, before opening the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Convert this Socket.IO chat server to TypeScript. Read package.json, package-lock.json, index.js, index.html, .gitignore and .codesandbox/tasks.json first. Add typescript, @types/node and @types/express as dev dependencies and write a strict tsconfig.json with NodeNext module resolution, an ES2022 target so top-level await keeps working, src as rootDir and dist as outDir. Move index.js to src/index.ts and fix the sendFile path so index.html is still found from dist. Declare ServerToClientEvents and ClientToServerEvents interfaces for the chat message event with its acknowledgement callback and pass them to the Server generics; call open with the sqlite3 Database and Statement generics. Narrow every value strict mode flags, including the optional lastID, the unknown error in the catch, the handshake auth offset and the PORT variable, without using any. Add build and start scripts, ignore dist, and add a GitHub Actions workflow that runs npm ci and npm run build. Build, start the server, send a message between two browser tabs and show the replay after a restart, then open a pull request.",
  "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

What comes back is a pull request that deletes `index.js`, adds `src/index.ts`, `tsconfig.json` and `.github/workflows/ci.yml`, and changes `package.json`, `package-lock.json` and `.gitignore`. The description lists every place the types forced a decision: how the optional `lastID` is handled before the broadcast, what the `catch` does with a non-constraint error, and how a missing `PORT` is treated, so a reviewer reads the semantic changes in one list rather than hunting for them in a rename diff.

The run's record holds the `tsc` output, the server start, the two browser sessions with the message crossing between them and the replay after the restart, so the claim that behaviour did not change rests on a recording rather than on the word of the diff.

Before merging, a reviewer decides whether to type the rows coming out of `db.each` with a `Message` interface, whether the client script in `index.html` should move to TypeScript too, and whether the CI workflow should also run a start-and-connect smoke test. The agent converts only the server, as asked.

## Run it on every JavaScript service left behind by a TypeScript codebase

A team converting several small Node services starts one run per repository from its own server: one `POST /o/{org}/sessions` each, with that repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started instead of a second pull request. Each run reads its own entry file and declares the event maps that file implies.

Once the repository is TypeScript, an automation on the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` and the prompt "if this pull request adds a socket event, check that both event interfaces declare it with the right argument types and comment if one side is missing" keeps the two maps in step. The trigger puts the pull request after the prompt; only work by an owner, member or collaborator fires it, never a fork's.

## Why run it on Rush?

A conversion done by renaming files and adding types until the compiler is quiet changes behaviour in the places strict mode complains, and those are exactly the places a chat server misbehaves: the offset that decides what replays, the error branch that decides whether a client retries, the port a worker binds. The agent runs the converted server, sends messages across tabs and restarts it to watch the replay, so the pull request shows the same behaviour and not only the same shape.

The sandbox keeps the compiler output, the server log and the browser recording with the run, and the pull request cites them. For a team with a handful of these services, each gets its own run, its own machine and its own evidence, reviewed in the time it takes to read one list of decisions.

## Frequently asked questions

### Why NodeNext rather than the older module settings?

Because the project is already an ES module with `"type": "module"`, and `NodeNext` is the setting that compiles to the import rules Node applies to it, including explicit `.js` extensions on relative imports. It also keeps the top-level `await` that the worker branch uses, provided the target is ES2022 or later.

### Why is the acknowledgement callback part of the event type?

Socket.IO passes the client's acknowledgement function as the last argument of the handler, and the client side in `index.html` sets `ackTimeout` and `retries` so it resends until that callback runs. Declaring the callback in `ClientToServerEvents` means the compiler fails a handler that forgets to call it, which is the bug that makes clients resend the same message three times.

### Does the cluster and adapter setup survive the conversion?

Yes. `node:cluster`, `availableParallelism` and `@socket.io/cluster-adapter` are typed, so the primary and worker branches compile as they are. The only change in that part of the file is the port: the primary forks each worker with a `PORT` environment variable, and the worker now parses it as a number instead of passing a string to `listen`.

### Why add CI when there are no tests?

After this change `tsc` is the one check the repository has, and it is worth running on every pull request. The workflow is two steps, `npm ci` and `npm run build`, and fails on a type error. A reviewer who later adds tests has a place to put them.

## More Socket.IO jobs

- [Move a Socket.IO Chat From SQLite to PostgreSQL](https://getrush.ai/run/migrate-sqlite-to-postgres/socket-io/)
- [Write Integration Tests for a Socket.IO Chat Server](https://getrush.ai/run/write-integration-tests/socket-io/)
- [Add the Admin UI to a Socket.IO Server](https://getrush.ai/run/add-admin-ui/socket-io/)

## The same job on other stacks

- [Convert a SolidJS App From JavaScript to TypeScript](https://getrush.ai/run/convert-javascript-to-typescript/solidjs/)
- [Convert a SvelteKit App from JavaScript to TypeScript](https://getrush.ai/run/convert-javascript-to-typescript/sveltekit/)
- [Convert a Vue App From JavaScript to TypeScript](https://getrush.ai/run/convert-javascript-to-typescript/vue/)

## 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/)
