Skip to content

Adding a Database

Adding a local database

Create a docker-compose.yml file in the root folder, with the following content:

yaml
version: "3.7"
services:
  postgres:
    image: postgres:latest
    container_name: name-of-your-activation
    restart: always
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_DB=activation
    ports:
      - "5432:5432"
    volumes:
      - ./postgres-data:/var/lib/postgresql/data

Add the following command to your package.json file:

json
"db:start": "docker-compose up -d",

The -d flag will run the container in the background (detached).

And now add the database URL to your .env file

bash
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/activation?schema=public"

Initialize Prisma

bash
npx prisma init

Create your models in the schema.prisma file

prisma
model User {
  id        String      @id @default(uuid())
  email     String   @unique
  name      String?
}

And run your changes into the db

bash
npx prisma db push

And add packages

bash
npm i @prisma/client

Instantiating the Prisma Client

Create a new file db.ts normally in your utils folder.

typescript
import { PrismaClient } from "@prisma/client";

const globalForPrisma = global as unknown as {
  prisma: PrismaClient | undefined;
};

export const prisma =
  globalForPrisma.prisma ??
  new PrismaClient({
    log: ["error"],
  });

if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;

This setup ensures that a single instance of PrismaClient is reused in development, preventing excessive connections during hot reloading. In production, it avoids storing the client in the global scope to prevent potential memory leaks.