|
| 1 | +# @ideative/next-handler |
| 2 | + |
| 3 | +Typed helpers for Next.js route handlers with: |
| 4 | + |
| 5 | +- request context access (`getRequest()`), |
| 6 | +- Zod payload validation (`payload()`), |
| 7 | +- serializable errors that round-trip from backend to frontend. |
| 8 | + |
| 9 | +## Install |
| 10 | + |
| 11 | +```bash |
| 12 | +pnpm add @ideative/next-handler |
| 13 | +``` |
| 14 | + |
| 15 | +Peer dependencies: |
| 16 | + |
| 17 | +- `next` >= 15 |
| 18 | +- `zod` >= 4.3.6 |
| 19 | +- `react` >= 19.2.4 (for intl context utilities) |
| 20 | +- `next-intl` >= 4.8.2 (for intl utilities) |
| 21 | + |
| 22 | +## Backend usage |
| 23 | + |
| 24 | +### Wrap handlers |
| 25 | + |
| 26 | +```ts |
| 27 | +import { NextResponse } from "next/server"; |
| 28 | +import { withApiHandler, payload, getRequest } from "@ideative/next-handler"; |
| 29 | +import { z } from "zod"; |
| 30 | + |
| 31 | +const schema = z.object({ name: z.string(), email: z.string().email() }); |
| 32 | + |
| 33 | +export const POST = withApiHandler(async () => { |
| 34 | + const body = await payload(schema); |
| 35 | + const req = getRequest(); |
| 36 | + return NextResponse.json({ from: req.url, ...body }); |
| 37 | +}); |
| 38 | +``` |
| 39 | + |
| 40 | +### Throw typed API errors |
| 41 | + |
| 42 | +```ts |
| 43 | +import { |
| 44 | + withApiHandler, |
| 45 | + BadRequestError, |
| 46 | + NotFoundError, |
| 47 | + UnauthorizedError, |
| 48 | +} from "@ideative/next-handler"; |
| 49 | + |
| 50 | +export const GET = withApiHandler(async (req) => { |
| 51 | + if (!req.headers.get("authorization")) throw new UnauthorizedError("Missing token"); |
| 52 | + throw new NotFoundError("User"); |
| 53 | +}); |
| 54 | +``` |
| 55 | + |
| 56 | +Built-ins: |
| 57 | + |
| 58 | +- `BadRequestError` (400) |
| 59 | +- `UnauthorizedError` (401) |
| 60 | +- `ForbiddenError` (403) |
| 61 | +- `NotFoundError` (404) |
| 62 | +- `ConflictError` (409) |
| 63 | +- `InternalServerError` (500) |
| 64 | + |
| 65 | +## Wire format contract |
| 66 | + |
| 67 | +Known API errors are returned as a serialized object: |
| 68 | + |
| 69 | +```ts |
| 70 | +type SerializedApiError = { |
| 71 | + name: string; |
| 72 | + uid: string; |
| 73 | + message: string; |
| 74 | + status?: number; |
| 75 | + details?: unknown; |
| 76 | + isSerializableError: true; |
| 77 | + [key: string]: unknown; |
| 78 | +}; |
| 79 | +``` |
| 80 | + |
| 81 | +Unhandled non-library errors return: |
| 82 | + |
| 83 | +```json |
| 84 | +{ "error": "An error occurred" } |
| 85 | +``` |
| 86 | + |
| 87 | +## Frontend integration with ky (`afterResponse`) |
| 88 | + |
| 89 | +```ts |
| 90 | +import ky from "ky"; |
| 91 | +import { |
| 92 | + scanResponseAndThrowErrors, |
| 93 | + BadRequestError, |
| 94 | + NotFoundError, |
| 95 | +} from "@ideative/next-handler"; |
| 96 | + |
| 97 | +const api = ky.create({ |
| 98 | + prefixUrl: "/api", |
| 99 | + hooks: { |
| 100 | + afterResponse: [ |
| 101 | + async (_req, _opts, response) => { |
| 102 | + await scanResponseAndThrowErrors(response); |
| 103 | + if (!response.ok) throw new Error(response.statusText); |
| 104 | + return response; |
| 105 | + }, |
| 106 | + ], |
| 107 | + }, |
| 108 | +}); |
| 109 | + |
| 110 | +try { |
| 111 | + await api.get("users/123").json(); |
| 112 | +} catch (e) { |
| 113 | + if (e instanceof NotFoundError) console.log(e.resource); |
| 114 | + if (e instanceof BadRequestError) console.log(e.details); |
| 115 | +} |
| 116 | +``` |
| 117 | + |
| 118 | +If you already have a `Response`, you can also call: |
| 119 | + |
| 120 | +```ts |
| 121 | +import { scanResponseAndThrowErrors } from "@ideative/next-handler"; |
| 122 | + |
| 123 | +await scanResponseAndThrowErrors(response); |
| 124 | +``` |
| 125 | + |
| 126 | +## Frontend integration with axios (response interceptor) |
| 127 | + |
| 128 | +```ts |
| 129 | +import axios from "axios"; |
| 130 | +import { deserializeApiError } from "@ideative/next-handler"; |
| 131 | + |
| 132 | +const api = axios.create({ baseURL: "/api" }); |
| 133 | + |
| 134 | +api.interceptors.response.use( |
| 135 | + (res) => res, |
| 136 | + (err) => { |
| 137 | + if (!axios.isAxiosError(err) || !err.response) return Promise.reject(err); |
| 138 | + const data = err.response.data; |
| 139 | + const candidate = |
| 140 | + typeof data === "object" && data !== null && "error" in data |
| 141 | + ? (data as { error: unknown }).error |
| 142 | + : data; |
| 143 | + const apiError = deserializeApiError(candidate); |
| 144 | + return Promise.reject(apiError ?? err); |
| 145 | + } |
| 146 | +); |
| 147 | +``` |
| 148 | + |
| 149 | +## Custom error types |
| 150 | + |
| 151 | +`EndpointError` is abstract and expects `(name, status, message, details?)`. |
| 152 | + |
| 153 | +```ts |
| 154 | +import { |
| 155 | + apiErrorFactory, |
| 156 | + EndpointError, |
| 157 | + type ErrorDeserializer, |
| 158 | +} from "@ideative/next-handler"; |
| 159 | + |
| 160 | +class PaymentRequiredError extends EndpointError { |
| 161 | + static ErrorName() { |
| 162 | + return "PaymentRequiredError"; |
| 163 | + } |
| 164 | + constructor(message = "Payment required") { |
| 165 | + super(PaymentRequiredError.ErrorName(), 402, message); |
| 166 | + } |
| 167 | +} |
| 168 | + |
| 169 | +const deserialize: ErrorDeserializer<PaymentRequiredError> = (d) => |
| 170 | + new PaymentRequiredError(d.message); |
| 171 | + |
| 172 | +apiErrorFactory.register(PaymentRequiredError, deserialize); |
| 173 | +``` |
| 174 | + |
| 175 | +Register custom errors in both server and client runtime initialization so deserialization works everywhere. |
| 176 | + |
| 177 | +## Intl exports |
| 178 | + |
| 179 | +Import intl helpers from: |
| 180 | + |
| 181 | +- `@ideative/next-handler/intl` |
| 182 | +- `@ideative/next-handler/intl/intl-context` |
| 183 | + |
| 184 | +## API summary |
| 185 | + |
| 186 | +| Export | Description | |
| 187 | +| --- | --- | |
| 188 | +| `withApiHandler(handler)` | Wraps route handlers and converts thrown `EndpointError` values to JSON responses. | |
| 189 | +| `payload(schema)` | Reads and validates request JSON with Zod, throws `BadRequestError` on invalid input. | |
| 190 | +| `getRequest()` | Gets current `NextRequest` from AsyncLocalStorage context. | |
| 191 | +| `serializeApiError(error)` | Converts `SerializableError` to transport-safe payload. | |
| 192 | +| `deserializeApiError(data)` | Converts payload back to typed error, or `null` if payload is not recognized. | |
| 193 | +| `isSerializedApiError(data)` | Runtime type-guard for serialized payload shape. | |
| 194 | +| `scanResponseAndThrowErrors(response)` | Scans non-OK responses and rethrows serialized API errors if present. | |
| 195 | +| `apiErrorFactory.register(ctor, deserialize)` | Register custom error classes for round-trip behavior. | |
| 196 | + |
| 197 | +## v0.1.0 release checklist |
| 198 | + |
| 199 | +- `pnpm run build` emits all exported entry points. |
| 200 | +- `pnpm test` passes. |
| 201 | +- README examples match current runtime contracts. |
| 202 | +- `package.json` exports resolve to emitted `dist/` files. |
0 commit comments