Skip to content

Migrating from Express ​

Express is a HTTP server. Nwire is a domain framework that has a HTTP wire. Migration is more about reshaping how you think than rewriting. This guide walks through the conceptual translation, then the mechanical steps.

The conceptual shift ​

Express thinks in routes. Nwire thinks in actions.
js
// Express:
app.post("/submissions", auth, validate(submitSchema), async (req, res) => {
  const result = await submissionService.create(req.body, req.user)
  res.status(201).json(result)
})
ts
// Nwire:
const submitAnswer = defineAction({
  name: "submissions.submit-answer",
  input: submitSchema,           // zod, same shape — validation is free
  policy: "student-self",         // authz hook
  emits: [AnswerSubmittedEvent],
  handler: async (ctx) => {
    const { input } = ctx;
    return AnswerSubmitted({ ...input, studentId: ctx.envelope.userId, submittedAt: now() });
  },
})

// Wire the action under a transport binding on an App.
app.wire(
  post("/submissions", { body: submitAnswer.input }),
  submitAnswer,
)

The HTTP route is just one transport. The same action also runs via the queue worker, the CLI, and the dispatch UI in Studio. You wrote the business operation once; the framework gave it three calling conventions.

Express threads req everywhere. Nwire threads ctx.envelope.

ctx.envelope carries messageId, correlationId, causationId, tenant, userId, timestamp, version. Set once at the wire (from x-tenant-id / auth middleware / etc.), threaded through every nested call automatically. No more pass req down 8 layers.

ctx.logger is already scoped to the envelope — every log line carries the ids without you remembering.

Express has middleware. Nwire has DispatchMiddleware + plugins.

Middleware in Nwire is around action dispatch, not HTTP requests:

ts
runtime.use(async (next, action, input, ctx) => {
  const start = performance.now()
  try {
    return await next()
  } finally {
    ctx.logger.info("dispatched", { action: action.name, durationMs: performance.now() - start })
  }
})

The pre-built ones: @nwire/observability (tracing), @nwire/auth (authz). Plus the canonical telemetry stream (runtime.onTelemetry) for read-only observation.

Mechanical migration ​

1. Identify your bounded contexts ​

If your Express app already has folders like controllers/users/, controllers/orders/, controllers/billing/ — each is a candidate app. The rule: one bounded context = one app. Domains shouldn't leak.

2. For each controller, identify the actions ​

  • POST /users → users.create action
  • POST /users/:id/verify-email → users.verify-email action
  • GET /users/:id → users.get query
  • GET /users → users.list query

Notice: GETs become queries (read projections). POSTs / PUTs / DELETEs become actions (commands that emit events).

3. Identify events ​

For each action, what happened? Past tense. Granular.

  • users.create → UserCreatedEvent
  • users.verify-email → UserEmailVerifiedEvent
  • orders.place → OrderPlacedEvent, maybe OrderConfirmedEvent if it's two-step

Don't combine: OrderPlacedOrCancelledEvent is a smell.

4. Identify aggregates ​

What state needs invariant enforcement? "Only confirmed orders can be shipped." "Can't refund a refunded payment." Those are state machines. Each gets an actor:

ts
const Order = defineActor(
  "order",
  ({ states, when }) => {
    const { placed, confirmed, shipped } = states;
    placed(() => when(OrderConfirmedEvent, (e, { assign }) => { assign({ ...e }); return confirmed; }));
    confirmed(() => when(OrderShippedEvent, (e, { assign }) => { assign({ ...e }); return shipped; }));
  },
  { schema: OrderData },  // OrderData declares states: placed (initial), confirmed, shipped (final)
)

Aggregates that don't have meaningful state transitions can be skipped — just fold the events into a projection.

5. Identify projections + queries ​

Per-entity views: users-by-id, orders-by-customer, articles-by-tag. Each is a projection folding the relevant events. Queries read them:

ts
const articlesByTag = defineQuery(ArticlesByTag, {
  name: "articles.by-tag",
  input: z.object({ tag: z.string(), limit: z.number().default(20) }),
  execute: (state, { tag, limit }) =>
    (state.byTag[tag] ?? []).slice(0, limit),
})

6. Identify reactions ​

Cross-cutting policies. "When a user verifies their email, send a welcome notification." "When a payment fails, retry the next day." Each is a when():

ts
const sendWelcomeOnVerify = when(
  UserEmailVerifiedEvent,
  async (event, ctx) => ctx.send(sendNotification, { to: event.email, template: "welcome" }),
  { dispatches: [sendNotification] },
)

7. External boundaries → orchestrator primitives ​

Every fetch(...) / SDK call to an external service → defineExternalCall:

ts
const chargeStripe = defineExternalCall({
  name: "stripe.charge",
  target: { provider: "stripe", endpoint: "/v1/payment_intents" },
  request: ChargeRequest,
  response: PaymentIntent,
  idempotencyKey: (req) => `charge-${req.orderId}-${req.amount}`,
  slo: { p95LatencyMs: 600, successRate: 0.995 },
  retry: { max: 3, backoff: "exponential" },
})

Webhooks → defineInboundWebhook. Crons → defineCron. Background queues → defineQueueWorker (@nwire/queue + adapter).

8. Wire it up ​

ts
import { createApp, defineRegistry } from "@nwire/app"
import { endpoint } from "@nwire/endpoint"
import { forgePlugins } from "@nwire/forge"
import { get, post } from "@nwire/wires/http"
import { httpKoa } from "@nwire/koa"

const app = createApp({
  appName: "api",
  registry: defineRegistry({
    handlers: [createUser, verifyEmail, getUserById, listUsers],
    actors: [User],
    projections: [UsersById],
    workflows: [sendWelcomeOnVerify],
    externalCalls: [chargeStripe],
  }),
  plugins: [...forgePlugins()],
})

app.wire(post("/users", { body: createUser.input }), createUser)
app.wire(
  post("/users/:id/verify-email", { params: z.object({ id: z.string() }) }),
  verifyEmail,
)
app.wire(get("/users/:id", { params: z.object({ id: z.string() }) }), getUserById)
app.wire(get("/users"), listUsers)

await app.start()

await endpoint("api", { port: 3000 })
  .use(httpKoa({
    inspect: true,
    openapi: { auto: true, title: "My API", version: "1.0.0" },
    docs: true,
  }))
  .mount(app)
  .run()

Patterns Express devs ask about ​

"Where does my error-handling middleware go?" ​

Errors thrown by handlers go through Nwire's retry+DLQ pipeline. The HTTP wire returns a 4xx/5xx envelope automatically — you don't write a catch. For custom error shaping, use @nwire/errors + the wire's envelopeFromRequest hook.

"Where do my interceptors / before-each hooks go?" ​

runtime.use(middleware). Runs around every dispatch (HTTP, queue, CLI). For HTTP-only concerns (CORS, rate limiting, etc.) use Koa middleware on the wire's koa instance.

"What about WebSockets?" ​

Today Nwire doesn't ship a WebSocket wire. Run a separate ws server, dispatch into the Nwire runtime from ws message handlers. A first-class wire is on the roadmap.

"What about file uploads?" ​

Standard Koa body parser handles multipart. Files become inputs to actions like any other field. For large uploads + storage, use defineExternalCall to S3/GCS — Studio surfaces the upload as a boundary sticky.

"How do I migrate incrementally?" ​

Run Nwire side-by-side with Express by mounting Nwire wires as an Express Router via nwireToExpressRouter:

ts
import express from "express"
import { createApp } from "@nwire/app"
import { nwireToExpressRouter } from "@nwire/express"

const expressApp = express()
const nwireApp = createApp({ appName: "v2" })
// ... nwireApp.wire(...) for the migrated routes ...
await nwireApp.start()

expressApp.use("/api/v2", nwireToExpressRouter(nwireApp))
expressApp.listen(3000)

/api/v2/* goes to Nwire; everything else stays on Express. Migrate one controller at a time. Once Express is empty, replace the bootstrap with endpoint(...).use(httpKoa()).mount(nwireApp).run() and drop Express.

See also ​

MIT licensed.