Documentation

Guide / Next.js and PostgreSQL

Next.js with PostgreSQL: connect, query and deploy

Updated

Next.js and PostgreSQL work well together once three things are in place: one connection pool that server code reuses, queries that run only on the server, and a schema you change through migrations. This guide builds a small notes app with the App Router and node-postgres (pg). You run it against a local database, then deploy it on Resilis with a managed PostgreSQL database. The code was run against Next.js 16 and PostgreSQL 17. You will:

A Next.js page queries PostgreSQL, above the app and its private database running on Resilis.

Overview

  • 1. Install node-postgres and set DATABASE_URL.
  • 2. Create one connection pool for server code.
  • 3. Add a SQL migration and run it.
  • 4. Query in a Server Component and write with a Server Action.
  • 5. Build a production image and deploy it with a managed PostgreSQL database.

Before you start

  • A Next.js app that uses the App Router. To start a new one, run npx create-next-app@latest notes.
  • A current Node.js LTS release. The migration step uses node --env-file, which needs Node.js 20.6 or later.
  • Docker, for a local PostgreSQL database and for the production image. Any PostgreSQL database you can reach also works.
  • For the deploy step: a Resilis account, and either a GitHub repository or a connected coding agent.

Install node-postgres and set DATABASE_URL

Add the PostgreSQL client and its types:

Shell

npm install pg
npm install --save-dev @types/pg

Start a local database:

Shell

docker run --name notes-db -e POSTGRES_PASSWORD=postgres \
  -p 5432:5432 -d postgres:17

Put the connection string in .env.local. Next.js loads this file in development, and the .gitignore from create-next-app already excludes .env files.

.env.local

DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres

Never give this variable a NEXT_PUBLIC_ prefix. Next.js inlines prefixed variables into the browser bundle at build time. DATABASE_URL must stay on the server.

Create one connection pool

TypeScript

// lib/db.ts
import { Pool } from 'pg';

const globalForPg = globalThis as unknown as { pgPool?: Pool };

export const pool =
  globalForPg.pgPool ?? new Pool({ connectionString: process.env.DATABASE_URL, max: 10 });

if (process.env.NODE_ENV !== 'production') globalForPg.pgPool = pool;

A pool keeps a few connections open and reuses them, so a request does not pay for a new connection each time. max caps the connections each app instance opens.

The globalThis lines only matter in development. Hot reload evaluates the module again, and without them each reload would open another pool. In production the module loads once.

Add a migration

Keep schema changes in numbered SQL files, so every environment applies the same changes in the same order.

SQL

-- migrations/001_create_notes.sql
CREATE TABLE notes (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  body       text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);

A short script applies each file that has not run yet and records it in a schema_migrations table. Each file runs in its own transaction.

JavaScript

// scripts/migrate.mjs
import { readdir, readFile } from 'node:fs/promises';
import pg from 'pg';

const dir = new URL('../migrations/', import.meta.url);
const client = new pg.Client({ connectionString: process.env.DATABASE_URL });
await client.connect();

try {
  await client.query('CREATE TABLE IF NOT EXISTS schema_migrations (name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())');
  const applied = new Set((await client.query('SELECT name FROM schema_migrations')).rows.map((row) => row.name));
  const files = (await readdir(dir)).filter((file) => file.endsWith('.sql')).sort();

  for (const file of files) {
    if (applied.has(file)) continue;
    const sql = await readFile(new URL(file, dir), 'utf8');
    await client.query('BEGIN');
    try {
      await client.query(sql);
      await client.query('INSERT INTO schema_migrations (name) VALUES ($1)', [file]);
      await client.query('COMMIT');
      console.log(`applied ${file}`);
    } catch (error) {
      await client.query('ROLLBACK');
      throw error;
    }
  }
} finally {
  await client.end();
}

Run it against the local database:

Shell

node --env-file=.env.local scripts/migrate.mjs

It prints applied 001_create_notes.sql. A second run prints nothing, because the file is already recorded.

If you already use Prisma, Drizzle or another migration tool, keep it. The rest of this guide only needs one command that applies pending migrations.

Query PostgreSQL in a Server Component

Server Components run only on the server, so they can query the database directly. The connection string and the SQL never reach the browser.

TypeScript

// app/page.tsx
import { Suspense } from 'react';
import { connection } from 'next/server';
import { pool } from '@/lib/db';
import { addNote } from './actions';

type Note = { id: string; body: string; created_at: Date };

async function Notes() {
  await connection();
  const { rows } = await pool.query<Note>(
    'SELECT id, body, created_at FROM notes ORDER BY created_at DESC LIMIT 20',
  );

  return (
    <ul>
      {rows.map((note) => (
        <li key={note.id}>{note.body}</li>
      ))}
    </ul>
  );
}

export default function Page() {
  return (
    <main>
      <h1>Notes</h1>
      <form action={addNote}>
        <input name="body" placeholder="Write a note" required />
        <button type="submit">Add</button>
      </form>
      <Suspense fallback={<p>Loading notes…</p>}>
        <Notes />
      </Suspense>
    </main>
  );
}

Two details matter here. First, await connection() tells Next.js to run the query for each request. Without it, Next.js can try to render the page once during next build, when no database is reachable.

Second, the Suspense boundary lets the page shell render at once while the notes stream in. Recent create-next-app releases enable Cache Components by default, and its build fails if request-time data is read outside a Suspense boundary.

Write with a Server Action

TypeScript

// app/actions.ts
'use server';

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

export async function addNote(formData: FormData) {
  const body = String(formData.get('body') ?? '').trim();
  if (!body) return;

  await pool.query('INSERT INTO notes (body) VALUES ($1)', [body]);
  revalidatePath('/');
}

The form in page.tsx calls addNote on the server. Pass values as query parameters ($1). Never build SQL strings from user input. revalidatePath refreshes the page data, so the new note appears without a reload.

A Server Action can be called by a direct request, not only from your form. Once your app has sign-in, check inside the action that the caller is allowed to make the change.

Start the app, open http://localhost:3000 and add a note:

Shell

npm run dev

Add a health check

TypeScript

// app/api/health/route.ts
import { connection } from 'next/server';
import { pool } from '@/lib/db';

export async function GET() {
  await connection();
  try {
    await pool.query('SELECT 1');
    return Response.json({ status: 'ok' });
  } catch {
    return Response.json({ status: 'database unavailable' }, { status: 503 });
  }
}

GET /api/health returns 200 while the database answers and 503 when it does not. You will use the same route to check the deployed app.

Build a production image

Next.js can build a standalone server that carries only the files it needs. Add output to next.config.ts and keep the options your project already has:

TypeScript

// next.config.ts
import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  output: 'standalone',
  // ...your existing options
};

export default nextConfig;

Dockerfile

FROM node:22-slim AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:22-slim
WORKDIR /app
ENV NODE_ENV=production HOSTNAME=0.0.0.0 PORT=3000
COPY --from=build /app/.next/standalone ./
COPY --from=build /app/.next/static ./.next/static
COPY --from=build /app/public ./public
COPY --from=build /app/migrations ./migrations
COPY --from=build /app/scripts ./scripts
EXPOSE 3000
CMD ["node", "server.js"]

The standalone server does not include public or .next/static, so the image copies them. The last two COPY lines add the SQL files and the migration script, so migrations run from the same image as the app. The standalone output already contains pg, because the app imports it.

Add a .dockerignore so local secrets and build output stay out of the build context:

.dockerignore

.env*
node_modules
.next
.git

The build needs no database, because the page queries at request time:

Shell

docker build -t notes .

Deploy on Resilis with a managed PostgreSQL database

Resilis builds with Railpack automatically, or from your Dockerfile. This guide uses the Dockerfile route, which keeps the standalone build explicit. Create the app and the database in the same project, environment and region, so the app can use the internal database connection.

From the dashboard, with the app in a GitHub repository:

  • 1. In your project, select Create Database. Choose PostgreSQL 17 and keep public network access off.
  • 2. When the database shows Running, open Connections, choose Internal and copy the connection URI. Keep the value private.
  • 3. Create an app from your GitHub repository. Select the branch, set the app root to . and choose Dockerfile.
  • 4. Add DATABASE_URL with the Secret option on, and paste the internal URI. Add PORT=3000.
  • 5. Deploy and wait for Running.

The Node.js and PostgreSQL guide records these screens step by step.

Or deploy from a coding agent

With Claude Code or Codex connected to the Resilis MCP server, you can ask for the same setup. This route deploys your local workspace through Git and a private repository hosted by Resilis. You do not need a GitHub repository.

Example

Inspect this Next.js workspace and prepare a Resilis deployment plan.
Ask me which project and environment to use. Propose a private
PostgreSQL 17 database bound to the app as DATABASE_URL, and a
Dockerfile build on port 3000. Do not create anything until I approve.

After you approve, the agent calls databases.create and then databases.bind. The bind injects the connection string into the app's environment as a sensitive variable, and the credential never passes through the model's context. workspaces.deploy then pushes the reviewed commit, and Resilis builds it.

Run migrations on the deployed app

Run migrations as their own step, not inside the start command, so a failed migration does not crash-loop the app. From a connected agent, a release command runs with the exact image and bound DATABASE_URL of the current deployment, with its own timeout and logs:

Example

Run "node scripts/migrate.mjs" as a release command on the current
deployment. Show me the exit code and the logs.

The agent calls deployments.release.run with ["node", "scripts/migrate.mjs"]. Run it right after the first deploy: until then, the notes query fails because the table does not exist yet.

If you deployed from the dashboard, connect an agent for this step with the Claude Code or Codex setup guide.

Check the live app

Shell

curl -i https://<your-app-url>/api/health

Then open the app, add a note and reload the page. A Running status and a green build are checkpoints. A real write and read against the database is the proof.

If the app cannot connect, check that DATABASE_URL is a secret that holds the Internal connection URI, and that the app and the database share a project, environment and region. Build failures show in the build logs. Startup and connection errors show in the runtime logs.

Roll back code, restore data

Each deploy keeps the previous release, so you can roll the app back from the dashboard or with an agent. Rollback changes the application release. It does not undo migrations or restore data. Write migrations the previous release can still run against, such as adding a column before you start reading it.

Database recovery is separate. Every plan includes snapshots. With continuous backups on, the database can be restored to a chosen minute: up to 7 days back on Hobby and up to 365 days on Pro and Enterprise.

When you need staging and production

This guide deploys one environment. Every Resilis project comes with development, staging and production. When each one needs its own database, secrets and branch, continue with the environments guide.

Frequently asked questions

How do I connect Next.js to PostgreSQL? Install pg, keep the connection string in a server-only DATABASE_URL variable, and create one Pool in lib/db.ts. Import that pool from Server Components, Server Actions and Route Handlers.

Can I query PostgreSQL from a Client Component? No. Database code must run on the server. Query in a Server Component, a Server Action or a Route Handler, and pass the result to Client Components as props.

Do I need an ORM such as Prisma or Drizzle? No. node-postgres and SQL are enough for this guide. An ORM adds typed queries and its own migration tool. The connection string, the server-only rule and the deployment steps stay the same.

Why does next build fail when a page reads the database? Next.js tries to render pages at build time unless they read request-time data. Call await connection() before the query, inside a Suspense boundary, so the query runs for each request.

Can I set up a Next.js app with Postgres, auth and deployment in one command? Not in one command. create-next-app scaffolds the app. A connected coding agent can then plan the database, the DATABASE_URL binding and the deployment in one request that you review. Authentication is code you add to the app with the library you choose.

Is there Next.js hosting with a built-in Postgres database? On Resilis, a Next.js app and a managed PostgreSQL database run in the same project, and the database is connected to the app through a DATABASE_URL secret. This guide runs Next.js as a Node.js server in a container. Test any feature that depends on a specific hosting platform in development before relying on it.

What does it cost? The app and the database are billed by usage against your plan credit. The billing docs show a worked example for one app and one database.