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.
- Make a folder and open it in a terminal. Run
npm init -y, then openpackage.jsonand add"type": "module"so thatimportworks. - Install what the lesson needs:
npm install express zod. - Save the file as
zod.js. For the test, installnpm 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,queryandparamsat 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
- Write a
loginSchemaand acreatePostSchemawith a maximum title length. - Validate
req.queryfor a list route withpageandlimit. - Write the Prisma model for
OrderandOrderItemwith 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.