@api-envelope/nextjs
v0.1.1
Published
Standardized API Envelope response helpers for Next.js App Router route handlers.
Maintainers
Readme
@api-envelope/nextjs
Standardized API Envelope response helpers for Next.js App Router route handlers.
Table of contents
- Why use this
- Install
- Quick start
- Configuration — custom codes
- Type-safe custom codes
- Things to know
- API reference
- FAQ
- License
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/nextjsRequires 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 Response — 200 { 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 & checkedThings to know
- Create
envelopeonce, at module scope. PutcreateNextEnvelope()in a shared file likelib/envelope.tsand 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 WebResponse, route handlers can setexport 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, soenvelope.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
@api-envelope/core— shared types and the code registry these helpers build on.
