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

next-api-zod

v0.1.0

Published

This is a simple wrapper for API route [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) in the new (standard now) App Router to validate user input.

Downloads

5

Readme

Next API Route Zod Validator

This is a simple wrapper for API route Route Handlers in the new (standard now) App Router to validate user input.

Motivation

I was looking for a simple solution to validate body, dynamic route param segments and search query params that would validate input and return type safe data or return 400 JSON error on failure. Of course I could add that logic to every route individually, but that sound like convoluted and repetitive process. So, once I failed to find what I was looking for, I've spent an evening and build this helper library.

Features

  • validates body (JSON)
  • validates search query params
  • validates dynamic route segments
  • validates headers
  • returns simple 400 error JSON response or returns error list in third param for you to return own response in handler or pre-handler
  • offers to run pre-handler (with access to validated data), so you can re-use logic to check auth tokens etc. Return data will be available in handler as ctx. Throw error to stop execution and return HTTP error (configurable to turn off)
  • returns third param to main handler with type safe validated input, an object: {body?: {}, segment?: {}, query?: {}, headers?: {}, errors?: {}, ctx?: unknown}
  • exports ApiHandlerError to throw on preHandler (you can also throw standard Error, then 400 status will be returned)

Usage

Import validator and wrap your route.

First param is an object (every key is optional) with 3 keys available:

  • schema, for schema setup with your Zod definitions (you need to provide z.object)
  • preHandler, a function where you can extract logic for repetitive tasks, ie to check token etc.
  • options, currently you can turn on/off functionality to show 400 page on any Zod error via return400ValidationError, this is true by default

Second param is your standard handler with extra 3rd param - validated, type safe input and if you set return400ValidationError to false, you'll also get Zod errors.

Code example

// src/app/api/route/[someParam]/route.ts

import { NextResponse } from 'next/server';
import { z } from 'zod';
import { apiHandler, ApiHandlerError } from 'next-api-zod';

export const POST = apiHandler(
  {
    schema: {
      body: z.object({ someKey: z.string() }),
      segment: z.object({ someParam: z.string().max(5) }),
      query: z.object({ someQueryParam: z.string() }),
      headers: z.object({ someHeader: z.string() }),
    },
    config: {
      return400ValidationError: false,
    },
    preHandler: (req, nfe, { headers }) => {
      // here you can validate token, etc
      // throw to stop execution - handler will not run
      // dummy code as an example
      if (!isValidToken(headers)) {
        throw new ApiHandlerError({ msg: "some error" }, 401);
      }
      // what you return here will be available in handler as ctx
      return userData;
    },
  },
  (req, nfe, { body, query, segment, headers, ctx: userData }) => {
    console.log({
      body: body.someKey,
      qp: query.someQueryParam,
      segment: segment.someParam,
      headers: headers.someHeader,
      userData
    });

    return new NextResponse("OK");
  }
);