Skip to content

Search docs

Jump between documentation pages.

Browse docs

Use MikroORM with DaloyJS

MikroORM is a TypeScript ORM built around a Data Mapper, Unit of Work, and Identity Map. It supports PostgreSQL, MySQL/MariaDB, SQLite, libSQL/Turso, PGlite, MSSQL, Oracle, and MongoDB. This SQL-focused guide targets MikroORM v7, PostgreSQL, and the Node.js adapter.

1. Install

Install @mikro-orm/core together with the driver package for your database. The version of every @mikro-orm/* package must match.

bash
# PostgreSQL (also CockroachDB)
pnpm add @mikro-orm/core @mikro-orm/postgresql
# or MySQL / MariaDB
pnpm add @mikro-orm/core @mikro-orm/mysql
# or SQLite
pnpm add @mikro-orm/core @mikro-orm/sqlite
# or libSQL / Turso
pnpm add @mikro-orm/core @mikro-orm/libsql
# or PGlite (embedded PostgreSQL in WASM)
pnpm add @mikro-orm/core @mikro-orm/pglite

# CLI + migrations (optional, dev-only)
pnpm add -D @mikro-orm/cli @mikro-orm/migrations

MikroORM v7 supports both ES-spec decorators and the legacy experimentalDecorators flag. The examples below use the defineEntity helper, which is decorator-free and gives you full TypeScript inference without any compiler flags.

2. Define an entity

defineEntity returns a schema object you can attach to a real class. The class gives you a named type for your handlers. The schema gives MikroORM its metadata.

ts
// src/db/entities/User.ts
import { defineEntity, p } from "@mikro-orm/core";

const UserSchema = defineEntity({
  name: "User",
  properties: {
    id: p.uuid().primary().defaultRaw("gen_random_uuid()"),
    email: p.string().unique(),
    name: p.string().nullable(),
    createdAt: p.datetime().onCreate(() => new Date()),
  },
});

export class User extends UserSchema.class {}
UserSchema.setClass(User);

3. Configure the ORM

Import defineConfig from your driver package, it infers the driver and gives you IntelliSense without extra type hints.

ts
// src/mikro-orm.config.ts
import { defineConfig } from "@mikro-orm/postgresql";
import { Migrator } from "@mikro-orm/migrations";
import { User } from "./db/entities/User.ts";

export default defineConfig({
  entities: [User],
  clientUrl: process.env.DATABASE_URL,
  // production-friendly defaults
  debug: process.env.NODE_ENV !== "production",
  extensions: [Migrator],
  migrations: {
    path: "./dist/db/migrations",
    pathTs: "./src/db/migrations",
  },
});

4. Create a MikroORM plugin

Initialize the ORM once at startup, decorate the app with the root ORM instance, and close it on shutdown. Handlers get their own forked EntityManager in step 5.

ts
// src/db/plugin.ts
import type { App } from "@daloyjs/core";
import { MikroORM } from "@mikro-orm/postgresql";
import config from "../mikro-orm.config.ts";

// Call with the root app, not through app.register(): a decoration made
// inside a registered plugin is visible only to that plugin's own routes.
export async function mikroOrmPlugin(app: App) {
  const orm = await MikroORM.init(config);
  app.decorate("orm", orm);
  app.onClose(async () => {
    await orm.close(true);
  });
}

5. Fork an EntityManager per request

MikroORM relies on an Identity Map that is bound to an EntityManager. You must fork the root EM for every request so identity maps and unit-of-work state do not leak between concurrent handlers. Do it in middleware and expose the forked EM on state.

A forked EntityManager per request
  1. 01startupRoot ORMstate.orm = await MikroORM.init(...)
  2. 02beforeHandleFork per requeststate.em = state.orm.em.fork()
  3. 03handlerScoped queriesstate.em.create / findOne
  4. 04unit of workPersist on flushawait state.em.flush()
The plugin function decorates the root app with one root ORM at startup. A beforeHandle hook forks a fresh EntityManager for each request onto state.em, so the identity map and unit-of-work state stay isolated, then a single flush() (or transactional()) persists the changes.
ts
// src/db/middleware.ts
import type { Hooks } from "@daloyjs/core";

export function requestEntityManager(): Hooks {
  return {
    beforeHandle(ctx) {
      ctx.state.em = ctx.state.orm.em.fork();
    },
  };
}

In Express-style middleware you will often see RequestContext.create(orm.em, next). Daloy hooks pass typed request state directly, so the simplest pattern is to use the forked state.em inside handlers.

6. Augment app state types

Add the declare module block to the same module that creates the plugin, not to a separate .d.ts file. Declaration files are exempt from type-checking when skipLibCheck is on (the scaffolded default), so a broken import inside a .d.ts fails silently and state.orm / state.em degrade to any.

ts
// src/db/plugin.ts (same module as the plugin above)
import type { EntityManager } from "@mikro-orm/postgresql";

declare module "@daloyjs/core" {
  interface AppState {
    orm: MikroORM;
    em: EntityManager;
  }
}

7. Use the EntityManager in routes

ts
// src/server.ts
import { z } from "zod";
import { App, NotFoundError } from "@daloyjs/core";
import { serve } from "@daloyjs/core/node";
import { mikroOrmPlugin } from "./db/plugin.ts";
import { requestEntityManager } from "./db/middleware.ts";
import { User } from "./db/entities/User.ts";

const app = new App();
await mikroOrmPlugin(app);
// Register before the routes: app.use() only applies to routes added after it.
app.use(requestEntityManager());

// Dates go over the wire as ISO strings: z.coerce.date() has no
// representation in the generated OpenAPI document.
const UserSchema = z.object({
  id: z.uuid(),
  email: z.email(),
  name: z.string().nullable(),
  createdAt: z.iso.datetime(),
});

const toUser = (user: User) => ({
  id: user.id,
  email: user.email,
  name: user.name ?? null,
  createdAt: user.createdAt.toISOString(),
});

app.get(
  "/users/:id",
  {
    operationId: "getUser",
    request: { params: z.object({ id: z.uuid() }) },
    responses: {
      200: { description: "Found", body: UserSchema },
      404: { description: "Not found" },
    },
  },
  async ({ params, state }) => {
    const user = await state.em.findOne(User, { id: params.id });
    if (!user) throw new NotFoundError("User not found");
    return { status: 200, body: toUser(user) };
  },
);

app.post(
  "/users",
  {
    operationId: "createUser",
    request: { body: z.object({ email: z.email(), name: z.string().optional() }) },
    responses: { 201: { description: "Created", body: UserSchema } },
  },
  async ({ body, state }) => {
    const user = state.em.create(User, { email: body.email, name: body.name ?? null });
    await state.em.flush();
    return { status: 201, body: toUser(user) };
  },
);

await app.ready();
serve(app, { port: 3000 });

MikroORM batches every change in the forked EM into a single flush(). You almost never need to call persist() manually when using em.create(), which auto-persists in v6+. Entities created with new User() still need em.persist().

Transactions

Use em.transactional() inside the handler that owns the unit of work. The callback receives a transactional EM that commits on success and rolls back if you throw. This example assumes Order and Inventory entities defined like User above and a route that declares 201.

ts
import { Inventory } from "./db/entities/Inventory.ts";
import { Order } from "./db/entities/Order.ts";

handler: async ({ body, state }) => {
  const order = await state.em.transactional(async (em) => {
    const created = em.create(Order, { sku: body.sku, qty: body.qty });
    const inventory = await em.findOneOrFail(Inventory, { sku: body.sku });
    inventory.stock -= body.qty;
    return created;
  });
  return { status: 201, body: { id: order.id, sku: order.sku, qty: order.qty } };
}

Migrations

The CLI is installed as a dev dependency and reads src/mikro-orm.config.ts by default. If you move the config under src/db, pass --config or configure mikro-orm.configPaths in package.json.

bash
# generate a migration from the current entity diff
pnpm mikro-orm migration:create

# apply all pending migrations
pnpm mikro-orm migration:up

# list pending migrations
pnpm mikro-orm migration:pending

# inspect the resolved CLI config
pnpm mikro-orm debug

Errors

Translate MikroORM errors into framework errors so they serialize as problem+json. MikroORM also exports a class named NotFoundError (thrown by findOneOrFail()), so alias it on import to avoid shadowing the DaloyJS one. Declare 404 and 409 in the route's responses.

ts
import { ConflictError, NotFoundError } from "@daloyjs/core";
import {
  NotFoundError as MikroNotFoundError,
  UniqueConstraintViolationException,
} from "@mikro-orm/core";

try {
  const user = state.em.create(User, { email: body.email, name: body.name ?? null });
  await state.em.flush();
  return { status: 201, body: toUser(user) };
} catch (err) {
  if (err instanceof UniqueConstraintViolationException) {
    throw new ConflictError("User already exists");
  }
  if (err instanceof MikroNotFoundError) {
    throw new NotFoundError();
  }
  throw err;
}

Runtime notes

  • This guide is tested against the Node.js adapter. MikroORM v7's JSR listings advertise Cloudflare Workers, Deno, and Bun support, but we have not verified any of them with DaloyJS, so most Workers apps should start with Drizzle or Supabase instead.
  • onClose() runs on the Node.js, Bun, and Deno adapters only; see Serverless and edge lifecycle.
  • Run migration:up as a deploy step, never at app boot (see migrations).
  • Always fork the EM per request. Sharing the root EM across requests will leak the identity map and corrupt unit-of-work state.
  • Keep @mikro-orm/core, your driver package, the CLI, and @mikro-orm/migrations on the same version.

Compare with Prisma, Drizzle, TypeORM, Sequelize, Kysely, Supabase, or the ODM overview for document databases.

Edit this page on GitHub

Last updated