Install
npm install --save-dev @noverax/courier-mockIt works with the app's own @noverax/courier. It also needs hono, and a mock server — one Studio runs, or one from /server — needs @hono/node-server. Add the ones the app does not depend on already, for development only:
npm install --save-dev hono @hono/node-serverLeave out any the app already lists under dependencies: --save-dev would move it out of them, and a production install would then go without it.
Declaring mocks
Declare mocks in courier.mocks.ts, beside courier.config.ts: its default export is defineMocks({ ... }), with one defineMockServer(...) under each key. Studio lists each mock by its key, generates its routes and data from its source, and runs it — at launch when autoStart is set, or when you start it from the Mocks view. Studio's mock wizard can write the declarations for you; see Add mocks from Studio.
The mocks have a file of their own because courier.config.ts is also loaded in production — by the standalone server, and by attachRuntime() — where this package is not installed. Only Studio reads courier.mocks.ts. courier.config.ts has no mocks key: defineConfig does not type-check with one, and Studio reads mocks from nowhere else.
// src/api.ts
import { courier, defineApi, defineGroup } from "@noverax/courier/define"
type User = { id: number; name: string }
const { endpoint } = courier()
const users = defineGroup({
prefix: "users",
endpoints: {
getAll: endpoint.get("").response<User[]>(),
getById: endpoint.get(":id").variables<{ id: number }>().response<User>(),
},
})
export const api = defineApi({ baseURL: "https://api.example.com", groups: { users } })// courier.config.ts
import { defineConfig } from "@noverax/courier/config"
import { api } from "./src/api"
export default defineConfig({ sources: { api } })// courier.mocks.ts
import { defineMocks, defineMockServer } from "@noverax/courier-mock"
import { api } from "./src/api"
export default defineMocks({
api: defineMockServer({
source: api,
port: 7001,
autoStart: true,
seed: { users: 5 },
overrides: (mock) => {
mock("users", "getById").rejects(404, { message: "Not found" })
},
}),
})sourceis the source object the mock serves. Import it from where the config does, as above, or read it from the config —import courierConfig from "./courier.config", thensource: courierConfig.sources.api— as Studio's wizard writes it. That form needs a config whose default export isdefineConfig({ sources }): a config that exportssourcesby name only loads, but a default import of it does not type-check. In a"type": "module"package whose tsconfig resolves modules as Node does (node16ornodenext), import./courier.config.jsinstead; TypeScript asks for the extension there, and the wizard writes it that way. Studio loadscourier.mocks.tstogether with the config, as one module graph, so a module both import runs once, and either way the mock holds the very source object the config declares.- The file may also be named
courier.mocks.mts,.cts,.js,.mjsor.cjs. Studio looks for these names in that order, in the directory that holdscourier.config, and loads the first it finds: acourier.mocks.tsthere hides acourier.mocks.jsbeside it. A TypeScript file loads as it is, with extensionless imports and tsconfig path aliases; nothing else needs installing. portis held exactly: when it is taken, Studio says so rather than moving the mock. Without one, Studio assigns the key a port fromstudio.mockBasePort(7001 by default), clear of the ports the project's other mocks were given. The mock takes that port, or the first free one above it, as it starts listening: the bind itself decides, with no check made beforehand, so two Studios starting their mocks at the same moment — a monorepo's dev task — never take the same port. A port the system keeps for itself is not free either: Windows keeps blocks of them for Hyper-V, WSL and Docker, and the mock moves past them. The key is assigned another when a mock declares its port, and after Studio restarts the mock can get another too. Setportto keep one.seedsets how many records each collection starts with:countfor every group (20 by default), and a number under a group's name for that group alone.autoStartdefaults tofalse. A key set toundefineddeclares no mock, so one can be switched off in place.overridesandscenariosare checked againstsource:mocktakes the source's group and endpoint names and each endpoint's response type. Write a scenario withdefineScenario<typeof api>(...)to have it checked the same way; one without the type argument fits every mock. An endpoint declared outside any group is mocked under the collection its path starts with,mock("users", "listUsers"); the types cannot check that name, so a mock under another collection is refused with aMockTargetErrorthat names the right one.scenariosis an object keyed by each scenario's name,{ empty: defineScenario("empty", …) }, which is how Studio and the admin API name them; an array is refused with aScenarioConfigErrorthat spells the object out.- Four scenarios come with every mock, beside yours:
happy-pathputs nothing on top, so every route answers as declared, from its schema or its override;emptyanswers every list with no records;server-errorfails every endpoint with a 500, 503 or 502;slow-networkslows every read by 300–900 ms, with jitter. A mock starts onhappy-path, so switching back to it turns any other off. One scenario is in force at a time: Studio's Scenarios tab switches them, and so doesPOST /__admin/scenarios/<name>on the mock. - Editing
courier.mocks.ts, or a module it imports, restarts a running mock whose declaration changed, or something that declaration uses — a declaration beside it, an import and every module that import reaches, a statement of the file that declares nothing. The other mocks keep running, with their records: adding a mock does not restart the ones already running. A mocks file whose mocks Studio cannot tell apart — its keys spread in or computed, or a CommonJS file — restarts every running mock on each edit.autoStartapplies when Studio first reads the definition, or when an edit turns it on — not again after you stop the mock. - A mock keeps its records in the project, in
.courier/mocks/— one SQLite database per mock, saved shortly after each request and when the mock stops, and read when it starts — so what an app created is still there after the mock restarts, an edit that changes it included, and after Studio restarts. Nothing is set up by hand: the database and its schema are created on the first start, a database from an earlier Courier is brought up to date as it opens, and records are kept as JSON documents, so an API whose shapes change needs no migration. A save writes, in one transaction, only the records that changed. A database that cannot be read is kept beside the new one as<name>.unreadable-<time>. A collection the database holds nothing for starts from its seeds, and one the mock no longer serves is dropped. Reset store empties the store and seeds it again, and that is kept too.persist: falsestarts the mock from its seeds each time. The database is Node's built-in SQLite, in Node 22.13 and later; elsewhere a mock keeps its records only while it runs, and says so.
Which route answers a request, what a mock's records are made from, and how mocks run and fail are on How a Mock Answers.
Mock only some endpoints, or answer with recordings
A mock need not answer everything. endpoints names the endpoints it answers; every other HTTP call goes to the source's own server at its baseURL, as the app calls it — handy while the backend has all but a few endpoints. fixtures answers with recordings of that server in place of generated data: a call the mock has no answer to yet goes to the server once, its answer is written to a HAR file, and the same call is answered from the file from then on.
// courier.mocks.ts
import { defineMocks, defineMockServer } from "@noverax/courier-mock"
import { api } from "./src/api"
export default defineMocks({
refunds: defineMockServer({ source: api, endpoints: ["users.getById"] }),
demo: defineMockServer({ source: api, fixtures: "./fixtures/api.har" }),
})endpointstakesgroup.method, or the method alone for an endpoint outside any group, and is checked against the source: a name it does not have stops the mock with aMockEndpointsErrorthat lists the names it has. Streams and channels the mock always answers itself. An endpoint left to the server is not mocked at all, so an override or a scenario for it does not apply.- A call passed to the server carries the request's own headers, its credentials included, but none of the hop's (
host,origin,content-length,sec-*and the like). The server's answer, a failure included, comes back with its status, its data and its headers. fixturesis relative tocourier.mocks.ts. The file is a HAR log, the format browsers' developer tools open; commit it to give everyone the same answers. A recording is matched by its endpoint and its variables, and keeps no credentials:authorization,cookieandset-cookieare left out. An override or a scenario on an endpoint answers in place of its recordings. A call with no recording while the server cannot be reached is answered with a 502 that says so; delete the file to record everything again. A file that is not a HAR log of recordings stops the mock with aFixtureFileError.- Studio's mock wizard sets both: Answers takes every endpoint or the ones ticked, and Data generated or recorded, kept in
fixtures/<key>.harbeside the mocks file. The Routes tab tags each route by what answers it,your serverorrecordedamong them, and the mock's log says the same of each call. - An endpoint added to the source later is not in a mock's
endpoints, so it goes to your server. The Routes tab names those its server answers above the routes, with Add to mock, and the route itself offers it too: Studio previews the change tocourier.mocks.tsas a diff — the names appended to the mock'sendpointsarray, nothing else — writes it only as shown, checks that the mock loads listing them, and restarts that mock. A list it cannot read in full, such as a variable, a spread or a template string, is left to you, with the names to add.
A proxy caller pointed at the mock
A mock stands in for the API itself, where a direct caller goes, and also for a Courier proxy, where a proxy caller goes. It serves the proxy's three routes:
| Route | For | As a Courier proxy serves it |
|---|---|---|
GET/POST /api/request | an HTTP call | the endpoint named by _s, _g and _m in the query; a cached read's variables in _v, any other call's in the body: JSON, a form, or the record upload of a record that holds a file |
GET /api/sse | a stream | the stream's events, the variables in _v |
/api/ws (WebSocket) | a channel | every channel a caller subscribes to, on one socket, each by its topic |
A mock built from a source refuses at these routes what that API's own proxy refuses — an endpoint it keeps from a page, a GET to anything but a read, or to a read whose variables stay out of the address — with the proxy's status and its body, { "success": false, "message": … }, so a page that works against the mock is not refused once it calls the proxy, and reads a refusal as the proxy writes it.
import { createProxyCaller } from "@noverax/courier/client"
import { routes } from "@noverax/courier/routes"
const mock = "http://localhost:7001"
const api = createProxyCaller(routes.api, {
proxyPath: { http: `${mock}/api/request`, sse: `${mock}/api/sse`, ws: "ws://localhost:7001/api/ws" },
})On /api/ws, and on a channel's own path where a direct caller connects, a subscription goes as it does on a Courier server. The variables are checked against the channel's schema, and a subscription that fails them ends with code 4422. Its topic is keyed as the channel's .topic() says, with a renamed frame first when that differs from the topic asked for, so subscribers who share a key share the channel's broadcasts. Each message is checked against what the channel .send()s, and one that fails is refused with 4422 while the subscription goes on; the message an override's onMessage receives is typed as that. A channel not mocked in the scenario state a subscription is made in ends with 4404, naming it and the state. ctx.close() ends that one subscription and leaves the socket's others open. An override is called with the upgrade request's headers and those of the client's auth frame — an Authorization a browser could send only there — as a Courier server reads them: none the handshake has, and no cookie, origin or forwarding header, is taken from the frame. A channel's own path serves that channel, and the parameters the path carries reach the override beside the variables a subscription sends. Every socket is pinged every 25 seconds, as a Courier server pings it, and closed with 4408 when its client stops answering, so a quiet channel stays open and a client that went away is let go. A mock built without a source checks nothing and keys each topic by its variables. Studio's mock logs show each subscription as it opens and ends.
Uploads and large bodies
A mock reads a form, a record that holds a file and a file sent as the whole body, up to 1 MB of JSON and 10 MB of form or upload as a Courier server does, and answers a body past its limit with 413: see Uploads and large bodies.
Slow and failing answers
network makes a mock answer as a slow or unreliable network would, and take uploads as a server with limits does: it adds latency, caps how fast answers are sent and uploads arrive, refuses an upload over a size or of a type it does not take, and fails a share of calls with any HTTP error status, a timeout, a dropped connection or an upload cut off partway, and its stop conditions end a run on their own. Studio's Network tab sets the same conditions on a running mock. See Network conditions.
// courier.mocks.ts
import { defineMocks, defineMockServer } from "@noverax/courier-mock"
import { api } from "./src/api"
export default defineMocks({
api: defineMockServer({ source: api, network: { latency: "3g", errorRate: 0.1 } }),
})Repeated writes
A write sent again with its idempotency key — a client's retry, a double click — gets the mock's first answer back, marked Idempotent-Replayed: true, and creates nothing twice, as an API that deduplicates by the key answers. The key is read from Idempotency-Key and from every header the source's endpoints name in their idempotencyKey. The same key sent with other variables is refused with 422, and one whose first call is still running with 409; a call that failed is not remembered, so its retry runs again. Keys are kept for a day, the last 1 000 of them.
defineMockServer({ source: api, idempotency: false }) // runs every write, keyed or notAdd mocks from Studio
Generate mocks in the Mocks view opens a wizard: pick the sources, the endpoints and the data to mock, and Studio shows the change to courier.mocks.ts as a diff and makes it — or, where it will not edit the file, shows the lines to add by hand. See Add Mocks from Studio.