Recipes

Nitro's useDatabase

Point Nitro's experimental database layer at the development socket, with the same connector in production.

Nitro ships a database layer, useDatabase() over db0, experimental in Nitro 2 and 3. The module does not register anything with it: db0's pglite connector opens an instance of its own, which cannot share a data directory with the socket or usePGlite(). Its postgresql connector over the socket URL works, and the same connector reaches your real Postgres in production.

Configuration

nitro.database is build-time configuration, so the development entry pins the socket port rather than reading the variable the socket exports later:

nuxt.config.ts
export default defineNuxtConfig({
  modules: ['nuxt-pglite'],
  pglite: { socket: { port: 5455 } },
  nitro: {
    experimental: { database: true },
    database: {
      default: { connector: 'postgresql', options: { url: process.env.DATABASE_URL! } },
    },
  },
  $development: {
    nitro: {
      database: {
        default: {
          connector: 'postgresql',
          options: { url: 'postgres://postgres@127.0.0.1:5455/postgres' },
        },
      },
    },
  },
})

Install db0 and pg. In production DATABASE_URL is read when the app is built, so it has to be set in the build environment as well as at runtime.

On Nuxt 5 (Nitro 3) the development entry is nitro.devDatabase, which replaces database in nuxt dev, and useDatabase is imported from nitro/database rather than auto-imported.

Usage

server/api/ping.get.ts
export default defineEventHandler(async () => {
  const db = useDatabase()
  const { rows } = await db.sql`SELECT now() AS at`
  return rows?.[0]
})

Migrations are not part of db0: apply them from init with applyMigrations, as with any other driver.