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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@api-envelope/nextjs

v0.1.1

Published

Standardized API Envelope response helpers for Next.js App Router route handlers.

Readme

@api-envelope/nextjs

Standardized API Envelope response helpers for Next.js App Router route handlers.

Table of contents

Why use this

Route handlers under app/api/**/route.ts return plain Response objects, so it's easy for each one to end up with a slightly different error shape. createNextEnvelope() gives every route handler in your app the same { success, code, status, message, data } body, built from a Response you return exactly the way App Router expects.

Install

npm install @api-envelope/nextjs

Requires next in your project. @api-envelope/core is installed automatically.

Quick start

Create the envelope once and import it wherever you need it:

// lib/envelope.ts
import { createNextEnvelope } from "@api-envelope/nextjs";

export const envelope = createNextEnvelope();
// app/api/users/[id]/route.ts
import { envelope } from "@/lib/envelope";

export async function GET(request: Request, { params }: { params: { id: string } }) {
  const user = { id: params.id, name: "Ada" };
  return envelope.ok({ code: "OK", data: user });
}
// app/api/users/[id]/missing/route.ts
import { envelope } from "@/lib/envelope";

export async function GET() {
  return envelope.fail({ code: "NOT_FOUND", message: "User does not exist" });
}

envelope.ok() returns a native Response200 { success: true, code: "OK", status: 200, message: "...", data: {...} }. envelope.fail() returns 404 { success: false, code: "NOT_FOUND", status: 404, message: "User does not exist" }.

Configuration — custom codes

// lib/envelope.ts
export const envelope = createNextEnvelope({
  codes: [
    { code: "USER_NOT_FOUND", status: 404 },
    { code: "EMAIL_EXISTS", status: 409 },
  ],
});
// app/api/users/route.ts
import { envelope } from "@/lib/envelope";

export async function POST(request: Request) {
  const body = await request.json();
  if (await emailTaken(body.email)) {
    return envelope.fail({ code: "EMAIL_EXISTS" });
  }
  const user = await createUser(body);
  return envelope.ok({ code: "CREATED", data: user });
}

Built-in codes (OK, SUCCESS, CREATED, NOT_FOUND, ...) are always available; see @api-envelope/core for the full default list.

Type-safe custom codes

import type { DefaultCode } from "@api-envelope/nextjs";

type AppCode = DefaultCode | "USER_NOT_FOUND" | "EMAIL_EXISTS";

return envelope.fail<AppCode>({ code: "EMAIL_EXISTS" }); // autocompleted & checked

Things to know

  • Create envelope once, at module scope. Put createNextEnvelope() in a shared file like lib/envelope.ts and import it — creating a new one inside every route handler works but throws away the point of a shared custom-code registry.
  • Works in both Node and Edge runtimes. Since envelope.ok()/fail() return a standard Web Response, route handlers can set export const runtime = "edge" without any change to how you call them.
  • This is for Route Handlers, not Server Actions. Server Actions don't return a Response, so envelope.ok()/fail() aren't meant for them.
  • Custom codes can override defaults, the same as every other adapter.

API reference

createNextEnvelope(options?)

Returns { ok, fail }. options.codes is an optional array of { code, status } pairs registered on top of the built-in defaults. Call this once per app (e.g. in lib/envelope.ts) and import the result.

envelope.ok({ code, data, message? })

Returns a Response built with Response.json(...) and the matching HTTP status.

envelope.fail({ code, message? })

Returns a Response built with Response.json(...) and the matching HTTP status.

Both throw if code hasn't been registered — check for typos in custom codes, or make sure options.codes was passed to createNextEnvelope().

FAQ

Does this work with the Pages Router (pages/api)? No — envelope.ok()/fail() return a Web Response, which App Router route handlers expect natively. Pages Router's res.json() API is a different shape; use @api-envelope/express-style helpers or call @api-envelope/core directly there instead.

Can I use this in Middleware? Yes — Next.js Middleware also works with the standard Response object, so envelope.ok()/fail() return values it can use.

Why is there no default export? To keep the import style consistent with the other named exports (ApiEnvelopeOptions, etc.) from this package.

License

MIT © 2026 ltimsina

Copyright (c) [2026] [ltimsina]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

See also