@inshorts/glint-http
v1.5.3
Published
Glint server-side HTTP client: timeouts, typed errors, redacted curl on failure.
Keywords
Readme
@inshorts/glint-http
Server-side HTTP client for calls between Inshorts services. It is a thin layer
over the platform fetch with no runtime dependencies, and adds:
- Timeouts — every call has one; a hit deadline throws
UpstreamTimeoutError(504). - Readable errors —
message/errorfields are pulled out of upstream bodies, including nested ones ({"message":{"error":"…"}}) and plain-text failures. - A replayable curl for every failure — one log line per failed call, with
credentials redacted (or named as
$ENV_VARso the line still runs), throttled to one per minute per distinct failure. - Error → response mapping —
errorResponse(err)honours any numericstatusthe error carries, so an upstream 404 reaches the browser as a 404.
Extracted from inpix-panel (src/lib/http/), where it backs ~150 call sites.
Server only. These calls usually carry system tokens. Never import this package into browser code.
Install
The package is private to the @inshorts npm org, so the installing machine (and
the Docker build) needs an .npmrc with an org token:
//registry.npmjs.org/:_authToken=${NPM_TOKEN}pnpm add @inshorts/glint-httpRequires Node ≥ 22 (global fetch and Response.json).
Usage
A client per upstream service
import {
createUpstreamClient,
internalHeaders,
requireUpstreamBaseUrl,
} from "@inshorts/glint-http";
export const crmClient = createUpstreamClient({
baseUrl: () => requireUpstreamBaseUrl(process.env.CRM_API_URL, "CRM_API_URL"),
headers: () => ({
...internalHeaders("users-crm"),
"X-AUTH-TOKEN": process.env.CRM_SYSTEM_TOKEN ?? "",
}),
timeoutMs: 10_000, // optional; see "Timeouts"
});
const profiles = await crmClient.request<ProfilesResponse>("/v1/crm/profiles", {
method: "POST",
body: { page: 1, limit: 20 }, // JSON-serialised for you
});baseUrl and headers are functions read on every request, so env values can
change between tests without rebuilding the client.
A non-OK response throws UpstreamError (message, status). Pass makeError to
throw your own class instead:
createUpstreamClient({
baseUrl: () => "…",
makeError: (message, status) => new CampaignError(message, status),
});Lower level: fetchUpstream + parseUpstream
For calls that need the raw Response (streams, non-JSON bodies, multipart):
import { fetchUpstream, parseUpstream } from "@inshorts/glint-http";
const response = await fetchUpstream(url, { method: "GET", headers }, 5_000);
const data = await parseUpstream<Thing>(
response,
(message, status) => new ThingError(message, status),
);fetchUpstream returns the response as-is (it does not throw on 4xx/5xx) but logs
the failure. parseUpstream returns parsed JSON (undefined for 204 / empty), or
throws through your factory with the upstream's own message.
In a route handler
import {
errorResponse,
invalidResponse,
logApiError,
} from "@inshorts/glint-http";
export async function GET(request: Request) {
const tenant = new URL(request.url).searchParams.get("tenant");
if (!tenant) return invalidResponse("tenant is required"); // 400
try {
return Response.json(await crmClient.request(`/v1/thing?tenant=${tenant}`));
} catch (error) {
// Logs status + message + redacted curl (never put curl in the JSON body).
logApiError(error, { service: "inpix-panel", route: "GET /api/thing" });
return errorResponse(error, "Failed to load thing"); // status from the error, else 500
}
}Both return a standard Response, which Next.js route handlers accept directly.
Bodies are { "message": "…" } only — no curl, no stack.
Timeouts
Resolved in this order:
timeoutMson the call (request(path, { timeoutMs })orfetchUpstream's 3rd argument)timeoutMson the client- the
UPSTREAM_TIMEOUT_MSenv var DEFAULT_UPSTREAM_TIMEOUT_MS(15 s)
An AbortSignal you pass in still works; aborting it rejects the call without
logging (a navigation is not a fault).
Failure logs
Single-line JSON on stdout/stderr (Cloud Logging jsonPayload):
{"severity":"ERROR","message":"upstream-failure","event":"upstream-failure","method":"POST","url":"https://core.internal/v1/themes","status":502,"outcome":"502 Bad Gateway","durationMs":812,"curl":"curl -X POST 'https://core.internal/v1/themes' -H 'X-AUTH-TOKEN: $CORE_SYS_TOKEN' -d '{\"tenant\":\"HI\"}'"}Route-level failures use logApiError (event: "api-error") with the same shape
plus service / route. The HTTP response stays { "message": "…" } with the
correct status — curl stays in logs only.
- 5xx, timeouts and refused connections →
console.error(severity: ERROR); 4xx →console.warn(severity: WARNING). - Credential-looking headers (
Authorization,Cookie,*token*,*secret*,*api-key*, …) and body fields (access_token,password, …) never appear. When a header value matches an env var exactly, it is written as$THAT_VAR. - Bodies are truncated at 512 chars; multipart and binary bodies are described, not dumped.
toCurl(request, options) is exported if you want the same line elsewhere.
API
| Export | Purpose |
|---|---|
| createUpstreamClient(config) | JSON client bound to one upstream |
| fetchUpstream(input, init?, timeoutMs?) | fetch + timeout + failure log |
| parseUpstream(response, makeError, fallback?) | JSON on success, typed throw on failure |
| requireUpstreamBaseUrl(value, envName) | Trimmed base URL, or UpstreamConfigError (500) |
| internalHeaders(deviceId) | Content-Type, x-os-type: internal, x-device-id |
| errorResponse(error, fallback?) / invalidResponse(message) | Error → { message } + status |
| logApiError(error, { service, route? }) | Cloud Logging line with curl |
| statusOf / messageOf / curlOf | Read status, message, curl from an error |
| toCurl(request, options?) | Redacted, shell-safe curl line |
| UpstreamError / UpstreamTimeoutError / UpstreamConfigError | Errors with status (+ optional curl) |
| DEFAULT_UPSTREAM_TIMEOUT_MS, resetUpstreamFailureLog() | Constant / test seam |
Development
nvm use 22
npm install
npm run typecheck && npm test && npm run buildPublishing (npm publish) runs all three first via prepublishOnly. Bump
version per semver before publishing.
