npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@zodyac/zod-express

v1.2.0

Published

Request validation for Express using zod

Downloads

59

Readme

Zod Express validator

npm version NPM Downloads npm bundle size

This package provides a set of usefull Express tools for REST request validation with zod (body, parameters and query) based on Matt Pocock's (💜) solution.

Installation

As simple as:

npm i @zodyac/express

pnpm add @zodyac/express

yarn add @zodyac/express

bun add @zodyac/express

Usage

Validating body

Define your request body schema:

import { z } from "zod";

const zBody = z.object({
  // ... your zod schema
});

Create an endpoint using CheckBody function:

const my_endpoint = CheckBody(zBody, (req, res) => {
  const body = req.body;
  // ... the rest of your code
});

Validating parameters

You can also parse your request parameters using CheckParams:

const my_endpoint = CheckParams(zParams, (req, res) => {
  const params = req.params;
  // ... the rest of your code
});

Validating query parameters

And query parameters using CheckQuery:

const my_endpoint = CheckQuery(zQuery, (req, res) => {
  const query = req.query;
  // ... the rest of your code
});

As you can see, req.body, req.params and req.query are inferring types from your zod schema.

Please remember that Express params and query parameters are always strings. If you want to parse them to other types, you have to do it manually.

Validating all at once

But what if... We want to validate all of them at once? No problem, just use Check:

const my_endpoint = Check(
  {
    body: zBody,
    params: zParams,
    query: zQuery,
  },
  (req, res) => {
    const body = req.body;
    const params = req.params;
    const query = req.query;
    // ... the rest of your code
  }
);

Error handling

If validation fails, Check, CheckBody, CheckParams and CheckQuery will automatically send 406 response with error message. If you want to handle errors yourself, you can use ValidationOptions:

const my_error_handler: ze.ValidationOptions = {
  errorCode: 400, // default is 406 (Not Acceptable)
  errorHandler: (req, res, error) => {
    // error is zod Error
    const error_message = error.errors[0].message;
    // ... your error handling code
  },
};

const my_endpoint = Check(
  {
    body: zBody,
    params: zParams,
    query: zQuery,
  },
  (req, res) => {
    const body = req.body;
    const params = req.params;
    const query = req.query;
    // ... the rest of your code
  },
  my_error_handler
);

ValidationOptions interface:

type ErrorHandler = (req: Request, res: Response, error: z.ZodError) => void;

interface ValidationOptions {
  errorCode?: number;
  errorHandler?: ErrorHandler;
}

Middleware

If you prefer to validate your requests aside from your endpoints logic, you can use zem.Body, zem.Params, zem.Query or zem.Check middleware:

import { zem } from "@zodyac/express";

const my_endpoint = (req: Request, res: Response) => {
  const body = req.body;
  const params = req.params;
  const query = req.query;
  // ... the rest of your code
};

app.post("/my_endpoint", zem.Body(zBody), my_endpoint);
app.get("/my_endpoint/:id", zem.Params(zParams), my_endpoint);
app.get("/my_endpoint", zem.Query(zQuery), my_endpoint);

app.put(
  "/my_endpoint",
  zem.Check({
    body: zBody,
    params: zParams,
    query: zQuery,
  }),
  my_endpoint
);

In this case your req.body, req.params and req.query will be any. If you want to use types, you have to specify them manually or use CheckBody, CheckParams, CheckQuery or Check.

Experimental: decorators

You can also use decorators to validate your requests. Just add @ValidateBody, @ValidateParams, @ValidateQuery or @Validate to your endpoint function:

export class Example {
  @ValidateBody(zBody)
  public static my_endpoint(req: Request, res: Response) {
    const body = req.body as z.infer<typeof zBody>;
    // ... the rest of your code
  }
}

Due to the limitations of TypeScript decorators, you have to specify the type of req.body manually.

Contributing

Feel free to open issues and pull requests! Here's a quick guide to get you started:

  • Fork the repository
  • Install linter and formatter for VSCode: Biome
  • Install dependencies: npm i
  • Make changes
  • ~~Run tests: npm test~~ (not implemented yet)
  • Run linter: npm run lint (fix with npm run lint:fix)
  • Commit and push your changes
  • Open a pull request

License

MIT