DEV Community

Alex Spinov
Alex Spinov

Posted on

Prisma Has a Free ORM — Here's How to Build Type-Safe Database Apps in Minutes

Why Prisma?

Prisma is the next-generation ORM for Node.js and TypeScript. It replaces traditional ORMs with a type-safe query builder, auto-generated migrations, and a visual database browser.

Frisma is free and open source. Prisma Accelerate (connection pooling + caching) has a free tier: 6K queries/month.

Getting Started

1. Install & Initialize

npm init -y
npm install prisma @prisma/client
npx prisma init --datasource-provider postgresql
Enter fullscreen mode Exit fullscreen mode

2. Define Schema

// prisma/schema.prisma
generator client {
  provider = "prisma-client-js"
}

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

model User {
  id        Int      @id @default(autoincrement())
  email     String   @unique
  name      String
  plan      String   @default("free")
  posts     Post[]
  createdAt DateTime @default(now())
}

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String?
  published Boolean  @default(false)
  author    User     @relation(fields: [authorId], references: [id])
  authorId  Int
  tags      String[]
  views     Int      @default(0)
  createdAt DateTime @default(now())
}
Enter fullscreen mode Exit fullscreen mode

3. Migrate & Generate

npx prisma migrate dev --name init
# Creates tables + generates type-safe client
Enter fullscreen mode Exit fullscreen mode

TypeScript Queries (Fully Type-Safe!)

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

const prisma = new PrismaClient();

// Create with relation
const user = await prisma.user.create({
  data: {
    email: "alice@example.com",
    name: "Alice",
    plan: "pro",
    posts: {
      create: [
        { title: "Getting Started with Prisma", content: "Prisma makes databases easy...", published: true, tags: ["prisma", "tutorial"] },
        { title: "Advanced Queries", content: "Let's explore relations...", tags: ["prisma", "advanced"] }
      ]
    }
  },
  include: { posts: true }
});

console.log(`Created ${user.name} with ${user.posts.length} posts`);

// Query with filters, sorting, pagination
const posts = await prisma.post.findMany({
  where: {
    published: true,
    author: { plan: "pro" }
  },
  include: { author: { select: { name: true, email: true } } },
  orderBy: { views: "desc" },
  take: 10
});

posts.forEach(p => console.log(`${p.title} by ${p.author.name} (${p.views} views)`));

// Aggregate
const stats = await prisma.post.aggregate({
  _count: true,
  _sum: { views: true },
  _avg: { views: true },
  where: { published: true }
});

console.log(`${stats._count} posts, ${stats._sum.views} total views, ${stats._avg.views?.toFixed(0)} avg`);

// Group by
const byAuthor = await prisma.post.groupBy({
  by: ["authorId"],
  _count: true,
  _sum: { views: true },
  orderBy: { _sum: { views: "desc" } }
});
Enter fullscreen mode Exit fullscreen mode

Prisma Studio (Visual Browser)

npx prisma studio
# Opens http://localhost:5555 — browse/edit data visually!
Enter fullscreen mode Exit fullscreen mode

Prisma with Next.js API Route

// app/api/posts/route.ts
import { prisma } from "@/lib/prisma";
import { NextResponse } from "next/server";

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const tag = searchParams.get("tag");

  const posts = await prisma.post.findMany({
    where: {
      published: true,
      ...(tag ? { tags: { has: tag } } : {})
    },
    include: { author: { select: { name: true } } },
    orderBy: { createdAt: "desc" },
    take: 20
  });

  return NextResponse.json(posts);
}
Enter fullscreen mode Exit fullscreen mode

Supported Databases

Database Status
PostgreSQL Full support
MySQL Full support
SQLite Full support
SQL Server Full support
CockroachDB Full support
MongoDB Preview

Need data for your Prisma-powered app? I build production-ready scrapers. Check out my Apify actors or email spinov001@gmail.com for custom data pipelines.

What's your Prisma setup? Share below!

Top comments (0)