Writing a typed fetch wrapper in TypeScript against an ASP.NET Core Minimal API: JSON requests, checking response.ok, parsing ProblemDetails and ValidationProblemDetails, timeouts and cancellation with AbortController and AbortSignal, and how the server sees the cancellation.
Wrap fetch once. Send JSON with method, a Content-Type: application/json header and JSON.stringify(body). Remember fetch only rejects on network errors or abort: a 400 or 500 resolves normally, so always check response.ok. On failure, if the content type is application/problem+json, parse the ProblemDetails (title, status, detail, and for validation an errors dictionary keyed by field) and throw a typed error the UI can map to form fields. For cancellation create an AbortController, pass its signal, and call abort() when the component unmounts or a newer search starts; combine with AbortSignal.timeout() for a deadline and ignore AbortError. On the server, ASP.NET Core binds a CancellationToken to RequestAborted, so the database query stops too. The trade-off: a small wrapper is enough; reach for a library only when you need caching and retries.
"
fetchreturns a promise of aResponse, and the first thing I tell people is that it only rejects when the request couldn't complete at all: DNS failure, connection refused, CORS blocked or aborted. A 404 or 500 is a successful fetch withokset to false. So I never sprinkle rawfetchcalls around; I write one small wrapper that sets the JSON headers, checksresponse.ok, handles 204, and turns error responses into a typed error.ASP.NET Core makes the error side easy because it speaks ProblemDetails, RFC 9457. With
AddProblemDetails(), unhandled exceptions and status codes come back asapplication/problem+jsonwithtype,title,status,detailand atraceId, and validation failures, whether from[ApiController],TypedResults.ValidationProblemor the built-in Minimal API validation in .NET 10, include anerrorsobject like{ \"Email\": [\"Email is required.\"] }. My wrapper parses that into anApiErrorwithfieldErrors, so the form can put each message under the right input, and everything else shows a generic message with the trace id for support.For cancellation I use AbortController. In a search box, each keystroke aborts the previous request so slow responses can't overwrite newer results; in React, the effect clean-up aborts when the component unmounts.
AbortSignal.timeout(10_000)gives a deadline, andAbortSignal.anycombines both. The browser closes the request, Kestrel notices, and theCancellationTokenparameter in my endpoint, which isHttpContext.RequestAborted, fires, so EF Core cancels the SQL command. The mistake I see is wrapping fetch in try/catch and assuming the catch handles 500s. It doesn't, and that's how error pages end up renderingundefined."
| Outcome | Promise | response.ok |
What to do |
|---|---|---|---|
| 2xx | Resolves | true |
Parse JSON (unless 204) |
| 4xx / 5xx | Resolves | false |
Parse ProblemDetails, throw ApiError |
| Network down, DNS, CORS blocked | Rejects TypeError |
n/a | Show offline/retry message |
abort() or timeout |
Rejects AbortError / TimeoutError |
n/a | Usually ignore silently |
| Field | Meaning | UI use |
|---|---|---|
status |
HTTP status | Branch on 400/401/403/404/409 |
title |
Short summary | Toast or banner |
detail |
Specific explanation (safe text only) | Banner |
errors |
Field → messages (validation) | Inline field errors |
traceId (extension) |
Correlates with server logs | "Quote this reference" |
A product search fired a request per keystroke; on 4G, responses arrived out of order and users saw results for "ca" after typing "cable". Aborting the previous request and debouncing 250 ms cut API calls by 70% and removed the stale-results bug; server-side, RequestAborted stopped about 40% of SQL queries early during peak.
Checks that the candidate can write correct, robust browser code against their own API, not just happy-path fetches.
Green flags
okerrors to fieldsCancellationTokenRed flags
res.json() blindlyReact component
| apiFetch('/api/products?q=cab', { signal })
v
fetch() -> browser network stack -> (CORS checks if cross-origin)
| |
| Kestrel -> routing -> endpoint(ct = RequestAborted)
| |
|<--------- Response (status, headers, body stream)
v
res.ok ? res.json() : parse problem+json -> throw ApiError
Response arrives as soon as headers do; res.json() then reads the body stream. Aborting during either phase rejects the pending promise.
The Fetch standard models HTTP faithfully: a 500 is still a valid HTTP response. Libraries like axios choose to throw on non-2xx; fetch leaves it to you. Hence the wrapper.
builder.Services.AddProblemDetails() registers IProblemDetailsService.app.UseExceptionHandler() + app.UseStatusCodePages() produce ProblemDetails for exceptions and empty error responses.TypedResults.ValidationProblem(dictionary) returns HttpValidationProblemDetails with errors.builder.Services.AddValidation() validates DataAnnotations on Minimal API parameters and returns a 400 ValidationProblem automatically.Field names in errors follow the property names as serialised (camelCase JSON naming in recent versions), so match them to form field names consistently.
AbortController.abort()
-> browser cancels the HTTP/1.1 connection or sends RST_STREAM (HTTP/2)
-> Kestrel marks the request aborted
-> HttpContext.RequestAborted is cancelled
-> CancellationToken passed to EF Core / HttpClient throws OperationCanceledException
-> ASP.NET Core logs it at a low level, no 500 sent (client is gone)
AbortSignal.timeout(ms) creates a signal that aborts with a TimeoutError; AbortSignal.any([a, b]) aborts when either does. Both are supported in all current evergreen browsers.
Same-origin requests send cookies by default (credentials: 'same-origin'). Cross-origin requests need credentials: 'include' and a CORS policy with AllowCredentials() and an explicit origin.
application/problem+json body in DevTools → Network → Response.await Task.Delay(5000, ct) to an endpoint, abort from the client after 1 s and log ct.IsCancellationRequested on the server.apiFetch with a mocked fetch returning a ValidationProblem.The endpoint and the TypeScript that calls it.
// Program.cs (.NET 10)
using System.ComponentModel.DataAnnotations;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails(); // RFC 9457 responses for errors
builder.Services.AddValidation(); // .NET 10: DataAnnotations on Minimal API parameters
var app = builder.Build();
app.UseExceptionHandler();
app.UseStatusCodePages();
var todos = new List<Todo>();
app.MapGet("/api/todos", async (string? q, CancellationToken ct) =>
{
await Task.Delay(300, ct); // stands in for an EF Core query using ct
return TypedResults.Ok(todos.Where(t => q is null || t.Title.Contains(q, StringComparison.OrdinalIgnoreCase)));
});
app.MapPost("/api/todos", (CreateTodo input) =>
{
var todo = new Todo(todos.Count + 1, input.Title);
todos.Add(todo);
return TypedResults.Created($"/api/todos/{todo.Id}", todo);
});
app.Run();
public sealed record Todo(int Id, string Title);
public sealed record CreateTodo([property: Required, StringLength(100, MinimumLength = 3)] string Title);
// api.ts
export type ProblemDetails = {
type?: string; title?: string; status?: number; detail?: string;
errors?: Record<string, string[]>; traceId?: string;
};
export class ApiError extends Error {
constructor(public status: number, public problem: ProblemDetails | null) {
super(problem?.title ?? `HTTP ${status}`);
}
get fieldErrors(): Record<string, string[]> { return this.problem?.errors ?? {}; }
}
export async function apiFetch<T>(url: string, init: RequestInit & { json?: unknown } = {}): Promise<T> {
const { json, headers, ...rest } = init;
const res = await fetch(url, {
...rest,
headers: { Accept: 'application/json', ...(json !== undefined && { 'Content-Type': 'application/json' }), ...headers },
body: json !== undefined ? JSON.stringify(json) : rest.body,
});
if (!res.ok) { // fetch does NOT throw for 4xx/5xx
const isProblem = res.headers.get('content-type')?.includes('application/problem+json');
throw new ApiError(res.status, isProblem ? ((await res.json()) as ProblemDetails) : null);
}
if (res.status === 204) return undefined as T;
return (await res.json()) as T;
}
// search.ts: abort the previous request on every new search, with a 10 s deadline
let current: AbortController | undefined;
export async function search(q: string) {
current?.abort();
current = new AbortController();
const signal = AbortSignal.any([current.signal, AbortSignal.timeout(10_000)]);
try {
return await apiFetch<{ id: number; title: string }[]>(`/api/todos?q=${encodeURIComponent(q)}`, { signal });
} catch (e) {
if (e instanceof DOMException && e.name === 'AbortError') return null; // superseded: ignore
throw e;
}
}
catch handles HTTP 500s. Why it is wrong: fetch resolves on any HTTP response. Instead: Check response.ok and throw.res.json() on every error. Why it is wrong: Proxies return HTML 502 pages or empty bodies, so parsing throws and hides the real error. Instead: Check Content-Type first.Content-Type: application/json on POST. Why it is wrong: ASP.NET Core returns 415 Unsupported Media Type. Instead: Set it in the wrapper.encodeURIComponent or URLSearchParams.AbortError as a failure to the user. Why it is wrong: It's an intentional cancel. Instead: Ignore aborts explicitly.CancellationToken in the endpoint. Why it is wrong: Server keeps querying for a client that left. Instead: Bind CancellationToken and pass it down.ex.Message in detail. Why it is wrong: Leaks internals. Instead: Generic detail plus a traceId to correlate with logs.The wrapper is the contract enforcement point between frontend and backend: one place for headers, auth, error mapping, telemetry and cancellation. Standardising on ProblemDetails server-side means the frontend writes error handling once. For screens that need caching, deduplication and background refresh, TanStack Query on top of this wrapper beats hand-rolled state.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Thin fetch wrapper | Most apps, few dependencies | You own retries/caching | Heavy caching needs |
| TanStack Query + wrapper | Lists, dashboards, refetching | Library to learn | Simple one-off forms |
| axios | Teams used to interceptors | Extra dependency; fetch now covers most needs | New projects without a reason |
| Generated client (Kiota/NSwag) | Large APIs | Generated code to review | Tiny APIs |
Measure with Application Insights browser telemetry: failed dependency calls by status code, and cancelled requests on the server (OperationCanceledException count) to confirm aborts reach the backend.
I validate input at the edge and business rules in the application or domain layer. For input, DataAnnotations ([Required], [Range], [StringLength]) and IValidatableObject on request DTOs are the baseline. In controllers, binding fills ModelState and [ApiController] returns a 400 ValidationProblemDetails before the action runs. In Minimal APIs on .NET 10, builder.Services.AddValidation() uses a source generator to validate parameters and return the same 400 ProblemDetails; before .NET 10 you needed a filter. FluentValidation is my choice for complex, conditional or async rules; I call it explicitly or from a filter, because its automatic MVC integration is deprecated. Business rules like stock levels or uniqueness are checked where the data lives and returned in the same error shape. The trade-off: attributes are simple and visible in OpenAPI; code-based validators are more expressive.
Cancellation in .NET is cooperative. A CancellationTokenSource owns the decision to cancel; it hands out CancellationTokens that code checks with IsCancellationRequested or ThrowIfCancellationRequested(), or passes to APIs that support it. When cancelled, the convention is to throw OperationCanceledException, which makes the task Canceled. Good APIs accept a CancellationToken as the last parameter (defaulting to default), pass it to every async call they make, and never swallow cancellation. In ASP.NET Core, a CancellationToken parameter is bound to HttpContext.RequestAborted, so client disconnects stop the work.
Retry only idempotent requests: GET and HEAD are safe, PUT and DELETE are idempotent by definition (though a DELETE retry may return 404 the second time, so treat that as success). Retry on network errors, 408, 429 and 502–504, with exponential backoff and jitter, honouring Retry-After. Never blindly retry a POST or PATCH that creates or changes state unless the API supports an idempotency key header, or you risk duplicate orders or payments. Don't retry 4xx validation or auth errors. Cap attempts at 2–3 so a struggling backend isn't hammered.
Last updated 23 Nov 2026.