NitroSQLite

MikroORM

Store and query MikroORM entities in a local Nitro SQLite database.

SQLite stores tables in a file on the device. MikroORM maps entities to those tables, tracks changes to the entities you load, and writes pending changes when you call flush(). The Nitro SQLite driver executes those queries asynchronously on a dedicated native connection.

Install the driver

Install the matching versions in the MikroORM quick start. The example uses MikroORM 7.2.13 and Kysely 0.29.9.

Use @mikro-orm/sql for the shared SQLite platform. The @mikro-orm/sqlite package requires the Node.js better-sqlite3 addon.

@mikro-orm/sql exposes a single entry point that also includes other SQL dialects. Account for those modules when assessing your app's bundle size.

MikroORM cursors encode with base64url, so the app's global Buffer must support it. React Native and NitroUI use different Buffer setups, described in their sections below.

Configure NitroUI

The NitroUI example prepares MikroORM as a browser bundle before the SDK bundles the app. Follow the same preparation for another NitroUI app. Install esbuild@0.28.1 as a development dependency, plus buffer@6.0.3 and reflect-metadata as app dependencies.

  1. Copy prepare-mikro-orm.mjs and mikro-environment.mjs from the repository into your app's scripts directory. Run the preparation script before starting or bundling the app:

    node scripts/prepare-mikro-orm.mjs

    The script creates .nitro/vendor/mikro-orm.js and its type declarations. It uses browser conditions for filesystem stubs and keeps SQLite, Nitro Core, and Kysely as app dependencies. Keep @mikro-orm/sql and nitro-sqlite-mikro-orm in the same browser bundle. Import the ORM and driver from that bundle so they share the same classes.

  2. Keep the environment shim used by that preparation script. MikroORM expects process.env to be an object and checks environment variable names with in. The script redirects MikroORM's environment reads to mikroOrmEnvironment, which turns a string into { NODE_ENV: value } and preserves an existing environment object. It does not replace the SDK global.

  3. Initialize Buffer with base64url support before importing ORM code. The repository's buffer.ts adapts buffer@6.0.3 for MikroORM cursor encoding. Copy that module into your app, then load it and reflect-metadata from your entry initialization:

    import 'reflect-metadata'
    import { Buffer } from './buffer'
    
    Object.assign(globalThis, { Buffer })

    Import this initialization before your app's database modules. The example uses polyfills.ts for this ordering. A plain buffer@6.0.3 global without the adapter does not support MikroORM's base64url cursor encoding.

  4. In a module such as src/database.ts, import every MikroORM entry point from the prepared bundle:

    import {
      defineEntity,
      MikroORM,
      NitroSQLiteDriver,
      p,
    } from '../.nitro/vendor/mikro-orm.js'

    The example's scripts/prepare-shared.mjs redirects its shared tests to this bundle. An app that imports the bundle directly does not need that test-source rewriting step. Pass explicit entity classes or schemas; device builds do not support filesystem entity discovery.

Configure React Native

The Metro and Babel configuration below applies to React Native. This setup uses the MIT-licensed @craftzdog/react-native-buffer package's root entry point. It supports the base64url encoding that MikroORM cursors require. The buffer@6.0.3 package does not. Quick Crypto is not required for this setup.

Quick Base64 is a native dependency. Install pods for a bare iOS app, or create a new development build for an Expo app. Expo Go cannot load this native module. The package's Node.js fallback uses base64-js, which Metro also resolves when bundling. Install it explicitly because version 6.1.2 lists it only as a development dependency. This fallback is not a native-free React Native entry point.

Configure Metro and Babel

The driver ships two build-time helpers. The Metro resolver selects MikroORM's browser stubs for filesystem access. The Babel plugin handles MikroORM's computed imports and leaves Unicode property escapes for Hermes.

This adapter requires React Native 0.88 or later. These snippets explicitly enable Metro package exports, which React Native enables by default only from 0.79. Keep exports enabled so the resolver can select MikroORM's browser stubs.

In a bare React Native app, start with your existing Metro configuration, including its resolver customizations. For a new app, use getDefaultConfig(__dirname) as below. Capture the existing resolver before wrapping it.

const { getDefaultConfig } = require('@react-native/metro-config')
const {
  resolveRequest: resolveMikroORM,
} = require('react-native-nitro-sqlite-mikro-orm/metro')

const config = getDefaultConfig(__dirname)
const previousResolveRequest = config.resolver.resolveRequest

config.resolver = {
  ...config.resolver,
  unstable_enablePackageExports: true,
  resolveRequest(context, moduleName, platform) {
    if (moduleName === 'buffer' || moduleName === 'node:buffer') {
      moduleName = '@craftzdog/react-native-buffer'
    }
    return resolveMikroORM(
      {
        ...context,
        resolveRequest(nextContext, name, targetPlatform) {
          const next = previousResolveRequest ?? context.resolveRequest
          return next(
            { ...nextContext, resolveRequest: context.resolveRequest },
            name,
            targetPlatform,
          )
        },
      },
      moduleName,
      platform,
    )
  },
}

module.exports = config

In Expo, use the same wrapper around your existing Expo configuration.

const { getDefaultConfig } = require('expo/metro-config')
const {
  resolveRequest: resolveMikroORM,
} = require('react-native-nitro-sqlite-mikro-orm/metro')

const config = getDefaultConfig(__dirname)
const previousResolveRequest = config.resolver.resolveRequest

config.resolver = {
  ...config.resolver,
  unstable_enablePackageExports: true,
  resolveRequest(context, moduleName, platform) {
    if (moduleName === 'buffer' || moduleName === 'node:buffer') {
      moduleName = '@craftzdog/react-native-buffer'
    }
    return resolveMikroORM(
      {
        ...context,
        resolveRequest(nextContext, name, targetPlatform) {
          const next = previousResolveRequest ?? context.resolveRequest
          return next(
            { ...nextContext, resolveRequest: context.resolveRequest },
            name,
            targetPlatform,
          )
        },
      },
      moduleName,
      platform,
    )
  },
}

module.exports = config

Both snippets preserve other resolver options and pass requests through your existing resolver. The Buffer aliases make dependencies that import buffer or node:buffer use the same implementation as the global below. MikroORM 7.2.13 itself reads the global Buffer.

Add babelPlugin to the plugins in babel.config.js. This example shows a bare React Native app. Keep babel-preset-expo in an Expo app.

const { babelPlugin } = require('react-native-nitro-sqlite-mikro-orm/metro')

module.exports = {
  presets: ['module:@react-native/babel-preset'],
  plugins: [babelPlugin],
}

Keep your app's existing presets and plugins. Restart Metro with a clear cache after changing either file.

Set up the Buffer implementation before importing your ORM code. For example, add this to an initialization module and import it first from the app entry point.

import { Buffer } from '@craftzdog/react-native-buffer'

globalThis.Buffer = Buffer

Assign the global even if an earlier polyfill installed Buffer. Keeping a Buffer without base64url support still breaks em.findByCursor().

Store and read an entity

This example belongs in src/database.ts of the NitroUI app prepared above. In React Native, import defineEntity, MikroORM, and p from @mikro-orm/sql, and NitroSQLiteDriver from react-native-nitro-sqlite-mikro-orm after completing the Metro setup.

import {
  defineEntity,
  MikroORM,
  NitroSQLiteDriver,
  p,
} from '../.nitro/vendor/mikro-orm.js'

const Note = defineEntity({
  name: 'Note',
  properties: { id: p.integer().primary(), title: p.string() },
})

const orm = new MikroORM({
  driver: NitroSQLiteDriver,
  dbName: 'notes.sqlite',
  entities: [Note],
})

try {
  await orm.schema.update()
  const writer = orm.em.fork()
  const note = writer.create(Note, { title: 'Packing list' })
  await writer.flush()
  const saved = await orm.em.fork().findOneOrFail(Note, note.id)
  console.log(saved.title)
} finally {
  await orm.close()
}

Use versioned migrations for production schema changes. schema.update() is shown here for a new example database.

The example above defines a Note entity and stores and reads it using separate entity manager forks. Use a fork for each independent unit of work. For a long-lived database, create the ORM once and close it after its queries and transactions finish.

A file name in dbName selects the database in the app's SQLite directory. Pass Nitro SQLite's location, readOnly, or encryptionKey in driverOptions. An encryptionKey requires a licensed SQLite SEE build.

Read large result sets

The driver loads all rows returned by a query into memory. MikroORM's em.stream() and qb.stream() are unsupported. To process a large table, fetch one page at a time. For the quick start's Note entity, use the last ID from the previous page and stop when a page is empty.

const page = await reader.find(
  Note,
  { id: { $gt: lastId } },
  { orderBy: { id: 'asc' }, limit: 100, disableIdentityMap: true },
)

Disabling the identity map keeps the entity manager from retaining earlier pages.

Wait for a database lock

SQLite allows one writer at a time. If several connections write to the same file, set a busy timeout on each connection that should wait for a lock. This example lets SQLite retry for up to five seconds before returning a busy error. MikroORM runs the hook again after reconnecting.

import { CompiledQuery, type DatabaseConnection } from 'kysely'

const orm = new MikroORM({
  driver: NitroSQLiteDriver,
  dbName: 'notes.db',
  entities: [Note],
  onCreateConnection: async (connection) => {
    const db = connection as DatabaseConnection
    await db.executeQuery(CompiledQuery.raw('PRAGMA busy_timeout = 5000'))
  },
})

Use transactions and manage the schema

SQLite transactions commit a group of writes together or roll them back together. Pass the transaction callback's entity manager to every function that does database work inside the transaction. Pass the nested callback's manager when you use a nested transaction. On Hermes, MikroORM's fallback for AsyncLocalStorage does not propagate across await.

Kysely holds the connection until the transaction callback returns. Awaiting a query on a different manager, such as await orm.em.fork().find(Note, {}) inside that callback, deadlocks. The query waits for the connection while the transaction waits for the query. Use the callback's manager instead.

await orm.em.fork().transactional(async (tx) => {
  await tx.insert(Note, { title: 'Packing list' })
  const notes = await tx.find(Note, {})
  console.log(notes)
})

List entity objects or classes directly in entities and use the synchronous ORM constructor. Keep filesystem discovery, generated migration files, and CLI tools in your development environment. To migrate an installed app, ship migration SQL with the app and run it on the device before using the new schema. See the transactions guide.

Import a SQLite dump

SQLite commits statements individually in autocommit mode. A dump can group statements with BEGIN or an outermost SAVEPOINT. Rolling back an open transaction leaves earlier commits in place.

PRAGMA foreign_keys controls foreign-key enforcement for the connection. SQLite ignores changes to it inside a transaction, and rolling back does not restore a setting changed before BEGIN. PRAGMA defer_foreign_keys postpones foreign-key checks until commit. Turning it off can clear SQLite's pending violation tracking and let invalid rows commit. SQLite resets it after a transaction ends.

SQL dumps are trusted executable SQL. orm.em.getConnection().executeDump(sql) runs the dump on the ORM connection and follows the transaction commands in the SQL. Run it outside em.transactional() callbacks. The callback holds the connection that the dump needs, so awaiting the dump inside the callback deadlocks.

The driver rejects a dump containing NUL before running any SQL. If a statement fails or the dump leaves its own transaction or outermost savepoint open, the driver rejects the import and rolls back that scope before queued work can run. A rejected dump also restores the connection's previous foreign_keys and defer_foreign_keys settings when safe. Cleanup does not restore unrelated PRAGMAs. A successful dump keeps the settings written by its statements. If you issued BEGIN yourself, finish that transaction and keep unrelated work off the connection until it ends.

If a statement fails, the import reports the original SQLite error. Before changing defer_foreign_keys during restoration, cleanup checks every attached schema, including temp, for foreign-key violations. If violations remain, it leaves deferral unchanged and blocks further queries on the handle. Cleanup never disables deferral while violations remain. It cannot recover violation tracking already cleared by the dump's own SQL. It also blocks reuse if rollback or setting restoration fails. Reconnect before running more queries on that connection. Reconnecting closes the old handle and rolls back any remaining caller-owned transaction.