0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · Lección

Población de bases de datos y connection pooling

Rellene su base de datos con datos seed fiables y configure el connection pooling de Prisma para que su app de Next.js siga siendo rápida y estable bajo carga.

Población de bases de datos y connection pooling es una lección gratuita de Next.js 15 Fullstack (App Router + Server Actions) en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Next.js 15 Fullstack (App Router + Server Actions), y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Next.js 15 Fullstack (App Router + Server Actions) incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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.

Preguntas frecuentes

¿La lección «Población de bases de datos y connection pooling» es gratis?

Sí — el texto completo de «Población de bases de datos y connection pooling» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Next.js 15 Fullstack (App Router + Server Actions), actualiza a CoddyKit PRO. El curso de Next.js 15 Fullstack (App Router + Server Actions) incluye 4 lecciones en total.

¿Qué aprenderé en «Población de bases de datos y connection pooling»?

Rellene su base de datos con datos seed fiables y configure el connection pooling de Prisma para que su app de Next.js siga siendo rápida y estable bajo carga. Practicas Next.js 15 Fullstack (App Router + Server Actions) con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Next.js 15 Fullstack (App Router + Server Actions)?

No se requiere experiencia previa. Next.js 15 Fullstack (App Router + Server Actions) en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Población de bases de datos y connection pooling»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Next.js 15 Fullstack (App Router + Server Actions)?

Sí. Cada lección de Next.js 15 Fullstack (App Router + Server Actions) incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Configuración de Prisma ORM
  2. CRUD con Server Actions
  3. Migraciones del esquema de la base de datos
  4. Población de bases de datos y connection pooling
← Volver a Next.js 15 Fullstack (App Router + Server Actions)