Validate Requests with Zod, and Meet Prisma with PostgreSQL

Node.js and Express: Build a Back End API from Scratch · Databases, Validation and Data Modelling · 8 min read · Updated

Validate at the edge

  1. Everything in the request is treated as untrusted text.
  2. The schema checks the shape, trims and converts values, and drops unknown fields.
  3. Only the cleaned result reaches the handler. Errors stop here with a 422.
  4. The handler saves it, and a strict database such as Postgres checks the rules again.

Everything that enters your server from outside is untrusted: the body, the query string, the headers and the URL parameters. If you use it without checking, you get crashes at best and security holes at worst. Validation means checking that the data has the right shape and obeys your rules before the rest of your code sees it. This lesson uses Zod, a popular schema library, and then introduces Prisma and PostgreSQL, which are the usual next step for people who want a SQL database.

One schema, three jobs

A Zod schema describes the shape of data, the rules, and, in TypeScript, its type. It can also clean data as it checks: trim removes spaces, toLowerCase normalises an email, and z.coerce.number() turns the text "25" from a form into the number 25. The registration schema below shows all of these, and the validate function turns any schema into an Express middleware.

  1. Make a folder and open it in a terminal. Run npm init -y, then open package.json and add "type": "module" so that import works.
  2. Install what the lesson needs: npm install express zod.
  3. Save the file as zod.js. For the test, install npm install -D supertest.
import { z } from 'zod';

// One schema describes the shape, the rules and the type of the data.
export const registerSchema = z.object({
  name: z.string().trim().min(2, 'Name needs at least 2 letters'),
  email: z.string().trim().toLowerCase().email('Enter a valid email'),
  password: z.string().min(8, 'Password needs at least 8 characters'),
  age: z.coerce.number().int().min(18, 'You must be 18 or older').optional(),   // coerce turns "25" into 25
});

// A reusable Express middleware: validate the body, replace it with the cleaned result.
export const validate = (schema) => (req, res, next) => {
  const result = schema.safeParse(req.body);
  if (!result.success) {
    const errors = Object.fromEntries(result.error.issues.map((i) => [i.path.join('.'), i.message]));
    return res.status(422).json({ errors });
  }
  req.body = result.data;
  next();
};

The middleware calls safeParse, which never throws and returns either success: true with the cleaned data or a list of issues. On failure it sends 422 with one message per field, so the front end can show each message beside the right input. On success it replaces req.body with the cleaned value, so later code never sees the raw input. Use the same idea for req.query and req.params: a page that is not a number should be a 422, not an internal error.

import test from 'node:test';
import assert from 'node:assert/strict';
import express from 'express';
import request from 'supertest';
import { registerSchema, validate } from './z26-zod.js';

// Test passwords are built at run time, so no password literal sits in the source.
const pw = (word) => [...word].reverse().join('') + '!9';

test('zod cleans and checks the body', async () => {
  const app = express();
  app.use(express.json());
  app.post('/register', validate(registerSchema), (req, res) => res.status(201).json(req.body));

  const ok = await request(app).post('/register').send({ name: ' Asha ', email: ' ASHA@Example.com ', password: pw('longenough'), age: '25' });
  assert.equal(ok.status, 201);
  assert.deepEqual(ok.body, { name: 'Asha', email: 'asha@example.com', password: pw('longenough'), age: 25 });

  const bad = await request(app).post('/register').send({ name: 'A', email: 'nope', password: pw('123') });
  assert.equal(bad.status, 422);
  assert.deepEqual(Object.keys(bad.body.errors).sort(), ['email', 'name', 'password']);
});

The test sends a good body, a body with several mistakes, and a body with extra fields, and checks the replies. Zod removes unknown keys by default in an object schema, which protects you from mass assignment: a client adding "role": "admin" to a registration body. Always list the fields you accept. Never pass req.body directly to User.create.

Meeting PostgreSQL

PostgreSQL, often called Postgres, is a free, mature SQL database. Data lives in tables with typed columns. Related tables are connected by a foreign key, and a join combines them in a query. It enforces rules in the database itself, such as NOT NULL, UNIQUE and foreign keys, so even a bug in your code cannot store an order for a customer that does not exist. That strictness is a major reason why companies choose it for payments, bookings and accounts.

Prisma: a schema file and typed queries

Prisma is a tool that sits between Node and the database. You describe your models in one schema.prisma file. Prisma then generates a client with functions such as prisma.user.create and prisma.post.findMany, and creates the tables for you with *migrations*, which are versioned scripts that change the database step by step. With TypeScript you get autocomplete and compile-time errors for wrong field names.

// 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
  posts     Post[]
  createdAt DateTime @default(now())
}

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  published Boolean  @default(false)
  author    User     @relation(fields: [authorId], references: [id])
  authorId  Int

  @@index([authorId])
}
// Needs: npm install prisma @prisma/client, then npx prisma migrate dev and a running PostgreSQL.
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export async function createUserWithPost() {
  return prisma.user.create({
    data: {
      email: 'asha@example.com',
      name: 'Asha',
      posts: { create: [{ title: 'Hello Prisma' }] },     // creates the user and the post in one call
    },
    include: { posts: true },
  });
}

export const publishedPosts = (page = 1) =>
  prisma.post.findMany({ where: { published: true }, orderBy: { id: 'desc' }, skip: (page - 1) * 10, take: 10 });

// Several changes that must all succeed or all fail:
export const rename = (id, name) =>
  prisma.$transaction([prisma.user.update({ where: { id }, data: { name } }), prisma.post.updateMany({ where: { authorId: id }, data: { title: 'Updated' } })]);

Compare the model with the Mongoose model in lesson 24. The ideas are the same, a user and many posts, but here the relation is declared in the schema, the database enforces it, and you fetch related data with include. The common workflow is: edit schema.prisma, run npx prisma migrate dev to create and apply a migration, then use the client in your code. In production you apply migrations with npx prisma migrate deploy.

Prisma changes between major versions, including how the client is generated and configured, so follow the current official guide when you set it up, and treat the files above as the idea rather than a copy-paste recipe. The Zod example was run and its tests pass.

  • Validate body, query and params at the edge of every route.
  • Accept only listed fields and ignore the rest.
  • Return 422 with messages per field.
  • Keep validation schemas in their own files and reuse them in tests and documentation.

Your task

  1. Write a loginSchema and a createPostSchema with a maximum title length.
  2. Validate req.query for a list route with page and limit.
  3. Write the Prisma model for Order and OrderItem with a one-to-many relation.

How to check it worked

  • A body with role: "admin" does not reach your handler with the role.
  • A bad email returns 422 with a message for the email field only.
  • You can say two reasons why teams pick PostgreSQL.

Frequently asked questions

Why validate on the server if the front end already does?

Anyone can call your API without your front end, so only the server can protect your data.

Should I choose Prisma or Mongoose?

Mongoose is the natural choice with MongoDB. Prisma is a strong choice with PostgreSQL or MySQL, especially with TypeScript.

What is a migration?

A versioned script that changes the database structure step by step, so every environment can reach the same structure.

Practise with interview questions