Migrate from Express or Hono
Move an existing Express or Hono API into RelKit one endpoint at a time, keeping the old app serving the rest until every endpoint has moved.
Move an Orders API from Express or Hono to RelKit without a big-bang rewrite. You will keep the old app serving its endpoints, move GET /orders/:orderId and POST /orders into RelKit functions and routes, and test both.
How the pieces map
| Express or Hono | RelKit |
|---|---|
app.get("/orders/:orderId", handler) |
src/routes/orders/[orderId]/route.ts exporting GET |
| The handler body | A function in src/services/orders/functions with input and output schemas |
Validation middleware such as zod-validator |
The function’s input schema; invalid requests get a 422 response |
res.status(404).json(...) or c.json(..., 404) |
A declared error with http: { status: 404 } |
| Error-handling middleware | Declared errors, returned from the function |
app.use(middleware) for CORS, headers or rate limits |
HTTP middleware and rate limits |
app.listen(3000) |
server.port in relkit.config.ts, started with bun run dev |
supertest or app.request() in tests |
createTestApplication from @relkit/testing |
1. Keep the old app running
Start from your existing endpoint:
import express from "express";
const app = express();
app.get("/orders/:orderId", (req, res) => {
const { orderId } = req.params;
if (orderId === "missing")
return res.status(404).json({ error: `Order ${orderId} was not found` });
res.json({ orderId, status: "confirmed", totalCents: 1_000 });
});
app.listen(4000);Express handlers take Node.js request and response objects, so RelKit can’t mount an Express app directly. Keep it running on its own port and move endpoints one at a time, pointing your proxy or clients at RelKit as each one moves.
A Hono app answers a web Request with a Response, so RelKit can serve it from a raw route. Give the app a base path that isn’t used by RelKit routes:
import { Hono } from "hono";
const app = new Hono().basePath("/legacy");
app.get("/orders/:orderId", (c) => {
const orderId = c.req.param("orderId");
if (orderId === "missing") return c.json({ error: `Order ${orderId} was not found` }, 404);
return c.json({ orderId, status: "confirmed", totalCents: 1_000 });
});
app.get("/health", (c) => c.text("ok"));Then mount it with an optional catch-all route, which matches /legacy and every path below it:
/** Serves every /legacy request from the existing Hono app until its endpoints move. */
import { defineRoute } from "relkit/routes";
import legacy from "../../../legacy/app.js";
export const ALL = defineRoute({ handler: (request) => legacy.fetch(request) });Add hono to the application with bun add hono. Endpoints under /legacy keep working while you move them, but they don’t get RelKit validation, OpenAPI entries or typed client calls until they move.
2. Move the handler into a function
Declare the not-found failure once. RelKit turns it into a 404 response with a consistent body:
/** Declares the missing-order failure and its HTTP 404 status. */
import { defineError } from "relkit/functions";
import { z } from "zod";
const orderNotFound = defineError({
id: "orders.not-found",
data: z.object({ orderId: z.string() }),
message: ({ orderId }) => `Order ${orderId} was not found`,
http: { status: 404 },
});
export default orderNotFound;Move the handler body into a function. The schemas replace manual parameter checks, and the function returns the error instead of building a response:
/** Looks up one order, returning the declared not-found error for unknown identifiers. */
import { defineFunction } from "relkit/functions";
import { z } from "zod";
import orderNotFound from "../errors/order-not-found.error.js";
const getOrder = defineFunction({
input: z.object({ orderId: z.string().min(1) }),
output: z.object({ orderId: z.string(), status: z.string(), totalCents: z.number().int() }),
errors: [orderNotFound],
handler: async ({ orderId }) => {
if (orderId === "missing") return new orderNotFound({ orderId });
return { orderId, status: "confirmed", totalCents: 1_000 };
},
});
export default getOrder;3. Add the routes
Moving a POST handler works the same way. The input schema replaces your body parser and validation middleware:
/** Validates a new order and returns its calculated total. */
import { defineFunction } from "relkit/functions";
import { z } from "zod";
const createOrder = defineFunction({
input: z.object({
orderId: z.string().min(1),
sku: z.string().min(1),
quantity: z.number().int().positive(),
}),
output: z.object({ orderId: z.string(), sku: z.string(), totalCents: z.number().int() }),
handler: async ({ orderId, sku, quantity }, context) => {
context.log.info("order created", { orderId });
return { orderId, sku, totalCents: quantity * 100 };
},
});
export default createOrder;List both functions in the service, which is the boundary routes and other services call through:
/** Declares the orders service and the functions its routes may call. */
import { defineService } from "relkit/services";
import createOrder from "./functions/create-order.function.js";
import getOrder from "./functions/get-order.function.js";
export default defineService({ functions: { createOrder, getOrder } });The file path chooses the URL. [orderId] becomes a path parameter, and RelKit passes it to the function’s orderId input:
/** GET /orders/:orderId reads the path parameter into the function's input. */
import { defineRoute } from "relkit/routes";
import orders from "../../../services/orders/service.js";
export const GET = defineRoute({ target: orders.getOrder });/** POST /orders creates an order and answers 201. */
import { defineServiceRoutes } from "relkit/routes";
import orders from "../../services/orders/service.js";
export default defineServiceRoutes(orders, {
POST: { member: "createOrder", successStatus: 201 },
});File-system routes explains catch-all segments and matching order.
4. Test the moved and remaining endpoints
createTestApplication runs the whole application in memory, so one test file covers the moved endpoints and the ones still served by the old app:
/** Checks the migrated endpoints and the endpoints still served by the Hono app. */
import { afterAll, expect, test } from "bun:test";
import { resolve } from "node:path";
import { createTestApplication } from "@relkit/testing";
import config from "../relkit.config.js";
const testApp = await createTestApplication(config, {
projectRoot: resolve(import.meta.dir, ".."),
});
afterAll(() => testApp.close());
test("POST /orders validates the body and answers 201", async () => {
const response = await testApp.http.request("/orders", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ orderId: "order-1", sku: "book", quantity: 3 }),
});
expect(response.status).toBe(201);
expect(await response.json()).toEqual({ orderId: "order-1", sku: "book", totalCents: 300 });
const invalid = await testApp.http.request("/orders", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ orderId: "order-2", sku: "book", quantity: 0 }),
});
expect(invalid.status).toBe(422);
});
test("GET /orders/:orderId returns the order or the declared 404", async () => {
const found = await testApp.http.request("/orders/order-1");
expect(found.status).toBe(200);
expect(await found.json()).toEqual({
orderId: "order-1",
status: "confirmed",
totalCents: 1_000,
});
expect((await testApp.http.request("/orders/missing")).status).toBe(404);
});
test("the Hono app still serves /legacy", async () => {
const response = await testApp.http.request("/legacy/health");
expect(response.status).toBe(200);
expect(await response.text()).toBe("ok");
expect((await testApp.http.request("/legacy/orders/missing")).status).toBe(404);
});In your application, you can leave out projectRoot when you run bun test from the application root. From the application root, run:
bun run check
bun testbun run check checks the application graph, including duplicate or ambiguous routes, and reports each problem with a RELKIT_* code. The tests pass when the moved endpoints and the /legacy endpoints answer as expected.
5. Finish the move
Repeat steps 2 to 4 for each remaining endpoint. When nothing is left under /legacy, delete src/legacy and src/routes/legacy, and remove hono from the application if nothing else uses it. For an Express app, stop the old server once your proxy sends every path to RelKit.
Related tasks
- Middleware for CORS, headers and request policies.
- Better Auth to replace session middleware.
- Testing for fakes and provider replacements.
- Why RelKit and the FAQ.