# Next.js

Connect a Next.js App Router app to KeelDB with node-postgres, query from Server Components, write from Server Actions, and deploy to serverless hosts on the pooled host.

This guide connects a Next.js app that uses the App Router to a KeelDB database with node-postgres (`pg`). To use an ORM instead, read [Prisma](/docs/prisma) or [Drizzle](/docs/drizzle): the connection setup here applies to both.

KeelDB speaks the PostgreSQL protocol over TCP with TLS. Query it from code that runs in the Node.js runtime, which is the default for Server Components, Server Actions and Route Handlers. The Edge runtime cannot open TCP connections, so never import your database module from code that runs there.

## Connection strings

Copy both connection strings from the database's **Overview** page and put them in `.env.local` (Next.js loads it in development; keep it out of git):

```bash
# App traffic: the pooled host
DATABASE_URL="postgresql://shop_owner:<password>@k7m2x9qa4pz1-pooler.us-east.db.keeldb.com:5432/shop?sslmode=require&connect_timeout=10"
# Migrations, pg_dump and LISTEN: the direct host
DIRECT_URL="postgresql://shop_owner:<password>@k7m2x9qa4pz1.us-east.db.keeldb.com:5432/shop?sslmode=require&connect_timeout=10"
```

The `-pooler` host runs PgBouncer in transaction mode, which suits a Next.js app: many short requests, often from many server instances. Read [Transaction mode caveats](/docs/connect#transaction-mode-caveats) once; the code below follows them.

## Install

```bash
npm install pg server-only
npm install --save-dev @types/pg
```

## Create one pool

```ts
// lib/db.ts
import "server-only";
import { Pool } from "pg";

const globalForDb = globalThis as unknown as { keeldbPool?: Pool };

export const pool =
  globalForDb.keeldbPool ??
  new Pool({
    connectionString: process.env.DATABASE_URL,
    max: 5,
    idleTimeoutMillis: 30_000,
  });

// The dev server re-evaluates modules on every edit. Keeping the pool on globalThis
// stops each reload from opening a new one.
if (process.env.NODE_ENV !== "production") globalForDb.keeldbPool = pool;
```

- `import "server-only"` makes the build fail if a Client Component imports this file, so credentials never reach the browser.
- Keep `max` small. Each server instance has its own pool, and the pooler accepts many more client connections than PostgreSQL itself (see [Connection limits](/docs/connect#connection-limits)), so several small pools are the right shape.

## Create a table

Run schema changes over the direct host, here with `psql`:

```bash
psql "$DIRECT_URL" -c "CREATE TABLE notes (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, title text NOT NULL, created_at timestamptz NOT NULL DEFAULT now())"
```

In a real app, a migration tool does this. See [Prisma](/docs/prisma) or [Drizzle](/docs/drizzle).

## Read in a Server Component

```tsx
// app/page.tsx
import { connection } from "next/server";
import { pool } from "@/lib/db";
import { addNote } from "./actions";

export default async function Page() {
  await connection(); // render at request time, not once at build time
  const { rows } = await pool.query<{ id: string; title: string }>(
    "SELECT id, title FROM notes ORDER BY id DESC LIMIT 20",
  );
  return (
    <main>
      <form action={addNote}>
        <input name="title" required />
        <button type="submit">Add</button>
      </form>
      <ul>
        {rows.map((n) => (
          <li key={n.id}>{n.title}</li>
        ))}
      </ul>
    </main>
  );
}
```

A page whose only input is a database query has nothing request-specific in it, so `next build` would otherwise render it once, with the data of build time, and would need the database during the build. `await connection()` moves the render to request time. Pages that already read `cookies()`, `headers()` or `searchParams` render at request time anyway. With `cacheComponents` turned on, put the component that queries inside `<Suspense>`, or cache its result with `"use cache"`.

node-postgres returns `bigint` columns as strings, which is why `id` is typed as a string above.

## Write in a Server Action

```ts
// app/actions.ts
"use server";

import { revalidatePath } from "next/cache";
import { pool } from "@/lib/db";

export async function addNote(formData: FormData) {
  const title = String(formData.get("title") ?? "").trim();
  if (!title) return;
  await pool.query("INSERT INTO notes (title) VALUES ($1)", [title]);
  revalidatePath("/");
}
```

- Always pass values as parameters (`$1`), never by building SQL strings.
- A Server Action is a public HTTP endpoint. Check who is calling it inside the action before you write.
- Run several statements that belong together in one transaction on one client:

  ```ts
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    // ... statements ...
    await client.query("COMMIT");
  } catch (e) {
    await client.query("ROLLBACK");
    throw e;
  } finally {
    client.release();
  }
  ```

## Route Handlers

```ts
// app/api/notes/route.ts
import { pool } from "@/lib/db";

export async function GET() {
  const { rows } = await pool.query("SELECT id, title FROM notes ORDER BY id DESC LIMIT 20");
  return Response.json(rows);
}
```

## Deploy

- **Environment variables:** set `DATABASE_URL` (pooled) and `DIRECT_URL` (direct) in your host's settings for each environment.
- **Region:** KeelDB's region is US East (`us-east`), centered on Ashburn, Virginia. Run your server functions in a nearby region, such as AWS `us-east-1` (Northern Virginia), so each query doesn't cross a continent.
- **Serverless functions** keep their pool between invocations while the instance is warm. Keep `max` between 1 and 5 per instance and let the pooler absorb the number of instances.
- **IP allowlist:** most serverless platforms don't have fixed outbound addresses. Leave the database's [IP allowlist](/docs/security#ip-allowlist) empty in that case; TLS and the password still protect it.
- **Sleeping databases:** a Free database, or a Launch database with scale to zero, can sleep. The first connection after a full sleep waits while it wakes, so raise `connect_timeout` to `30` for such a database. See [Waking a sleeping database](/docs/connect#waking-a-sleeping-database).

## Preview deployments

Give each pull request its own copy of the data with a [branch](/docs/branching): branches on Free and Launch are copy-on-write, ready in seconds, with their own hostnames and password. [Preview environments per pull request](/docs/branching#preview-environments-per-pull-request) has a GitHub Actions workflow that creates one per pull request, runs migrations on it and deletes it when the pull request closes. Pass the branch's pooled connection string to the preview deployment as `DATABASE_URL`.
