Cloudflare
On Cloudflare Workers, your Postgres is reached through Hyperdrive, which pools the connections and hands each request a connection string through a binding. In nuxt dev the app runs on Node, and the development socket stands in for it. One useDB(event) covers both: a pool over DATABASE_URL in development, a client per request over Hyperdrive on Workers. import.meta.dev picks the branch when the app is built, so the Workers build only carries its own.
This recipe needs Nuxt 4.6 or later, or Nuxt 5, a Cloudflare account, and a Postgres that Cloudflare can reach.
How it fits together
nuxt dev | Deployed on Workers | |
|---|---|---|
| Runs on | Node | Workers |
| Connection | one pool over DATABASE_URL, the socket's unless already set | one client per request over env.HYPERDRIVE.connectionString |
| Database | PGlite, behind the socket | your Postgres, through Hyperdrive |
server/pglite.config.ts | loaded by the socket | not bundled |
| Migrations | applied by init with applyMigrations | applied by you, from CI or the build |
The routes only know Drizzle over pg. Nothing else changes between development and production.
What ends up in the build
.output/server | |
|---|---|
| PGlite engine and WebAssembly | absent (server.enabled: false) |
server/pglite.config.ts | absent: only the socket reads it, in nuxt dev |
| The development pool | absent: import.meta.dev is false in the build |
pg and drizzle-orm | bundled |
wrangler.json | your wrangler.jsonc, with the entry and the static assets added |
The build also writes .wrangler/deploy/config.json, which points Wrangler at .output/server/wrangler.json: run wrangler deploy and wrangler dev from the app's root, and keep .wrangler out of git.
Steps
Install the driver and Wrangler
npm i pg drizzle-orm
npm i -D wrangler @cloudflare/workers-types @types/pg
Hyperdrive needs pg 8.16.3 or later.
Configure Nuxt
export default defineNuxtConfig({
modules: ['nuxt-pglite'],
pglite: {
server: {
enabled: false, // nothing of PGlite in the Workers build
},
socket: { port: 5433 }, // `DATABASE_URL` while `nuxt dev` runs
},
nitro: {
preset: 'cloudflare_module',
devServer: { runner: 'node-worker' },
},
})
export default defineNuxtConfig({
modules: ['nuxt-pglite'],
pglite: {
server: {
enabled: false, // nothing of PGlite in the Workers build
},
socket: { port: 5433 }, // `DATABASE_URL` while `nuxt dev` runs
},
nitro: {
preset: 'cloudflare_module',
alias: { 'pg-native': 'unenv/mock/empty' },
cloudflare: { deployConfig: true },
},
})
On Nuxt 5, devServer.runner keeps nuxt dev on Node, next to the socket: without it, the preset runs the app in a local Workers runtime.
On Nuxt 4, nuxt dev already runs on Node, and two other settings are needed. pg-native is pg's optional native binding, which pg never loads unless asked to, but Nitro 2 bundles it anyway and Workers cannot load it: the alias replaces it with an empty module. cloudflare.deployConfig makes the build write .output/server/wrangler.json and the .wrangler/deploy/config.json that points to it, which Nitro 2 only does by itself on Cloudflare's own build servers.
Create the Hyperdrive configuration
Point Hyperdrive at your database:
npx wrangler hyperdrive create my-app-db --connection-string="postgres://app:secret@db.example.com:5432/app"
The command prints an id. Bind it as HYPERDRIVE, with nodejs_compat, which pg needs:
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "my-app",
"compatibility_date": "2026-10-19",
"compatibility_flags": ["nodejs_compat"],
"hyperdrive": [
{
"binding": "HYPERDRIVE",
"id": "<the id printed by wrangler hyperdrive create>",
"localConnectionString": "postgres://postgres:postgres@127.0.0.1:5433/postgres"
}
]
}
localConnectionString is the database the binding connects to when Wrangler runs the app locally: the socket here. nuxt dev reads DATABASE_URL, not this, but on Nuxt 4 the Cloudflare emulation it starts logs an error without one. Wrangler requires a password in the URL, and the socket accepts any.
wrangler.jsonc: Nitro reads the file to merge it into the build, and its parser rejects them.Type the binding where the server routes and the app's typed useFetch both see it: cloudflare.d.ts at the root of the app on Nuxt 5, shared/types/cloudflare.d.ts on Nuxt 4.
/// <reference types="@cloudflare/workers-types" />
declare namespace Cloudflare {
interface Env {
HYPERDRIVE: Hyperdrive
}
}
--caching-disabled to wrangler hyperdrive create. See Query caching.Write the schema and prepare the development database
import { pgTable, serial, timestamp } from 'drizzle-orm/pg-core'
export const visits = pgTable('visits', {
id: serial('id').primaryKey(),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
})
import { defineRelations } from 'drizzle-orm'
import * as schema from './schema'
export const relations = defineRelations(schema)
Generate the migrations with drizzle-kit generate, as for any Postgres, and let init apply them to the socket's instance:
import { fileURLToPath } from 'node:url'
import { applyMigrations } from 'nuxt-pglite/migrations'
const migrations = fileURLToPath(new URL('./database/migrations', import.meta.url))
export default definePGliteServerConfig({
init: (pg) => applyMigrations(pg, migrations),
})
Connect to the database
The same file works on Nuxt 4 and Nuxt 5:
import { drizzle } from 'drizzle-orm/node-postgres'
import type { RequestEvent } from 'nuxt/server'
import { Client, Pool } from 'pg'
import { relations } from '../database/relations'
import * as schema from '../database/schema'
function connect(client: Client | Pool) {
return drizzle({ client, relations })
}
export type DB = ReturnType<typeof connect>
declare module 'nuxt/schema' {
interface RequestEventContext {
db?: Promise<DB>
}
}
let pool: DB | undefined
let env: Promise<Partial<Cloudflare.Env> | undefined> | undefined
/** A client for this request only, over the Hyperdrive binding. */
async function connectRequest() {
// `cloudflare:workers` only resolves on Workers.
env ??= import('cloudflare:workers').then(
(m) => m.env,
() => undefined,
)
const url = (await env)?.HYPERDRIVE?.connectionString ?? process.env.DATABASE_URL
if (!url) {
throw new Error('No database: neither a HYPERDRIVE binding nor DATABASE_URL is set.')
}
const client = new Client({ connectionString: url })
await client.connect()
return connect(client)
}
/** Drizzle over a pool in development, over a client per request in production. */
export async function useDB(event: Pick<RequestEvent, 'context'>): Promise<DB> {
if (import.meta.dev) {
const url = process.env.DATABASE_URL
if (!url) {
throw new Error('No database: DATABASE_URL is not set.')
}
return (pool ??= connect(new Pool({ connectionString: url })))
}
return (event.context.db ??= connectRequest())
}
export const tables = schema
In nuxt dev, useDB returns Drizzle over one pool on DATABASE_URL, created on the first call. In the build, the first useDB(event) of a request opens a client on the HYPERDRIVE binding's connection string, and the rest of the request reuses it. There is nothing to close: Workers close the request's connection once it is over, and Hyperdrive keeps its own connections to your database open between requests.
To run nuxt dev against a real database, a staging one for instance, set DATABASE_URL in .env. The socket leaves a variable that is already set alone, and warns that it is taken; the pool connects to your database instead. Remove the line to return to PGlite. init does not run against that database.
Use it in routes
Import defineEventHandler from nuxt/server on Nuxt 5; on Nuxt 4 it is auto-imported. A route that records a visit, in server/api/visits.post.ts:
import { defineEventHandler } from 'nuxt/server'
import { tables, useDB } from '../utils/db'
export default defineEventHandler(async (event) => {
const db = await useDB(event)
const [visit] = await db.insert(tables.visits).values({}).returning()
return visit
})
import { tables, useDB } from '../utils/db'
export default defineEventHandler(async (event) => {
const db = await useDB(event)
const [visit] = await db.insert(tables.visits).values({}).returning()
return visit
})
One that lists them, in server/api/visits.get.ts, without the nuxt/server import on Nuxt 4:
import { count, desc } from 'drizzle-orm'
import { defineEventHandler } from 'nuxt/server'
import { tables, useDB } from '../utils/db'
export default defineEventHandler(async (event) => {
const db = await useDB(event)
const [latest, [totals]] = await Promise.all([
db.select().from(tables.visits).orderBy(desc(tables.visits.id)).limit(5),
db.select({ total: count() }).from(tables.visits),
])
return { total: totals?.total ?? 0, latest }
})
Apply the migrations to your database
Hyperdrive does not apply migrations: you do. Run drizzle-kit migrate from CI or the build command, with DATABASE_URL set to your database's own connection string, the one you gave wrangler hyperdrive create. See Any Postgres for both.
Build and deploy
npx nuxt build
npx wrangler deploy
wrangler deploy finds the build through .wrangler/deploy/config.json, and uploads the Worker with its HYPERDRIVE binding.
When a route fails with "No database: neither a HYPERDRIVE binding nor DATABASE_URL is set.", the Worker has no HYPERDRIVE binding: check wrangler.jsonc. In nuxt dev, "No database: DATABASE_URL is not set." means the socket is not running.
Testing
The @nuxt/test-utils recipe applies, with a database from a vitest globalSetup file. @nuxt/test-utils starts the built app with node .output/server/index.mjs, which a Workers build is not, so build the suite's app for Node. The build takes the production branch of useDB, which finds no binding on Node and reads the suite's DATABASE_URL: the per-request client is what the suite tests.
import { fileURLToPath } from 'node:url'
import { $fetch, setup } from '@nuxt/test-utils/e2e'
import { describe, expect, inject, it } from 'vitest'
describe('/api/visits', async () => {
const { env } = inject('pglite')
await setup({
rootDir: fileURLToPath(new URL('..', import.meta.url)),
server: true,
nuxtConfig: { nitro: { preset: 'node-server', builtinModules: ['cloudflare:workers'] } },
env,
})
it('starts with no visits', async () => {
expect(await $fetch('/api/visits')).toEqual({ total: 0, latest: [] })
})
})
import { fileURLToPath } from 'node:url'
import { $fetch, setup } from '@nuxt/test-utils/e2e'
import { describe, expect, inject, it } from 'vitest'
describe('/api/visits', async () => {
const { env } = inject('pglite')
await setup({
rootDir: fileURLToPath(new URL('..', import.meta.url)),
server: true,
nuxtConfig: { nitro: { preset: 'node-server' } },
env,
})
it('starts with no visits', async () => {
expect(await $fetch('/api/visits')).toEqual({ total: 0, latest: [] })
})
})
On Nuxt 5, builtinModules lets the Node build leave cloudflare:workers unresolved, where it would otherwise fail; Nuxt 4 leaves it unresolved by itself.
Preview the build locally
wrangler dev runs the build in a local Workers runtime, where the HYPERDRIVE binding connects to the localConnectionString of wrangler.jsonc: the socket, with nuxt dev running in another terminal. To preview against another database, set CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE, which takes precedence:
npx nuxt build
CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE=postgres://postgres:postgres@127.0.0.1:5432/postgres npx wrangler dev
This is a check of the Workers build, not a way to develop: nuxt dev is.