ProvenPin Install

Joi request validation middleware for Express 5: working versions (tested 2026-10-15)

Validate Express 5 bodies and query strings with Joi schemas in a reusable middleware, with defaults, type conversion, stripUnknown and 400 error details, tested with supertest.

passed4 passed · 0 failed2026-10-15 17:10 UTC
Status
passed
Last passed
2026-10-15 17:10 UTC
Tests
4 / 4
Language
TypeScript
Runtime
node v22.23.3
pinned versions7
joi@18.2.9express@5.3.0@types/node@26.6.5tsx@4.23.15supertest@7.3.1@types/express@5.0.6@types/supertest@7.2.1
run it
npm install --no-audit --no-fund --ignore-scripts=false
npm test
test environment
node v22.23.3
linux 6.17.0-1022-azure
x64
runner: github-actions 38775053802

The code

Exactly the files that passed. Your agent can pull them with get_recipe("joi-express-validation") (install), or see them on GitHub.

package.json
{
  "name": "joi-express-validation",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "node --import tsx --test test/*.test.ts"
  },
  "dependencies": {
    "joi": "18.2.9",
    "express": "5.3.0"
  },
  "devDependencies": {
    "@types/node": "26.6.5",
    "tsx": "4.23.15",
    "supertest": "7.3.1",
    "@types/express": "5.0.6",
    "@types/supertest": "7.2.1"
  }
}
src/app.ts
import express, { type Request, type Response, type NextFunction } from "express";
import Joi from "joi";

export const createUserSchema = Joi.object({
  email: Joi.string().email({ tlds: { allow: false } }).lowercase().required(),
  name: Joi.string().trim().min(2).max(50).required(),
  age: Joi.number().integer().min(13).default(18),
  role: Joi.string().valid("admin", "member").default("member"),
});

export const listQuerySchema = Joi.object({
  page: Joi.number().integer().min(1).default(1),
  limit: Joi.number().integer().min(1).max(100).default(20),
  sort: Joi.string().valid("name", "-name").default("name"),
});

type Source = "body" | "query" | "params";

/**
 * Express 5 makes req.query a read-only getter, so the validated and converted
 * value is stored on res.locals[source] instead of being written back.
 */
export function validate(schema: Joi.ObjectSchema, source: Source = "body") {
  return (req: Request, res: Response, next: NextFunction) => {
    const { value, error } = schema.validate(req[source] ?? {}, {
      abortEarly: false,
      convert: true,
      stripUnknown: true,
    });
    if (error) {
      res.status(400).json({
        errors: error.details.map((d) => ({ path: d.path.join("."), type: d.type, message: d.message })),
      });
      return;
    }
    res.locals[source] = value;
    next();
  };
}

export function createApp() {
  const app = express();
  app.use(express.json());
  const users: Array<Record<string, unknown>> = [];

  app.post("/users", validate(createUserSchema), (_req, res) => {
    const user = { id: users.length + 1, ...res.locals.body };
    users.push(user);
    res.status(201).json(user);
  });

  app.get("/users", validate(listQuerySchema, "query"), (_req, res) => {
    const { page, limit, sort } = res.locals.query as { page: number; limit: number; sort: string };
    res.json({ page, limit, sort, total: users.length });
  });

  return app;
}
test/app.test.ts
import { test } from "node:test";
import assert from "node:assert/strict";
import request from "supertest";
import { createApp, createUserSchema } from "../src/app.ts";

test("valid body gets defaults, trimming, lowercasing and unknown keys stripped", async () => {
  const res = await request(createApp())
    .post("/users")
    .send({ email: "[email protected]", name: "  Ada  ", isAdmin: true });
  assert.equal(res.status, 201);
  assert.deepEqual(res.body, { id: 1, email: "[email protected]", name: "Ada", age: 18, role: "member" });
});

test("invalid body returns every error with its path", async () => {
  const res = await request(createApp()).post("/users").send({ email: "nope", age: 9, role: "root" });
  assert.equal(res.status, 400);
  const paths = res.body.errors.map((e: { path: string }) => e.path).sort();
  assert.deepEqual(paths, ["age", "email", "name", "role"]);
  const email = res.body.errors.find((e: { path: string }) => e.path === "email");
  assert.equal(email.type, "string.email");
});

test("query strings are converted to numbers with defaults", async () => {
  const res = await request(createApp()).get("/users?page=3");
  assert.equal(res.status, 200);
  assert.deepEqual(res.body, { page: 3, limit: 20, sort: "name", total: 0 });
  const bad = await request(createApp()).get("/users?limit=500");
  assert.equal(bad.status, 400);
  assert.equal(bad.body.errors[0].type, "number.max");
});

test("schema can be used directly outside Express", () => {
  const { error, value } = createUserSchema.validate({ email: "[email protected]", name: "Al", age: "21" });
  assert.equal(error, undefined);
  assert.equal(value.age, 21);
});

Connect to ProvenPin

Add the free MCP server so your agent can pull this recipe and others like it. Same setup as the docs.

terminal
claude mcp add --transport http provenpin https://mcp.provenpin.com/mcp

Any other MCP client: Streamable HTTP at https://mcp.provenpin.com/mcp. No API key, no signup.