tsentials/http
Fetch API wrapper that returns Result<T> instead of throwing on 4xx/5xx responses. Never catch fetch exceptions again.
Installation
npm install tsentials
Import
import { fetchResult, RequestBuilder, httpStatusToError, extractErrorDescription } from 'tsentials/http';
import { computeETag, formatETag, notModified, checkIfMatch } from 'tsentials/http';
import { toProblemDetails, toProblemResponse, resultToResponse } from 'tsentials/http';
import { isBlockedAddress } from 'tsentials/http';
fetchResult — direct fetch wrapper
fetchResult is a const object with HTTP method functions — not a generic function. Each method returns Promise<Result<T>>.
import { fetchResult } from 'tsentials/http';
// GET
const result = await fetchResult.get<User>('https://api.example.com/users/1');
// POST with JSON body
const created = await fetchResult.post<Order>('https://api.example.com/orders', newOrder);
// PUT with JSON body
const updated = await fetchResult.put<User>('https://api.example.com/users/1', userDto);
// PATCH with JSON body
const patched = await fetchResult.patch<User>('https://api.example.com/users/1', partial);
// DELETE
const deleted = await fetchResult.delete('https://api.example.com/users/1');
// 2xx → Result.success(T), 4xx/5xx → Result.failure(AppError)
if (result.ok) {
console.log(result.value); // User
} else {
console.log(result.errors[0]?.description);
}
fetchResult Method Signatures
fetchResult.get<T>(url: string | URL, init?: RequestInit): Promise<Result<T>>
fetchResult.post<T>(url: string | URL, body: unknown, init?: RequestInit): Promise<Result<T>>
fetchResult.put<T>(url: string | URL, body: unknown, init?: RequestInit): Promise<Result<T>>
fetchResult.patch<T>(url: string | URL, body: unknown, init?: RequestInit): Promise<Result<T>>
fetchResult.delete<T = void>(url: string | URL, init?: RequestInit): Promise<Result<T>>
POST, PUT, and PATCH automatically set Content-Type: application/json and stringify the body.
A 2xx JSON response with an empty or null body is a NotFound failure (code NotFound), except for fetchResult.delete, which succeeds with undefined. 204/205 and non-JSON responses are void successes. A body that is not read (204/205, a non-JSON 2xx or error response) is cancelled so the connection is released.
Text and binary bodies
Set responseType ('text', 'blob' or 'arrayBuffer') to read a 2xx body as a string, Blob or ArrayBuffer whatever its content type; the default 'json' keeps the rules above. An empty body or 204/205 gives an empty value, not NotFound. Error responses go through the same ProblemDetails parsing, a read error is an Unexpected failure with the response status, a timeout is Http.Timeout, and the caller's abort still rejects.
const csv = await fetchResult.get<string>('/export.csv', { responseType: 'text' });
const pdf = await RequestBuilder.get('/invoice/7').responseType('blob').send<Blob>();
const bytes = await fetchResult.post<ArrayBuffer>('/render', { id: 7 }, { responseType: 'arrayBuffer' });
RequestBuilder — fluent request construction
For requests with multiple headers, query parameters, or custom bodies. The terminal method is .send<T>().
import { RequestBuilder } from 'tsentials/http';
// GET with headers and query params
const result = await RequestBuilder.get('https://api.example.com/users')
.header('Authorization', `Bearer ${token}`)
.header('X-Correlation-Id', correlationId)
.query('page', '1')
.query('limit', '20')
.send<User[]>();
// Route placeholders, array and Date query values
const posts = await RequestBuilder.get('https://api.example.com/users/{id}/posts')
.route('id', userId) // URL-encoded
.query('tag', ['news', 'tech']) // tag=news&tag=tech
.query('since', new Date(2026, 0, 1)) // ISO 8601
.send<Post[]>();
// POST with JSON body
const posted = await RequestBuilder.post('https://api.example.com/orders')
.header('Authorization', `Bearer ${token}`)
.json(newOrder)
.send<Order>();
// PUT
const updated = await RequestBuilder.put(`https://api.example.com/users/${id}`)
.header('Authorization', `Bearer ${token}`)
.json(userDto)
.send<User>();
// PATCH
const patched = await RequestBuilder.patch(`https://api.example.com/users/${id}`)
.header('Authorization', `Bearer ${token}`)
.json(partial)
.send<User>();
// DELETE — send<T>() expects a value: an empty/null JSON body is a NotFound failure
// (use fetchResult.delete for a DELETE that may answer with an empty body)
const deleted = await RequestBuilder.delete(`https://api.example.com/users/${id}`)
.header('Authorization', `Bearer ${token}`)
.send<DeleteReceipt>();
// Raw (non-JSON) body on POST/PUT/PATCH — .body() bypasses JSON serialization entirely
const uploaded = await RequestBuilder.post('https://api.example.com/upload')
.header('Content-Type', 'text/plain')
.body(rawText)
.send<UploadResult>();
.json(value) stringifies value and sets Content-Type: application/json. .body(raw) sends raw (a BodyInit — string, Blob, FormData, ArrayBuffer, ...) untouched, with no assumption that it's JSON — send<T>() never runs JSON.parse/JSON.stringify on a .body() payload, so it can't throw on non-JSON content. Calling .json() after .body() (or vice versa) simply replaces whichever was set last.
RequestBuilder API
| Static Factory | Returns |
|----------------|---------|
| RequestBuilder.get(url) | RequestBuilder |
| RequestBuilder.post(url) | RequestBuilder |
| RequestBuilder.put(url) | RequestBuilder |
| RequestBuilder.patch(url) | RequestBuilder |
| RequestBuilder.delete(url) | RequestBuilder |
| Builder Method | Description |
|----------------|-------------|
| .header(name, value) | Add a request header; the same name again adds another value (Content-Type is replaced) |
| .query(name, value) / .query(record) | Append query string parameters; an array repeats the key (tag=a&tag=b), a Date is sent as ISO 8601, null/undefined record values are skipped |
| .route(name, value) / .route(record) | Replace every {name} placeholder in the URL with the URL-encoded value; a missing placeholder or a null/undefined value makes send() a Validation failure (RequestBuilder.RouteParameterNotFound, RequestBuilder.RouteValueRequired) with no request sent |
| .json(body) | Set body as JSON + Content-Type header |
| .body(body: BodyInit) | Set raw body |
| .idempotencyKey(key?, { idempotencyKeyGenerator }?) | Set Idempotency-Key (a UUID, or your generator's result, created once when omitted and validated like an explicit key; every send() reuses it) |
| .send<T>() | Send request, returns Promise<Result<T>> |
Cancellation and timeout
fetchResult and RequestBuilder accept an AbortSignal and a request timeout.
const ctrl = new AbortController();
await fetchResult.get<User>('/users/42', { signal: ctrl.signal, timeout: 5_000 });
await RequestBuilder.get('/users')
.query({ limit: 10, q: undefined }) // record form; null/undefined values are skipped
.timeout(5_000)
.signal(ctrl.signal)
.send<User[]>();
- AbortSignal convention: the caller's abort rejects the promise with
signal.reason; it never becomes aResult. Network, HTTP and body-parse errors become failures. - A 2xx JSON body that cannot be parsed is a
Validationfailure (codeSyntaxError, withhttpStatusmetadata), so a retry does not repeat it. A JSON request body that cannot be serialized (cyclic object, BigInt) is aValidationfailure (codeTypeError) and no request is sent.RequestBuilder.json()never throws: it serializes the value once, insend(). - Default timeout is 30 s (
timeoutin ms;0orInfinitydisables it). On expiry the result is a failure with codeHttp.Timeout(Unexpected).
Idempotency keys and retries
import { withIdempotencyKey, idempotentRetryClassifier, HttpErrorMetadataKeys } from 'tsentials/http';
const init = withIdempotencyKey({ method: 'POST', body }); // one key for every retry of this operation
await ResiliencePolicy.create()
.withRetry({ shouldRetry: idempotentRetryClassifier('POST', true) })
.execute((signal) => fetchResult.send<Order>('/orders', { ...init, signal }));
idempotentRetryClassifier(method, hasKey)treats GET, HEAD, PUT, DELETE and OPTIONS as safe and every other method as unsafe. It never retries an unsafe method without a key or a replayed response. It retries network errors, timeouts, 408, 429, 503 and 504, any other 5xx for a safe method only, and 409Idempotency.InFlightonly whenhasKeyistrue.- A failed response's first error carries
HttpErrorMetadataKeysmetadata:httpStatus,retryAfterMs(fromRetry-After, seeparseRetryAfter; an HTTP-date is measured from the responseDateheader, or the local clock without a valid one),idempotencyReplayed,problemCode. - Server side:
tsentials/idempotency(withIdempotency).
Conditional requests (ETag, 304, If-Match)
import { computeETag, formatETag, notModified, checkIfMatch } from 'tsentials/http';
// GET: answer 304 when the client's copy is current
async function getItem(request: Request): Promise<Response> {
const item = await load();
const etag = formatETag(item.version); // '"7"'; computeETag(body) hashes content
const headers = { 'cache-control': 'max-age=60' };
return notModified(request, { etag, lastModified: item.updatedAt }, headers)
?? Response.json(item, { headers: { ...headers, etag } });
}
// PUT/PATCH/DELETE: optimistic concurrency
async function updateItem(request: Request): Promise<Response> {
const item = await load(); // null when it does not exist
const rejected = checkIfMatch(request, item && { etag: formatETag(item.version) }, { required: true });
if (rejected) return rejected; // 400, 412 or 428 problem+json
// ... write, passing the version as a concurrency token
}
formatETag(value, { weak })quotes an opaque value (RangeErrorfor spaces, quotes, non-ASCII).computeETag(stringOrBytes, { weak })is the base64url SHA-256 (Web Crypto). Both strong by default.notModified(request, { etag, lastModified }, headers?)only answersGET/HEAD.If-None-Matchuses weak comparison and*matches; without it,If-Modified-Sinceis compared with second precision. The 304 has no body and carriesETag,Last-Modifiedandheaders. Returnsundefinedwhen the full response should be sent.checkIfMatch(request, current, { required })only evaluatesPOST,PUT,PATCH,DELETE.currentisnull/undefinedwhen the resource does not exist. Strong comparison, so weak tags never match;*passes for any existing resource. Responses: 428Http.PreconditionRequired(missing header withrequired), 400Http.InvalidIfMatch(malformed, or*mixed with tags), 412Http.PreconditionFailed(mismatch or missing resource). Codes are inConditionalErrorCodes.parseETagList(header)returns'*', the tags as written,[]for a missing header, orundefinedwhen malformed.compareETags(a, b, 'strong' | 'weak')follows RFC 9110 section 8.8.3.2.- The
If-Matchcheck is not atomic with the write.If-Unmodified-SinceandIf-None-Matchon unsafe methods are not evaluated.
Problem responses (server side)
import { resultToResponse, toProblemDetails, toProblemResponse } from 'tsentials/http';
return resultToResponse(await createUser(input)); // 200 JSON, 204 for Result.ok(), or problem+json
return toProblemResponse([Err.notFound('User.NotFound', 'User 7 was not found.')], {
extensions: { traceId },
headers: { 'cache-control': 'no-store' },
});
const body = toProblemDetails(errors); // the plain object
- The body matches CSharpEssentials.AspNetCore:
{ type, title, status, detail, ...extensions, errorCodes, errors? }. The primary error is the one with the highesterrorTypeToHttpStatusstatus (the first on a tie) and givesstatus,title(from itsErrorType, such asNot FoundorValidation Error) anddetail. typeis the RFC 9110 section link (rfc9110TypeUri), left out for statuses without one.errorCodeslists every code once, in order.errorslists theValidationerrors as{ code, description }and is left out when there are none.- Options:
statusandtitlereplace the defaults (an overridden status withouttitlegets the status reason phrase, such asService Unavailable),typeUrireplaces the link resolver,extensionsadds members,headersadds response headers. - The status comes from the
ErrorTypeonly. CSharpEssentials also maps some codes to their own status (Idempotency.KeyReusedto 422,Idempotency.InFlightto 409, a failed precondition to 412); passstatus(andtitleif needed) for those. - The body reads back with
problemDetailsToErrors(and so withfetchResulton the client): codes, order and types are kept; a non-validation error that is not primary takes the primary error's description and the type of the status. toProblemDetails([])throws aTypeError.
Blocked addresses (SSRF checks)
isBlockedAddress(address) returns true for an IP literal that a server-side request to a user-supplied URL must not reach. The ranges are those of the CSharpEssentials SSRF guard: unspecified, loopback, private (RFC 1918), CGNAT (100.64.0.0/10), link-local (including the 169.254.169.254 metadata endpoint), unique local (fc00::/7), multicast, broadcast and reserved, and the documentation and benchmark ranges. An IPv4 address inside IPv6 (::ffff:127.0.0.1, ::10.0.0.1, 64:ff9b::a9fe:a9fe, 2002:c0a8:101::) is checked as IPv4 too.
import { lookup } from 'node:dns/promises';
import { isBlockedAddress } from 'tsentials/http';
async function assertPublicHost(url: URL): Promise<void> {
const host = url.hostname.replace(/^\[|\]$/g, ''); // URL keeps the brackets of an IPv6 literal
const addresses = await lookup(host, { all: true }); // an IP literal comes back as is
if (addresses.length === 0 || addresses.some((a) => isBlockedAddress(a.address))) {
throw new Error(`Blocked outbound host ${url.hostname}`);
}
}
await assertPublicHost(new URL(target));
const result = await fetchResult.get<Data>(target, { redirect: 'manual' });
- Parsing is strict. Accepted: dotted-decimal IPv4 with four parts and no leading zeros, and IPv6 with hex groups,
::and an optional dotted IPv4 tail, optionally in brackets (asURL.hostnamegives it). Anything else returnstrue: host names,127.1,0177.0.0.1,0x7f000001, zone ids such asfe80::1%eth0, and surrounding spaces. - Check every address the lookup returns, not just the first.
- It is a pure check, not a full SSRF defence.
fetchresolves the host again, so a DNS rebinding answer can still reach a blocked address between the check and the request; pin the checked address in the connection (a custom agent orlookup) for that. Redirects are followed by default: passredirect: 'manual'and check eachLocationyourself.
Chaining with ResultAsync
import { fromAsync } from 'tsentials/result';
import { Err } from 'tsentials/errors';
const profile = await fromAsync(
RequestBuilder.get('https://api.example.com/users/me')
.header('Authorization', `Bearer ${token}`)
.send<User>(),
)
.ensure(user => user.isActive, Err.validation('User.Inactive', 'Account is not active.'))
.map(user => user.profile)
.match(
profile => profile,
() => null,
);
Error Mapping
HTTP errors are automatically mapped to AppError with descriptive codes via httpStatusToError():
| HTTP Status | ErrorType | Notes |
|-------------|-----------|-------|
| 400 | Validation | Bad Request |
| 401 | Unauthorized | |
| 403 | Forbidden | |
| 404 | NotFound | |
| 409 | Conflict | |
| 410 | NotFound | Gone — mapped to NotFound |
| 422 | Validation | Unprocessable Entity — mapped to Validation |
| 429 | Conflict | Too Many Requests — mapped to Conflict |
| 5xx | Unexpected | All server errors |
| Other | Failure | Unmapped status codes |
| Network error | Unexpected | TypeError from fetch |
| Malformed 2xx JSON body | Validation | Code SyntaxError |
| Unserializable JSON request body | Validation | Code TypeError, nothing sent |
The error code format is Http.{status} (e.g., Http.404, Http.500).
A ProblemDetails body overrides the code (problemDetailsToErrors):
errorsextension: oneAppErrorper entry (list[{ code, description, type? }]or dictionary{ key: string[] }); entries without a validtypeareValidation.errorCodesextension (CSharpEssentials.AspNetCore writes it on every problem): the server's domain codes are kept, in that order. A code with entries inerrorsyields those entries; a code without one yields an error with that code, the status type anddetail(thentitle) as the description.
// 404 body: {"title":"Not Found","status":404,"detail":"No user with id 42.","errorCodes":["User.NotFound"]}
// AppError { code: 'User.NotFound', description: 'No user with id 42.', type: 'NotFound' }
Only when the body has neither does the code fall back to Http.{status}.
httpStatusToError / extractErrorDescription
Exported utility functions for custom HTTP handling:
import { httpStatusToError, extractErrorDescription } from 'tsentials/http';
// Manual status-to-error mapping
const error = httpStatusToError(404, 'User not found');
// AppError { code: 'Http.404', description: 'User not found', type: 'NotFound' }
// Extract error description from a ProblemDetails (RFC 9457) response
const description = await extractErrorDescription(response);
// Reads `detail` or `title` from application/problem+json or application/json body
Best Practices
fetchResultis a const object — usefetchResult.get<T>(url), notfetchResult<T>(url)RequestBuilderterminal method is.send<T>()— not.fetchResult<T>()- Prefer
RequestBuilderover rawfetchResultfor multi-header or multi-param requests - Combine with
fromAsync()to chain downstream calls without nested try/catch - Always type the generic parameter
send<T>()/get<T>()so TypeScript knows the response shape - Works in both Node.js >= 22 (built-in
fetch) and browser environments - POST/PUT/PATCH on
fetchResulttakebodyas the second argument (auto-serialized to JSON)