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-route

v0.2.1

Published

Small routing library for [API Routes](https://nextjs.org/docs/api-routes/introduction) in [Next.js](https://nextjs.org/)

Downloads

8

Readme

next-api-route npm

Small routing library for API Routes in Next.js

Installation

npm install next-api-route
# or
yarn add next-api-route
# or
pnpm add next-api-route

Usage

// pages/api/hello.ts
import { createRouter, route } from "next-api-route";

export default createRouter({
    GET: route().build(({ req, res }) => {
        res.status(200).json({ hello: "world" });
    }),

    POST: route().build(({ req, res }) => {
        // returned value is automatically passed to `res.json`
        return { foo: "bar" };
    }),
});

Validation with Zod

You can use zod to validate req.body and req.query:

// pages/api/hello.ts
import { createRouter, route } from "next-api-route";
import { z } from "zod";

export default createRouter({
    POST: route()
        .query(
            z.object({
                id: z.string().min(1),
            })
        )
        .body(
            z.object({
                value: z.number(),
            })
        )
        .build(async ({ req, res, query, body }) => {
            // `query` and `body` are fully typed now
            const item = await updateItem(query.id, body.value);
            return item;
        }),
});

Middleware

You can add custom middleware to routes with .use() method:

// pages/api/hello.ts
import { createRouter, route } from "next-api-route";

export default createRouter({
    GET: route()
        .use(async (req, res, next) => {
            const start = Date.now();
            try {
                await next();
            } finally {
                const duration = Date.now() - start;
                console.log(`${req.method} request completed in ${duration}ms`);
            }
        })
        .build(async ({ req, res }) => {
            return { foo: "bar" };
        }),
});

Or you can also create a reusable route builder:

// pages/api/hello.ts
import { createRouter, route, Middleware } from "next-api-route";

const logger: Middleware = async (req, res, next) => {
    const start = Date.now();
    try {
        await next();
    } finally {
        const duration = Date.now() - start;
        console.log(`${req.method} request completed in ${duration}ms`);
    }
};

const loggedRoute = route().use(logger);

export default createRouter({
    GET: loggedRoute.build(async ({ req, res }) => {
        return { foo: "bar" };
    }),

    POST: loggedRoute.build(async ({ req, res }) => {
        return { hello: "world" };
    }),
});

Custom Error Handlers

// pages/api/hello.ts
import { createRouter, route } from "next-api-route";

export default createRouter(
    {
        GET: route().build(async ({ req, res }) => {
            return { foo: "bar" };
        }),
    },
    {
        // called when there is no route matching request method
        onNotAllowed(method, req, res) {
            res.status(405).send(`Method ${method} isn't supported`);
        },
        // catches all errors inside handlers
        onError(error, req, res) {
            console.error(error);
            res.status(500).send("Oops, something went wrong...");
        },
    }
);