Since 01-04, the events have lived in an array with a simulated wait. That decision had a purpose: making the pages depend on a set of signatures rather than on a source. Now it's time to check whether it worked. In this lesson AgendaViva moves to PostgreSQL, and no page should notice.
We'll use Drizzle, a lightweight ORM in which the schema is TypeScript and the queries look like SQL. You'll see the full journey: a local database, the schema, migrations, seed data, a connection that survives Fast Refresh, rewriting the queries with indexes and pagination, and how Cache Components treats a query. The schema will already include users and bookings, which will be used in modules 6 and 8.
- Why an ORM, and why this one
You can talk to PostgreSQL with the pg driver and hand-written SQL. You lose the types: the result is any, and renaming a column doesn't break any build. An ORM provides types, safe query building and, almost always, migrations.
| Hand-written SQL | Drizzle | ORM with its own model (Prisma, TypeORM…) | |
|---|---|---|---|
| Result types | None | Inferred from the query | Generated or via decorators |
| Distance from SQL | None | Small: you know what runs | Larger |
| Migrations | Separate | drizzle-kit |
Included |
| Schema | SQL files | TypeScript | Its own language or classes |
Choosing Drizzle is a teaching decision: it lets you see the SQL, which is what's worth understanding. Everything explained about connections, layers and Cache Components applies to any other ORM.
A word of warning about versions. The stable version published on npm, which is the one this course uses, is 0.45, with drizzle-kit 0.31. Version 1.0 is at the release candidate stage, and the official documentation already installs @rc in its examples. We'll rely on the most established part, the select, insert, update and delete builders with explicit column names, and we'll avoid relational queries, which change with 1.0. Pin the versions when you install:
npm install [email protected] pg
npm install -D [email protected] tsx @types/pg @next/env@16pg is the PostgreSQL driver for Node. Next.js keeps it out of the server bundle without you configuring anything, because it's on its list of external packages. tsx runs TypeScript scripts outside Next.js, and @next/env loads the .env files with the same rules as the framework.
- PostgreSQL on your machine
With Docker, one file at the root is enough. Whoever joins the project will have the same version as everyone else:
# compose.yaml
services:
db:
image: postgres:18
environment:
POSTGRES_USER: agendaviva
POSTGRES_PASSWORD: agendaviva_local
POSTGRES_DB: agendaviva
ports:
- '127.0.0.1:5432:5432'
volumes:
- db-data:/var/lib/postgresql
volumes:
db-data:docker compose up -d # starts in the background
docker compose stop # stops, keeps the data
docker compose down -v # also deletes the data127.0.0.1:publishes the port only on your machine. Without that prefix it would be reachable from the network.- The volume is mounted at
/var/lib/postgresql. That's the location the image has used since version 18; in earlier ones it was/var/lib/postgresql/data, and mixing them up means the data doesn't persist. - The password is in the repository because it's only good for a local, empty database. The production one is never written in any versioned file.
The connection string is one more secret. Add it to .env.local and to the template:
# .env.local
DATABASE_URL=postgresql://agendaviva:agendaviva_local@localhost:5432/agendaviva
# Artificial pause on every query, in milliseconds; 0 in production
QUERY_DELAY_MS=300In lib/env.ts, bring in readRequired, which you wrote in exercise 2 of 03-05, and two fields:
// lib/env.ts
export interface Env {
siteNotice: string | null
maxSpotsPerBooking: number
weatherUrl: string | null
weatherKey: string | null
databaseUrl: string
queryDelay: number
}
// In the object readEnv returns
databaseUrl: readRequired('DATABASE_URL'),
queryDelay: readInteger('QUERY_DELAY_MS', {
defaultValue: 0,
min: 0,
max: 10_000,
}),Since instrumentation.ts calls readEnv, from now on the server won't start without DATABASE_URL. The delay replaces the pause in simulateQuery: a local database responds in one or two milliseconds, and you wouldn't see any loading state. It's a learning tool; when the variable is missing it's zero.
- The schema
The schema describes the tables in TypeScript. The migrations and the query types come from it. First, two lists in lib/types.ts become values, as CATEGORIES already was, so they can be used to create PostgreSQL enumerated types:
// lib/types.ts (replaces the EventStatus and Role types)
export const EVENT_STATUSES = ['draft', 'review', 'published', 'canceled'] as const
export type EventStatus = (typeof EVENT_STATUSES)[number]
export const ROLES = ['visitor', 'organizer', 'admin'] as const
export type Role = (typeof ROLES)[number]// lib/db/schema.ts — no 'server-only': drizzle-kit and the scripts use it too
import { sql } from 'drizzle-orm'
import {
boolean, check, index, integer, pgEnum, pgTable, text, timestamp, unique,
} from 'drizzle-orm/pg-core'
import { CATEGORIES, EVENT_STATUSES, ROLES } from '../types'
export const categoryEnum = pgEnum('category', CATEGORIES)
export const eventStatusEnum = pgEnum('event_status', EVENT_STATUSES)
export const roleEnum = pgEnum('role', ROLES)
const generatedId = sql`gen_random_uuid()::text`
export const venues = pgTable('venues', {
id: text('id').primaryKey().default(generatedId),
slug: text('slug').notNull().unique(),
name: text('name').notNull(),
district: text('district').notNull(),
address: text('address').notNull(),
capacity: integer('capacity').notNull(),
outdoor: boolean('outdoor').notNull().default(false),
})
export const users = pgTable('users', {
id: text('id').primaryKey().default(generatedId),
name: text('name').notNull(),
email: text('email').notNull().unique(),
role: roleEnum('role').notNull().default('visitor'),
})
export const events = pgTable(
'events',
{
id: text('id').primaryKey().default(generatedId),
slug: text('slug').notNull().unique(),
title: text('title').notNull(),
summary: text('summary').notNull(),
description: text('description').notNull(),
category: categoryEnum('category').notNull(),
startsAt: timestamp('starts_at', { withTimezone: true }).notNull(),
endsAt: timestamp('ends_at', { withTimezone: true }).notNull(),
venueId: text('venue_id').notNull().references(() => venues.id),
organizerId: text('organizer_id').notNull().references(() => users.id),
capacity: integer('capacity').notNull(),
spotsLeft: integer('spots_left').notNull(),
image: text('image'),
status: eventStatusEnum('status').notNull().default('draft'),
},
(table) => [
index('events_status_starts_at_idx').on(table.status, table.startsAt),
index('events_venue_idx').on(table.venueId),
index('events_organizer_idx').on(table.organizerId),
check('events_ends_after_start', sql`${table.endsAt} > ${table.startsAt}`),
check('events_valid_spots', sql`${table.spotsLeft} between 0 and ${table.capacity}`),
],
)
export const bookings = pgTable(
'bookings',
{
id: text('id').primaryKey().default(generatedId),
eventId: text('event_id').notNull().references(() => events.id),
userId: text('user_id').notNull().references(() => users.id),
spots: integer('spots').notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
unique('bookings_event_user').on(table.eventId, table.userId),
index('bookings_user_idx').on(table.userId),
check('bookings_positive_spots', sql`${table.spots} > 0`),
],
)The decisions, and the reasons behind them:
- It doesn't have
server-only.drizzle-kitand the scripts import it outside Next.js, where that marker doesn't exist (03-05). It doesn't contain secrets either: it's the shape of the tables. The connection module is the one that carries the marker. - The import is relative,
'../types'. The@/alias is resolved by Next.js; don't count on every tool that reads this file understanding it. - Properties in camelCase, columns in lowercase with underscores. The first argument of each column is its name in the database.
timestampwithwithTimezone. It stores an instant, not a wall-clock time, and Drizzle returns it as aDate. Without a time zone, the result would depend on the server's configuration.- The database generates the
idvalues withgen_random_uuid(). Producing random values in a Server Component has its own rules under Cache Components; this way you don't have to think about it. - The constraints repeat what the code will also check.
spots_leftcan't go negative even if two bookings happen at the same time. When that case arrives, in module 6, the database will be the last line of defense. uniqueon event and user: a person has at most one booking per event. That constraint creates an index, which also serves to look up by event.
Two things are deliberately missing. users doesn't store passwords: that column will be added in 08-02. And events has exactly the fields of AgendaEvent, so a row is an AgendaEvent with no conversion.
3.1. The indexes
An index avoids scanning the whole table, at the cost of taking up space and making writes more expensive. You create them for the queries that exist:
| Query | Index |
|---|---|
Event page by slug |
The one from unique |
| Published by date (home page, guide) | (status, starts_at): filters by the first and returns rows already sorted by the second |
| A venue's events | venue_id |
| An organizer's events | organizer_id |
| A person's bookings | user_id |
PostgreSQL creates indexes for primary keys and unique constraints, but not for foreign keys: hence the last three. Text search, an ILIKE '%…%', doesn't use any of these. With a few thousand events it doesn't matter; if it grew, there's the pg_trgm extension.
- Migrations
A migration is an SQL file that takes the database from one state to the next. It's versioned with the code and applied in order, the same way on your machine as in production. Drizzle generates them by comparing the schema with the latest snapshot.
The configuration is read outside Next.js, so the environment has to be loaded by hand:
// lib/db/load-env.ts — only for tools outside Next.js
import { loadEnvConfig } from '@next/env'
loadEnvConfig(process.cwd())// drizzle.config.ts
import './lib/db/load-env'
import { defineConfig } from 'drizzle-kit'
const url = process.env.DATABASE_URL
if (!url) throw new Error('Missing variable DATABASE_URL. See .env.example')
export default defineConfig({
dialect: 'postgresql',
schema: './lib/db/schema.ts',
out: './drizzle',
dbCredentials: { url },
})The loading is in a separate module because imports are evaluated before the rest of the file. Add the scripts and create the first migration:
{
"db:generate": "drizzle-kit generate",
"db:migrate": "drizzle-kit migrate",
"db:seed": "tsx scripts/seed.ts",
"db:studio": "drizzle-kit studio"
}npm run db:generate -- --name initial # creates drizzle/0000_initial.sql
npm run db:migrate # applies itOpen the generated SQL and read it. You'll see the CREATE TYPE statements, the tables, the foreign keys and the indexes. It's a habit worth keeping: renaming a column, for example, can be interpreted as dropping one and creating another, and the tool will ask you about it. Applied migrations are recorded in a table, drizzle.__drizzle_migrations, so they aren't repeated.
There's a shortcut, drizzle-kit push, which applies the schema without generating files. It's handy for trying out ideas locally, but it leaves no record: don't use it on a database you share. And a migration that has already been applied in production isn't edited; it's fixed with a new one.
The drizzle/ folder, including meta/, is versioned. When 1.0 arrives, its format will change and drizzle-kit up will convert it.
- The seed data
Move the venues and events arrays from memory.ts to scripts/seed-data.ts, along with EventData and createEvent, without simulateQuery or the server-only marker, and with a relative type import ('../lib/types'). Add the users:
// scripts/seed-data.ts (addition)
export const users: User[] = [
{ id: 'usr-01', name: 'Test Visitor', email: '[email protected]', role: 'visitor' },
{ id: 'usr-02', name: 'Mill Association', email: '[email protected]', role: 'organizer' },
{ id: 'usr-03', name: 'Municipal Choir', email: '[email protected]', role: 'organizer' },
{ id: 'usr-04', name: 'Administration', email: '[email protected]', role: 'admin' },
]// scripts/seed.ts
import '../lib/db/load-env'
import { drizzle } from 'drizzle-orm/node-postgres'
import { Pool } from 'pg'
import * as schema from '../lib/db/schema'
import { events, venues, users } from './seed-data'
async function seed(): Promise<void> {
const url = process.env.DATABASE_URL
if (!url) throw new Error('Missing variable DATABASE_URL')
if (!['localhost', '127.0.0.1'].includes(new URL(url).hostname)) {
throw new Error('Seeding deletes the data: it is only allowed locally')
}
const pool = new Pool({ connectionString: url })
const db = drizzle({ client: pool })
try {
await db.transaction(async (tx) => {
await tx.delete(schema.bookings)
await tx.delete(schema.events)
await tx.delete(schema.users)
await tx.delete(schema.venues)
await tx.insert(schema.venues).values(venues)
await tx.insert(schema.users).values(users)
await tx.insert(schema.events).values(events)
await tx.insert(schema.bookings).values([
{ eventId: 'evt-01', userId: 'usr-01', spots: 2 },
{ eventId: 'evt-05', userId: 'usr-01', spots: 1 },
])
})
console.log('Seed data loaded')
} finally {
await pool.end()
}
}
seed().catch((error: unknown) => {
console.error(error)
process.exitCode = 1
})The host check is essential: a script that deletes tables and reads the connection from the environment will one day end up running with the wrong environment. The order of deletion and insertion respects the foreign keys, and the transaction ensures it isn't left half done. The identifiers are kept (evt-01, usr-02…), so PLACEHOLDER_ORGANIZER_ID is still valid. Run npm run db:seed, and with npm run db:studio you'll be able to see the tables in the browser.
- The connection
Opening a connection to PostgreSQL takes several network round trips, and the server accepts a limited number (100 in a standard installation). That's why you use a pool: a set of open connections that are lent out and returned. There must be one per process.
In development there's a trap. Fast Refresh re-evaluates the modules that change and the ones that depend on them, so a new Pool() at the top level would run again and again, and the previous ones would keep their connections open until the server's supply runs out. The usual solution is to store it in globalThis, which isn't reset:
// lib/db/client.ts
import 'server-only'
import { io } from 'next/cache'
import { drizzle } from 'drizzle-orm/node-postgres'
import { Pool } from 'pg'
import { readEnv } from '@/lib/env'
function createDb(url: string) {
const pool = new Pool({ connectionString: url, max: 10 })
pool.on('error', (error) => console.error('Lost idle connection:', error))
return drizzle({ client: pool })
}
export type Database = ReturnType<typeof createDb>
const store = globalThis as typeof globalThis & { agendaVivaDb?: Database }
export async function getDb(): Promise<Database> {
await io()
const { databaseUrl, queryDelay } = readEnv()
if (queryDelay > 0) {
await new Promise<void>((resolve) => setTimeout(resolve, queryDelay))
}
store.agendaVivaDb ??= createDb(databaseUrl)
return store.agendaVivaDb
}- It's created when used, not when imported. Importing the module doesn't require
DATABASE_URL, which is what lets you build without it. max: 10is the maximum number of simultaneous queries per process; the rest wait their turn. The server's limit is shared among all instances of the application: ten instances with ten connections each already make a hundred.pool.on('error'). If PostgreSQL restarts, idle connections emit an error; without that handler, Node would treat it as uncaught and could end the process.- It isn't user state. It's one of the legitimate uses of a global variable we saw in 03-04: it doesn't depend on who's visiting.
- It isn't closed. It lives as long as the process. The seed script does close it, because it has to finish.
6.1. How Cache Components sees a query
To Next.js, an uncached asynchronous query is the same as a fetch: if it finds one inside a <Suspense> while prerendering, it leaves the hole; if not, it raises the uncached data error. The documentation states that with an asynchronous driver like pg, io() isn't needed, because the query itself already stops prerendering.
We keep it in getDb for three reasons:
- The query doesn't even start at build time. Without
io(), prerendering would reachreadEnv()and, on a CI machine withoutDATABASE_URL, the error would happen at build time. - Whatever happens inside stops mattering. If the driver, the logger or our code read the clock or generate a random value synchronously, it's already during the request.
- It's compatible with module 5. Inside a function with
'use cache',io()resolves instantly and the query will run wherever it needs to, including at build time. At that point you will need a database during the build.
- The queries
Now the modules in lib/data/ are rewritten. The signatures stay as they are. This is the complete events.ts:
// lib/data/events.ts
import 'server-only'
import { and, asc, eq, ilike, inArray } from 'drizzle-orm'
import { getDb } from '@/lib/db/client'
import { events, venues } from '@/lib/db/schema'
import type { AgendaEvent, EventFilters, EventPage } from '@/lib/types'
export const EVENTS_PER_PAGE = 6
const isPublished = eq(events.status, 'published')
const byDate = [asc(events.startsAt), asc(events.id)]
// In a LIKE pattern, these three characters have a meaning of their own
function escapePattern(text: string): string {
return text.replace(/[\\%_]/g, '\\$&')
}
export async function listUpcomingEvents(limit = 6): Promise<AgendaEvent[]> {
const db = await getDb()
return db.select().from(events).where(isPublished).orderBy(...byDate).limit(limit)
}
export async function listEvents(
filters: EventFilters = {},
): Promise<EventPage> {
const db = await getDb()
const text = filters.q?.trim()
const condition = and(
isPublished,
filters.category ? eq(events.category, filters.category) : undefined,
filters.district
? inArray(
events.venueId,
db.select({ id: venues.id }).from(venues).where(eq(venues.district, filters.district)),
)
: undefined,
text ? ilike(events.title, `%${escapePattern(text)}%`) : undefined,
)
const total = await db.$count(events, condition)
const totalPages = Math.max(1, Math.ceil(total / EVENTS_PER_PAGE))
const page = Math.min(Math.max(1, filters.page ?? 1), totalPages)
const matches = await db
.select()
.from(events)
.where(condition)
.orderBy(...byDate)
.limit(EVENTS_PER_PAGE)
.offset((page - 1) * EVENTS_PER_PAGE)
return { events: matches, total, page, totalPages }
}
export async function getEventBySlug(slug: string): Promise<AgendaEvent | null> {
const db = await getDb()
const [event] = await db
.select()
.from(events)
.where(and(eq(events.slug, slug), inArray(events.status, ['published', 'canceled'])))
.limit(1)
return event ?? null
}
export async function listEventsByVenue(venueId: string): Promise<AgendaEvent[]> {
const db = await getDb()
return db
.select()
.from(events)
.where(and(isPublished, eq(events.venueId, venueId)))
.orderBy(...byDate)
}andignoresundefinedvalues. That's why the optional filters are written as expressions rather than with a chain ofifstatements.- The condition is built once and used both to count and to read. If it were duplicated, sooner or later the two would diverge.
inArraywith a subquery producesvenue_id in (select id …). The district is in another table, and there's no need to fetch it.- The ordering is total. Two events with the same
startsAtcould come out in any order, and withOFFSETone might be repeated on two pages and another never show up. Theidbreaks the tie. - Values travel as parameters, never inside the SQL text. Even if
filters.qcontains quotes or'; drop table, it's data. The same goes for interpolations in thesqltemplate. The exception issql.raw, which inserts text as is: don't use it with anything that comes from outside. escapePatternisn't about security, it's about meaning: searching for "100%" shouldn't be equivalent to "anything starting with 100".- The return type acts as a check.
db.select().from(events)infers its result from the schema, and TypeScript requires it to matchAgendaEvent. If you change a column, the error shows up here.
If the query fails, the exception propagates. There's no try, for the reasons explained in 02-04: ErrorBoundary and error.tsx are the ones that respond.
7.1. Venues and dashboard
// lib/data/venues.ts
import 'server-only'
import { asc, eq } from 'drizzle-orm'
import { getDb } from '@/lib/db/client'
import { venues } from '@/lib/db/schema'
import type { Venue, VenueSummary } from '@/lib/types'
export async function listVenues(): Promise<Venue[]> {
const db = await getDb()
return db.select().from(venues).orderBy(asc(venues.name))
}
export async function listVenueSummaries(): Promise<VenueSummary[]> {
const db = await getDb()
return db
.select({
id: venues.id,
slug: venues.slug,
name: venues.name,
district: venues.district,
})
.from(venues)
.orderBy(asc(venues.name))
}
export async function getVenueBySlug(slug: string): Promise<Venue | null> {
const db = await getDb()
const [venue] = await db.select().from(venues).where(eq(venues.slug, slug)).limit(1)
return venue ?? null
}
export async function getVenueById(id: string): Promise<Venue | null> {
const db = await getDb()
const [venue] = await db.select().from(venues).where(eq(venues.id, id)).limit(1)
return venue ?? null
}
export async function listDistricts(): Promise<string[]> {
const db = await getDb()
const rows = await db
.selectDistinct({ district: venues.district })
.from(venues)
.orderBy(asc(venues.district))
return rows.map(({ district }) => district)
}The trimming in listVenueSummaries, which in 03-03 was done with a map, is now a four-column SELECT: what isn't requested isn't read, doesn't travel from the database and can't end up in the browser.
In the dashboard, occupancy is no longer a reduce. Adding things up is the database's job:
// lib/data/dashboard.ts
import 'server-only'
import { and, asc, eq, sql } from 'drizzle-orm'
import { getDb } from '@/lib/db/client'
import { events } from '@/lib/db/schema'
import type { AgendaEvent } from '@/lib/types'
// Will be replaced by the session user in module 8
export const PLACEHOLDER_ORGANIZER_ID = 'usr-02'
export interface Occupancy {
spots: number
booked: number
}
export async function listDashboardEvents(organizerId: string): Promise<AgendaEvent[]> {
const db = await getDb()
return db
.select()
.from(events)
.where(eq(events.organizerId, organizerId))
.orderBy(asc(events.startsAt), asc(events.id))
}
export async function getOccupancy(organizerId: string): Promise<Occupancy> {
const db = await getDb()
const [row] = await db
.select({
spots: sql<number>`coalesce(sum(${events.capacity}), 0)`.mapWith(Number),
booked: sql<number>`coalesce(sum(${events.capacity} - ${events.spotsLeft}), 0)`.mapWith(Number),
})
.from(events)
.where(and(eq(events.organizerId, organizerId), eq(events.status, 'published')))
return row ?? { spots: 0, booked: 0 }
}mapWith(Number) isn't decoration. In PostgreSQL, sum returns a big integer, and pg delivers those values as strings so as not to lose precision. The sql<number> is only an assertion for TypeScript; without the conversion it would compile, and at runtime booked would be '772'.
Delete lib/data/memory.ts, run npm run typecheck and go through the site. Pages, components and filters are the same as yesterday. Also try stopping PostgreSQL with docker compose stop: the notices and the retry button from 02-04 appear without touching anything, and when you start it again, "Try again" brings the page back.
7.2. The limits of OFFSET
OFFSET 6000 forces the database to read six thousand rows only to discard them, and if someone publishes an event while you're paging, the next page shifts and repeats one. The alternative is cursor pagination: asking for "the ones after this one", with where (starts_at, id) > (…), which with an index costs the same on the first page as on the last. In exchange, you can't jump to page 7 or easily show a total.
OFFSET |
Cursor | |
|---|---|---|
| Jump to a specific page | Yes | No |
| Cost on distant pages | Growing | Constant |
| Stable when data changes | No | Yes |
| A good fit for | Paginated listings, shareable URL | Infinite scrolling, exports |
A city's events guide has a few dozen pages at most, and its ?page= is part of the URL: OFFSET is the right choice.
Common Mistakes and Tips
- Creating the pool at the module's top level. In development it exhausts the connections, and it requires the configuration at build time.
- Importing
lib/db/client.tsfrom a script. It hasserver-only; scripts use the schema and create their own connection. - Querying with Drizzle inside a component. It works, and it scatters rules like "published only" across the UI.
- Forgetting the tiebreaker in
orderBywhen paginating. - Believing that
sql<number>converts. It only types; usemapWith. - Composing SQL by concatenating strings or with
sql.raw. - Using
pushon a shared database, or editing an applied migration. - Returning the full row for convenience when the table has private columns. That will happen with
usersin module 8.
Exercises
Exercise 1: a new column
You want to store when each event was created, in createdAt, without it appearing in the AgendaEvent type. Give the schema change, the commands, and what happens to existing rows and to db.select().from(events).
Solution
// lib/db/schema.ts, in events
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),Existing rows get the time of the migration, thanks to the default value; without it, adding a NOT NULL column to a table with data would fail. The queries still compile, because a row with an extra field fits AgendaEvent, but the field travels: if the event reached a Client Component, so would the field. It's the same lesson as in 03-03: types don't trim. If it's a problem, you select columns. The course doesn't keep the column.
Exercise 2: filtering by available spots only
Bring back the onlyAvailable filter from exercise 2 of 02-02 and add it to the query. Then explain why filtering in JavaScript after reading the page would be wrong.
Solution
// Inside and(…); import gt from 'drizzle-orm'
filters.onlyAvailable ? gt(events.spotsLeft, 0) : undefined,Filtering afterwards would produce pages with fewer than six items, perhaps empty ones, and a total that counts events nobody sees. Filters must be applied before counting and slicing, and only the database can do that.
Exercise 3: diagnosing a connection
A teammate writes this module. After half an hour of coding, PostgreSQL rejects connections with too many clients already; on top of that, continuous integration can't build. Explain both problems and fix it with the files from this lesson.
// lib/db.ts
import { drizzle } from 'drizzle-orm/node-postgres'
import { Pool } from 'pg'
if (!process.env.DATABASE_URL) throw new Error('Missing DATABASE_URL')
const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 50 })
export const db = drizzle({ client: pool })Solution
- Every time Fast Refresh re-evaluates the module, another pool of up to 50 connections is created, and the previous one isn't closed. With two of them in use, the server's 100 are exhausted.
- The check is at the top level, so it runs on import.
next buildimports the page modules, and the variable doesn't exist in CI. The check is a good idea; the timing isn't. - It doesn't have
server-onlyeither: nothing prevents importing it from the client.
The fix is to use getDb(): it stores the instance in globalThis, doesn't connect on import, validates the variable with readEnv and awaits io(), so at build time it never gets as far as querying.
Conclusion
The TypeScript schema provides types and migrations; lib/db/client.ts keeps a single pool per process, which isn't created on import or connected at build time; and the queries live in lib/data/ with the same signatures they had over the array. The change of source never reached the UI, which was the goal since 01-04. Filters, totals and sums are now done where they belong, in the database.
Keeping the signatures unchanged has a downside: the pages still request their data in the same order, one after another. With an array it didn't matter; with a network in between, every wait adds up. In Sequential and Parallel Loading and Preloading you'll learn to spot them and shorten them.
