Node.js, Prisma & PostgreSQL

Lesson 10 of 12

Building a REST API with Express and Prisma

Wiring Prisma into an Express route handler looks almost exactly like the CRUD calls from earlier, just inside a request handler.

import express from 'express';
import { PrismaClient } from '@prisma/client';

const app = express();
const prisma = new PrismaClient();
app.use(express.json());

app.get('/api/posts', async (req, res) => {
  const posts = await prisma.post.findMany({
    where: { published: true },
    include: { author: { select: { name: true } } },
    orderBy: { createdAt: 'desc' },
  });
  res.json(posts);
});

app.post('/api/posts', async (req, res) => {
  try {
    const post = await prisma.post.create({ data: req.body });
    res.status(201).json(post);
  } catch (err) {
    res.status(400).json({ error: 'Could not create post' });
  }
});

app.listen(4000);

One PrismaClient instance is created once and reused across every request, creating a new one per request would open far too many database connections.

📝 Express + Prisma Quiz

Passing score: 70%
  1. 1.How many PrismaClient instances should a typical Express app create?

  2. 2.Wrapping a Prisma call in try/catch inside a route handler lets you return a proper error ____ code instead of crashing.

  3. 3.Prisma Client calls inside an Express route handler must be awaited, just like anywhere else.