All jobs

Add WebSockets to a Fastify App

Yes. An agent adds a WebSocket route that pushes task events to signed-in clients of your Fastify API, authenticated by its session cookie, tests it, and opens a PR.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent reads how the app is assembled before it adds a transport to it. In an app shaped like fastify/demo, package.json has fastify ^5.10.0 with @fastify/autoload, @fastify/session and @fastify/cookie, @fastify/rate-limit, @fastify/helmet, @fastify/under-pressure, @fastify/swagger and @fastify/type-provider-typebox, knex with mysql2, and close-with-grace; tests run with node:test through tsx --test under c8, and npm test seeds the database first. src/app.ts autoloads plugins/external, then plugins/app, then routes with autoHooks and cascadeHooks, so a file dropped into src/routes/api/tasks/ is mounted under /api/tasks with the hooks of its parents. src/routes/api/autohooks.ts adds an onRequest hook that answers unauthorized to any /api request without request.session.user, except the login route.

src/routes/api/tasks/index.ts is the model for the new code: typed routes with TypeBox schemas from src/schemas/tasks.ts, POST / answering 201 with { id }, PATCH /:id, DELETE /:id behind request.isAdmin, POST /:id/assign behind request.isModerator, and file upload and CSV routes. All data access goes through fastify.tasksRepository in src/plugins/app/tasks/tasks-repository.ts, a decorated object with create, update, delete and findById over knex. test/helper.ts builds the app with fastify-plugin, logs in through POST /api/auth/login to get the COOKIE_NAME cookie, and injects requests with app.inject, which never opens a TCP port; .env.example sets RATE_LIMIT_MAX=4 for the test run, so every extra request in a test counts.

The agent registers @fastify/websocket as src/plugins/external/websocket.ts, with a name so other plugins can depend on it, and adds src/plugins/app/tasks/tasks-events.ts, which decorates fastify.taskEvents with a Node EventEmitter and a small typed emit for task.created, task.updated, task.assigned and task.deleted. The four handlers in routes/api/tasks/index.ts emit after their repository call, carrying the task as TaskSchema already serialises it. A new src/routes/api/tasks/events.ts adds GET /events with { websocket: true }: the upgrade is a GET that passes through autohooks.ts, so a client without the session cookie is refused before the socket opens, with no second authentication path to maintain. Each connection subscribes to the emitter, sends one JSON frame per event, honours an optional assigned_user_id query filter validated by TypeBox, and unsubscribes on close so a dropped browser does not leak a listener. server.ts is untouched; close-with-grace closes open sockets through app.close() as it already does for HTTP.

Tests need a real port, because app.inject cannot upgrade. test/routes/api/tasks/events.test.ts calls build(t), then await app.listen({ port: 0 }), reads the port from app.server.address(), logs in with app.login, and opens a ws client with the session cookie in headers; it then creates a task through app.injectWithLogin and awaits one frame with type: 'task.created' and the new id. A second case opens a socket with no cookie and expects the upgrade to fail with 401; a third assigns a task and checks the task.assigned frame carries assigned_user_id. ws joins devDependencies for the client only. The agent runs npm run build -- --noEmit, npm run lint and npm test against a MySQL started in the sandbox from docker-compose.yml, and keeps the output.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "codex",
  "input": "Add a WebSocket route that streams task events to this Fastify app and open a pull request. Read package.json, src/app.ts, src/server.ts, src/routes/api/autohooks.ts, src/routes/api/tasks/index.ts, src/plugins/app/tasks/tasks-repository.ts, src/plugins/external/session.ts, src/schemas/tasks.ts, test/helper.ts and .env.example first. Register @fastify/websocket as a named plugin in src/plugins/external. Add src/plugins/app/tasks/tasks-events.ts decorating fastify.taskEvents with an EventEmitter and typed emits for task.created, task.updated, task.assigned and task.deleted, and emit from the four route handlers after the repository call. Add src/routes/api/tasks/events.ts with GET /events as a websocket route, protected by the existing autohooks session check, sending one JSON frame per event, with an optional assigned_user_id query filter and listener cleanup on close. Add test/routes/api/tasks/events.test.ts using node:test that listens on port 0, logs in with the helper, connects with the ws client and the session cookie, creates a task and asserts the frame, and also asserts an unauthenticated upgrade is refused. Keep RATE_LIMIT_MAX=4 in mind. Run npm run build -- --noEmit, npm run lint and npm test, and paste the output in the 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 adds a websocket plugin under plugins/external, an events plugin under plugins/app/tasks, a routes/api/tasks/events.ts, four one-line emits in the existing task routes, a test file, and @fastify/websocket plus ws in package.json and package-lock.json. The description shows the frame shape, explains why the session cookie is the only credential, and pastes the type check, the lint and the node:test summary with the new file included.

The repository's CI workflow runs the same three commands on Node 22 and 24 against a MySQL 8.4 service on the pull request, so the socket test runs there with the rest of the suite.

A reviewer checks that an upgrade without a cookie never reaches the handler, that a client cannot subscribe to events it could not read over HTTP, that listeners are removed on close, and that app.close() ends open sockets so close-with-grace still exits within its delay. They merge when both Node versions are green.

Run it on every Fastify API whose clients poll for changes

A team with several Fastify services sends one POST /o/{org}/sessions per repository with this prompt and the repository in resources. Each run reads that service's own routes and repository and streams the events it actually has, so a service with orders instead of tasks gets order.* frames, and each run opens its own pull request.

Add a request_id to each call so a retry returns the run already started, and set a webhook_url on the key so run.completed reaches your server with session_url when each turn ends and the pull request link lands where the backend team reads it.

The use case this job follows, with its automation and trigger: Hand off a long task.

Why run it on Rush?

WebSockets fail in ways unit tests through inject cannot see: an upgrade that skips a hook, a listener that outlives its socket, a server that hangs on shutdown. The proof is a real TCP port, a real client and a real MySQL behind the repository, which is what the agent runs in its Rush sandbox, with every command and frame kept in the run's record beside the pull request.

On a laptop this means reading the @fastify/websocket docs, finding out that inject cannot upgrade, and wiring a client into a node:test file under a rate limit of four requests. The agent does it in one pass with the repository's own tools, and a follow-up such as "add a task.commented event" wakes the parked sandbox and lands on the same branch.

Frequently asked questions

How are socket clients authenticated?

With the same session cookie the HTTP routes use. The upgrade request is a GET /api/tasks/events, so the onRequest hook in src/routes/api/autohooks.ts runs before the handshake completes and answers 401 when request.session.user is missing. No token in the URL, no second login path.

Does this work with several server processes?

Within one process, yes: the emitter is in memory, and every route and socket shares it. Across processes, events emitted on one instance do not reach sockets on another; the pull request says so and names Redis pub/sub or MySQL polling in the events plugin as the place to add fan-out, without changing the route.

Why not Server-Sent Events?

They would also work for a one-way stream, and the same taskEvents plugin could feed one. The prompt asks for WebSockets because the clients in question may later send acknowledgements or filters over the same connection, and @fastify/websocket is the maintained plugin for that in Fastify 5.

Why does the test listen on a port?

app.inject uses light-my-request, which drives the router without a socket and cannot perform an HTTP upgrade. The test calls app.listen({ port: 0 }) so the operating system picks a free port, reads it from app.server.address(), and connects a ws client; build(t) still closes the app after the test.

More Fastify jobs

The same job on other stacks

Keep reading