Next.js 15 Fullstack (App Router + Server Actions) · Lezione

Popolamento del database e connection pooling

Popoli il database con dati seed affidabili e configuri il connection pooling di Prisma, così la Sua app Next.js rimane veloce e stabile sotto carico.

Lezione 4 di 413 passaggi

Popolamento del database e connection pooling è una lezione Next.js 15 Fullstack (App Router + Server Actions) gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Next.js 15 Fullstack (App Router + Server Actions), e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Next.js 15 Fullstack (App Router + Server Actions) include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Why Seed a Database?

Seeding fills your database with predictable starter data: admin users, demo records, lookup tables. It lets every developer and every CI run start from the same known state.

Without seeds, manual data entry makes tests flaky and onboarding slow.

The Prisma Seed Script

Prisma runs a seed file you point it at. Create prisma/seed.ts and register it in package.json under the prisma.seed key so prisma db seed knows what to execute.

{
  "prisma": {
    "seed": "ts-node prisma/seed.ts"
  }
}

Writing Seed Logic

Inside the seed file you instantiate the client and create records. Wrap it in an async function and disconnect when finished.

import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();

async function main() {
  await prisma.user.create({
    data: { email: 'admin@app.com', name: 'Admin' }
  });
}

main().finally(() => prisma.$disconnect());

Idempotent Seeds with upsert

Running a seed twice should not create duplicates. Use upsert so a record is created if missing and updated if it already exists.

await prisma.user.upsert({
  where: { email: 'admin@app.com' },
  update: {},
  create: { email: 'admin@app.com', name: 'Admin' }
});

Bulk Seeding

To insert many rows efficiently, use createMany. The skipDuplicates option avoids errors on unique conflicts.

await prisma.tag.createMany({
  data: [
    { name: 'news' },
    { name: 'sports' },
    { name: 'tech' }
  ],
  skipDuplicates: true
});

Running the Seed

Trigger the script from the CLI. Prisma also runs it automatically after prisma migrate reset, giving you a clean reseeded database.

npx prisma db seed

The Connection Problem in Serverless

Next.js on Vercel runs serverless functions. Each invocation can open a fresh DB connection, and under load you quickly exhaust the database connection limit.

Connection pooling solves this by reusing a fixed set of connections.

Reusing the Prisma Client

In development, hot reload can spawn many clients. Store a single instance on globalThis so only one client exists per process.

import { PrismaClient } from '@prisma/client';
const g = globalThis as unknown as { prisma?: PrismaClient };
export const prisma = g.prisma ?? new PrismaClient();
if (process.env.NODE_ENV !== 'production') g.prisma = prisma;

Pooling with a Connection URL

Use a pooler such as PgBouncer or Prisma Accelerate. Point your DATABASE_URL at the pooled endpoint and add ?pgbouncer=true so Prisma disables prepared statements that PgBouncer cannot share.

DATABASE_URL="postgresql://user:pass@host:6543/db?pgbouncer=true&connection_limit=1"

Direct URL for Migrations

Pooled connections cannot run migrations. Add a directUrl in your schema that bypasses the pooler so prisma migrate works.

datasource db {
  provider  = "postgresql"
  url       = env("DATABASE_URL")
  directUrl = env("DIRECT_URL")
}

Best Practices

Keep your data layer healthy:

  • Make seeds idempotent with upsert
  • Reuse a single client instance
  • Use a pooler in serverless environments
  • Keep a separate direct URL for migrations

Quick Check

Test what you learned about pooling.

Recap

You learned to seed and pool your database:

  • Configure prisma.seed and write idempotent seeds with upsert
  • Bulk insert with createMany
  • Reuse a single Prisma client to avoid leaks
  • Use a pooled DATABASE_URL plus a directUrl for migrations

Now your database starts in a known state and scales safely.

Gratis per iniziare

Impara TypeScript con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
22
Lezioni
88

Domande Frequenti

La lezione «Popolamento del database e connection pooling» è gratuita?

Sì — il testo completo di «Popolamento del database e connection pooling» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Next.js 15 Fullstack (App Router + Server Actions), passa a CoddyKit PRO. Il corso Next.js 15 Fullstack (App Router + Server Actions) include 4 lezioni in totale.

Cosa imparerò in «Popolamento del database e connection pooling»?

Popoli il database con dati seed affidabili e configuri il connection pooling di Prisma, così la Sua app Next.js rimane veloce e stabile sotto carico. Eserciti Next.js 15 Fullstack (App Router + Server Actions) con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Next.js 15 Fullstack (App Router + Server Actions)?

Non è richiesta alcuna esperienza precedente. Next.js 15 Fullstack (App Router + Server Actions) su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Popolamento del database e connection pooling»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Next.js 15 Fullstack (App Router + Server Actions)?

Sì. Ogni lezione Next.js 15 Fullstack (App Router + Server Actions) include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Configurare Prisma ORM
  2. CRUD con le Server Actions
  3. Migrazioni dello schema del database
  4. Popolamento del database e connection pooling
← Torna a Next.js 15 Fullstack (App Router + Server Actions)