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
Use matching MikroORM packages. This setup uses MikroORM 7.2.13 and Kysely 0.29.9.
npm install react-native-nitro-sqlite react-native-nitro-sqlite-mikro-orm @mikro-orm/core@7.2.13 @mikro-orm/sql@7.2.13 kysely@0.29.9 @craftzdog/react-native-buffer@6.1.2 react-native-quick-base64@3.0.1 base64-js@1.5.1Use @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.
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.
Nitro SQLite requires React Native 0.75 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 = configIn 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 = configBoth 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 JavaScript 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 = BufferAssign the global even if an earlier polyfill installed Buffer. Keeping a Buffer without base64url support still breaks em.findByCursor().
Store and read an entity
A file name in dbName selects the database in the app's SQLite directory. The driver accepts Nitro SQLite's location, readOnly, and encryptionKey options in driverOptions. An encryptionKey requires a licensed SQLite SEE build.
import { defineEntity, MikroORM, p } from '@mikro-orm/sql'
import { NitroSQLiteDriver } from 'react-native-nitro-sqlite-mikro-orm'
const Note = defineEntity({
name: 'Note',
properties: {
id: p.integer().primary(),
title: p.string(),
},
})
const orm = new MikroORM({
driver: NitroSQLiteDriver,
dbName: 'notes.db',
entities: [Note],
})
try {
// Create or update the schema for this example.
await orm.schema.update()
const writer = orm.em.fork()
const note = writer.create(Note, { title: 'Packing list' })
await writer.flush()
const reader = orm.em.fork()
const saved = await reader.findOneOrFail(Note, note.id)
console.log(saved.title)
} finally {
await orm.close()
}For a long-lived database, create the ORM once and close it after its queries and transactions finish. Use an entity manager fork for each independent unit of work.
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 Note entity above, 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.