---
title: Migrate from Express or Hono
description: 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.
pagination: false
search:
  keywords: [migration, Express, Hono, port an existing API, incremental migration]
sidebar:
  icon: arrow-right-left
---

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.

> **Before you begin**
>
> You need Bun **1.3.10 or later** and a RelKit application. Create one with `bunx
> create-relkit@latest my-api --template api`, or follow [Create and run an
> API](/docs/learn/create-an-app). The complete example lives in
> [`apps/docs/examples/migrate`](https://github.com/rel-kit/relkit/tree/main/apps/docs/examples/migrate),
> and its tests run with the documentation test suite.

## 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](/docs/modules/http/middleware) and [rate limits](/docs/modules/http/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. ## 1. Keep the old app running [#keep-the-old-app-running]

    Start from your existing endpoint:

    **Express**

    ```ts title="server.ts — Express"
    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.

    **Hono**

    A Hono app answers a web `Request` with a `Response`, so RelKit can serve it from a [raw route](/docs/modules/http/raw-handlers). Give the app a base path that isn't used by RelKit routes:

    ```ts title="src/legacy/app.ts"
    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:

    ```ts title="src/routes/legacy/[[...path]]/route.ts"
    /** 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. ## 2. Move the handler into a function [#move-the-handler]

    Declare the not-found failure once. RelKit turns it into a 404 response with a consistent body:

    ```ts title="src/services/orders/errors/order-not-found.error.ts"
    /** 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:

    ```ts title="src/services/orders/functions/get-order.function.ts"
    /** 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. ## 3. Add the routes [#add-the-routes]

    Moving a `POST` handler works the same way. The `input` schema replaces your body parser and validation middleware:

    ```ts title="src/services/orders/functions/create-order.function.ts"
    /** 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:

    ```ts title="src/services/orders/service.ts"
    /** 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:

    ```ts title="src/routes/orders/[orderId]/route.ts"
    /** 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 });
    ```

    ```ts title="src/routes/orders/route.ts"
    /** 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](/docs/modules/http/routes) explains catch-all segments and matching order.

4. ## 4. Test the moved and remaining endpoints [#test-the-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:

    ```ts title="tests/integration/orders.route.test.ts"
    /** 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:

    ```sh title="Terminal — application root"
    bun run check
    bun test
    ```

    `bun 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. ## 5. Finish the move [#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](/docs/modules/http/middleware) for CORS, headers and request policies.
- [Better Auth](/docs/modules/auth/better-auth) to replace session middleware.
- [Testing](/docs/modules/operations/testing) for fakes and provider replacements.
- [Why RelKit](/docs/why-relkit) and the [FAQ](/docs/faq).

{/* Generated by apps/docs/scripts/generate.ts. Do not edit. */}

**Reference and source**

- [`relkit/functions` API](/docs/api/functions)
- [`relkit/routes` API](/docs/api/routes)
- [`@relkit/testing` API](/docs/api/testing)

- [`apps/docs/examples/migrate/src/routes/legacy/[[...path]]/route.ts`](https://github.com/rel-kit/relkit/blob/main/apps/docs/examples/migrate/src/routes/legacy/[[...path]]/route.ts)
- [`apps/docs/examples/migrate/src/services/orders/functions/get-order.function.ts`](https://github.com/rel-kit/relkit/blob/main/apps/docs/examples/migrate/src/services/orders/functions/get-order.function.ts)
- [`apps/docs/examples/migrate/tests/orders.route.test.ts`](https://github.com/rel-kit/relkit/blob/main/apps/docs/examples/migrate/tests/orders.route.test.ts)
