@api-envelope/core
v0.1.1
Published
Framework-agnostic builder for standardized success/failure API response envelopes, with a customizable code-to-HTTP-status registry.
Maintainers
Readme
@api-envelope/core
Framework-agnostic builder for standardized success/failure API response envelopes, with a customizable code-to-HTTP-status registry.
Table of contents
- Why use this
- Install
- Quick start
- Built-in codes
- Registering custom codes
- Type-safe custom codes
- Things to know
- API reference
- FAQ
- License
Why use this
Every route in a real API eventually needs to answer the same two
questions: what HTTP status do I send, and what shape does the body
take. Left unmanaged, that turns into scattered res.status(404).json({...})
calls with slightly different field names in every route file.
@api-envelope/core centralizes both: give it a code, it resolves the
status and builds a consistent { success, code, status, message, data }
body every time — whether you call it directly or through one of the
framework adapters.
Install
npm install @api-envelope/coreInstall this directly only if you're calling ApiResponse yourself
outside a supported framework, or writing a new adapter. Otherwise install
the adapter for your framework — it pulls this in automatically.
Quick start
import ApiResponse from "@api-envelope/core";
const api = new ApiResponse();
api.ok({ code: "OK", data: { id: 1 } });
// { success: true, code: "OK", status: 200, message: "Request completed successfully", data: { id: 1 } }
api.fail({ code: "NOT_FOUND" });
// { success: false, code: "NOT_FOUND", status: 404, message: "Request failed" }ApiResponse never touches HTTP. It only builds the plain object above —
each adapter is responsible for putting status and the JSON body onto
whatever response object its framework uses.
Built-in codes
Every ApiResponse instance starts pre-loaded with these. Multiple codes
can share a status (OK/SUCCESS, CREATED/ADDED) — pick whichever
name reads better at the call site.
| Code | Status |
| ------------------------------ | ------ |
| 2xx — Success | |
| OK | 200 |
| SUCCESS | 200 |
| CREATED | 201 |
| ADDED | 201 |
| ACCEPTED | 202 |
| NO_CONTENT | 204 |
| 3xx — Redirection | |
| MOVED_PERMANENTLY | 301 |
| FOUND | 302 |
| NOT_MODIFIED | 304 |
| TEMPORARY_REDIRECT | 307 |
| PERMANENT_REDIRECT | 308 |
| 4xx — Client errors | |
| BAD_REQUEST | 400 |
| UNAUTHORIZED | 401 |
| FORBIDDEN | 403 |
| NOT_FOUND | 404 |
| METHOD_NOT_ALLOWED | 405 |
| NOT_ACCEPTABLE | 406 |
| REQUEST_TIMEOUT | 408 |
| CONFLICT | 409 |
| GONE | 410 |
| UNPROCESSABLE_ENTITY | 422 |
| TOO_MANY_REQUESTS | 429 |
| 5xx — Server errors | |
| INTERNAL_SERVER_ERROR | 500 |
| NOT_IMPLEMENTED | 501 |
| BAD_GATEWAY | 502 |
| SERVICE_UNAVAILABLE | 503 |
| GATEWAY_TIMEOUT | 504 |
Code lookups are case-insensitive: api.fail({ code: "not_found" }) works
the same as "NOT_FOUND".
Registering custom codes
api.defineCode("USER_NOT_FOUND", 404);
api.fail({ code: "USER_NOT_FOUND" });
// { success: false, code: "USER_NOT_FOUND", status: 404, message: "Request failed" }Codes must be unique case-insensitively — registering "user_created"
twice (or as "USER_CREATED" later) throws, even if the status differs.
Every @api-envelope/* adapter exposes this as an options.codes array
so you don't need to call defineCode yourself:
useApiEnvelope({
codes: [
{ code: "USER_NOT_FOUND", status: 404 },
{ code: "EMAIL_EXISTS", status: 409 },
],
});Type-safe custom codes
Code defaults to DefaultCode (the union of built-in code names). Extend
it to get autocomplete and compile-time checking on your own codes:
import type { DefaultCode } from "@api-envelope/core";
type AppCode = DefaultCode | "USER_NOT_FOUND" | "EMAIL_EXISTS";
api.fail<AppCode>({ code: "USER_NOT_FOUND" }); // ✅ type-checked
api.fail<AppCode>({ code: "TYPO" }); // ❌ compile errorThings to know
- Each
new ApiResponse()owns an isolated registry. Custom codes registered on one instance are never visible on another — this is what lets multiple adapter registrations coexist without colliding. ok()/fail()throw on unregistered codes. There's no silent fallback to a default status; a typo in a custom code surfaces immediately asError: Code "..." is not defined.datapasses through untouched, includingnullandundefined—ApiResponsenever validates or transforms your payload.- This package builds objects, not responses. If you're not using one
of the adapters, you still need to apply
output.statusand JSON-encode the result yourself.
API reference
new ApiResponse()
Creates an instance with its own isolated code registry, pre-loaded with the built-in codes above.
api.ok({ code, data, message? })
Builds a success envelope. message defaults to
"Request completed successfully". Throws if code isn't registered.
api.fail({ code, message? })
Builds a failure envelope. message defaults to "Request failed".
Throws if code isn't registered.
api.defineCode(code, status)
Registers a new code on this instance. Throws on a case-insensitive duplicate.
api.getAllCodes() / api.getDefaultCodes() / api.getCustomCodes()
Introspection helpers — each returns { code, status }[].
FAQ
Does @api-envelope/core send the HTTP response for me?
No. It only builds the { success, code, status, message, data } object.
Sending it is the adapter's job — or your own, if you're using core
directly.
Can two codes point to the same status?
Yes — OK/SUCCESS and CREATED/ADDED are built-in examples. Pick
whichever name best documents intent at the call site.
What happens if I register a code that's already taken?
defineCode() throws, even if the new status differs from the existing
one. Registration is case-insensitive, so "user_created" and
"USER_CREATED" collide.
Do I need to register OK, NOT_FOUND, etc. myself?
No — the built-in codes table above is loaded
automatically into every instance.
Is the Code generic required?
No, it defaults to DefaultCode. Pass your own extended union only when
you want compile-time checking on custom codes.
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.
