How to Fetch with Timeout and Cancellation
Wrap fetch in an AbortController with a timeout so a hanging request is cancelled and the caller gets a predictable error not an infinite wait.
Step-by-step guides and in-depth articles to level up your skills.
Page 3 of 9
Wrap fetch in an AbortController with a timeout so a hanging request is cancelled and the caller gets a predictable error not an infinite wait.
Follow redirects up to a cap, reject cross-origin redirects without consent, and never forward the Authorization header to a different host.
Fill missing rows in a time series with the last seen value so a gap from a dropped sample does not break a downstream average.
Emit a bash, zsh, or fish completion script from the command tree so tab completion works and the user does not memorize flags.
Run a sharp or Pillow pipeline to generate thumbnails the moment an image upload completes so the UI has previews without a separate job.
Stop accepting new requests on SIGTERM, let in-flight work finish, and exit so a deploy does not drop the requests in progress.
Put a timeout on every remote call so a slow dependency fails fast and the caller stays responsive instead of piling up waiting threads.
Catch SIGINT and SIGTERM, stop accepting new work, finish in-flight tasks, and exit so a Ctrl-C does not leave a half-written file.
Run independent tasks in parallel with a bounded pool so a CLI that processes N files finishes in N divided by pool time not N time.
Queue uploads behind a bounded concurrency limit so ten files do not open ten connections and saturate the user is bandwidth or the server.
Validate each step of a wizard form independently, preserve state between steps, and block navigation on invalid input.
Decide whether a new column is nullable, backfill it, and add the not-null constraint so the migration does not break existing queries.
Process a batch item by item, collect successes and failures, and report which failed so a partial failure does not roll back the whole batch.
Queue mutations made offline, replay them on reconnect, and merge conflicts with a last-write-wins or CRDT strategy so the user keeps working.
Detect a broken upload by missing chunks or a short content length, resume from the last byte, and never make the user restart from zero.
Tag each fetch with a sequence number and ignore the response of an older fetch so a slow request never overwrites a newer one.
Watch the config file, validate the new value, and swap atomically so a config change takes effect without a deploy or a dropped request.
Give each dependency a bounded thread or connection pool so one slow dependency cannot consume the resources of the whole service.
Use a counting semaphore to limit concurrent access to a resource so the resource stays under its capacity and callers queue.
Wrap an external call in a time limiter that cancels or fires a fallback so a hung dependency does not hold a thread forever.
Add full jitter to backoff across clients so a recovering server is not hit by a synchronized wave of retries from the whole fleet.
Signal the producer to slow down when the consumer falls behind so a fast stream does not overflow a slow UI or a constrained queue.
Assign each dependency a dedicated thread pool so a slow dependency blocks its own pool, not the pool the critical path runs on.
Read the WAL or binlog and emit change events in order so downstream consumers see every change exactly once without a full table scan.
Check the latest version from npm in the background and print a one-line upgrade hint so the user knows a new release exists without a forced update.
Version the config schema and migrate old configs so a new field does not break a deployment running the previous version.
Yield to the event loop between chunks of CPU work with setImmediate so a long computation does not starve I/O callbacks.
Generate a per-request nonce, allow scripts with that nonce, and use strict-dynamic so inline scripts work without unsafe-inline.
Use an idempotency key so a retry after a timeout does not double-charge or double-insert, and the server deduplicates by the key.
Render only the visible window of a long list with a virtualizer so scrolling through ten thousand items does not mount ten thousand nodes.
Check permissions at the moment of the action, not at login, so a role change takes effect immediately and stale grants cannot persist.
Issue client certs to each service and verify the peer cert on the server so only known services can call each other.
Cache the 404 result with a short TTL so repeated lookups for a missing resource do not hit the origin every time.
Apply the update to the UI immediately, send the request in the background, and roll back to the previous state if the server rejects it.
Carry roles in a JWT claim and check them in a guard so an endpoint declares its required role and the middleware enforces it in one place.
Open an SSE connection for one-way live updates so the server pushes events without the overhead of WebSockets or the polling of fetch.
Run concurrent tasks in a scope that cancels all on first failure so a partial result is not left running after the caller gives up.
Layer tenant-specific config over the base so one tenant can override a limit without forking the whole config for the rest.
Generate a TOTP secret, verify the six-digit code with a time window, and rate-limit attempts so brute force on the second factor is impractical.
Mount secrets as files or env at container start so the image is reproducible and a secret change does not require a rebuild.
Invalidate by query key after a mutation so the cache refetches only the affected queries and the UI stays consistent with the server.
Carry the tenant ID in a claim and scope every query and check to it so a token from tenant A can never read tenant B data.
Keep access tokens to minutes not hours, issue a refresh token for the session, and rotate the pair so a leaked access token expires fast.
Read env vars with type coercion and fall back to defaults so a missing var uses the default and a wrong type fails fast.
Merge config from defaults, file, env, and flags in a fixed order so the precedence is explicit and a later source overrides an earlier one.
Track in-flight uploads per user ID and reject new ones over a per-user cap so one user cannot monopolize the upload pipeline.
Map validation error codes to translated strings so the form shows the right language without changing the schema or the logic.
Pull secrets from Vault or Secrets Manager at startup so secrets never live in the image or the repo and rotation is a store operation.
Collect requests in a microtask and send them as one batch so N calls to the same endpoint become one round trip to the server.
Use expand-then-contract so a field is added, consumers update, and the old field is removed only after all consumers have migrated.
Move a CPU-bound task to a worker thread or a child process so the event loop stays free for I/O and the task runs on another core.
Define the order: defaults, config file, env, flags, and merge so the user can override at the level they need without confusion.
Add a --json flag that prints machine-readable output to stdout so the CLI composes with jq and scripts without parsing text.
Use a cursor over a unique, stable sort key so pagination does not skip or repeat rows when new data arrives between page fetches.
Use Commander to define subcommands with their own options so a CLI grows by adding a command, not a new if-else branch in a main.
Read env vars with type coercion and fall back to defaults so a CLI works with a config file or a twelve-factor deployment.
Prefetch the next likely route data on hover or idle so the click lands on a page that is already loaded and the navigation feels instant.
Return the same message and timing for a wrong username and a wrong password so an attacker cannot tell which part failed by the response.
Check that the user owns the resource on every request so an IDOR where a user swaps an ID is rejected at the handler.
Validate the config against a schema on every change so a typo in a key is caught by the schema, not by a runtime undefined.
Scope private packages and pin registries so a public package with the same name as an internal one is not installed by mistake.
Disable the submit button and track in-flight state so an impatient user clicking twice never sends two requests to the server.
Pass data as context, never as part of the template string, so a user value cannot become a directive the engine executes.
Validate the redirect URI against a registered list so a login does not bounce the user to an attacker-controlled site with a code in the URL.
Resolve the path and check it stays under the allowed root so a request for dot-dot-slash does not escape the sandbox.
Use a safe merge that skips __proto__ and constructor keys so a crafted JSON does not pollute Object.prototype across the app.
Resolve the URL, reject internal IPs and localhost, and fetch only allowed hosts so a user URL cannot reach the metadata endpoint.
Apply backpressure in a Node stream pipeline so a slow consumer signals the producer to pause and memory stays bounded under bursty traffic.
Append events to a log table and project to a read model so the state is rebuilt from the log and the history is preserved.
Send the remaining deadline on each call so a downstream knows how long it has and does not start work it cannot finish in time.
Let the client ask for only the fields it renders so a list view does not download the full detail payload and the bytes stay on the wire.
Keep fetched data in a stable reference, split selectors so only the component that needs the slice re-renders, and avoid inline objects in render.
Rehash on next login with the new algorithm and store the result so users are migrated transparently without a forced password reset.
Reject new work when the queue is full so the system stays responsive for the work it has instead of collapsing under all of it.
Use a load ID and a checksum so re-running a load for the same partition skips or overwrites safely without duplicating rows.
Use a fetch ReadableStream or XHR progress event to report byte-level upload progress to the UI so the user sees the bar move, not a spinner.
Reset a form to initial values while preserving unsaved drafts in a separate buffer so a misclick does not destroy the user is work.
Use the tus protocol to resume an upload that broke mid-stream so a flaky connection does not force the user to start over from byte zero.
Detect a deadlock from the error code, retry the transaction with a new snapshot, and give up after a cap so progress is made.
Register a passkey with the authenticator and verify assertion challenges so a user logs in with a device credential instead of a password.
Publish a new key to a JWKS endpoint, accept tokens signed by both keys during overlap, then retire the old key once traffic clears.
Support two valid secrets during overlap, switch readers to the new one, then retire the old so rotation is transparent to the service.
Issue a new refresh token on each use, denylist the old one, and detect replay when a retired token appears so theft is visible.
Pass user HTML through DOMPurify with an allowlist so script tags and event handlers are stripped before the HTML reaches the DOM.
Strip dangerous HTML from rich text input with DOMPurify before running schema validation so the validator sees clean data.
Copy a template tree, substitute variables, and run hooks so a CLI turns a one-line command into a configured project in seconds.
Run a secret scanner on every push so a key committed by accident is caught before the build, not after it ships.
Run uploaded content through a pattern matcher for shellcode and polyglot files so a file that is valid PDF and valid EXE is caught.
Pipe uploaded files to ClamAV in a background task so the user does not wait on the scan and infected files are quarantined after detection.
Sign download URLs with an expiry so a shared link stops working after a window and the storage backend rejects expired tokens.
Check authorization on every resolver field so a query for another user data is rejected at the field, not at the query root.
Use a double-submit cookie so a cross-site request lacks the cookie-bound token and the server rejects it before the JWT is ever checked.
Use a constant-time comparison for the reset token and a generic message whether the email exists so leaks are closed.
Serve public keys from a JWKS endpoint, cache them with a TTL, and refetch on kid miss so rotation is transparent to resource servers.
Render a bar with ETA and rate to stderr so the user sees the task is moving and the output stays clean when piped.
Render a linked, aria-live error summary that lists every invalid field so screen reader users hear what to fix and can jump to it.
Measure the event loop lag and alert when it crosses a threshold so a blocking operation is found before it causes a timeout cascade.
Allowlist the fields a request can set so a user cannot send role=admin in the body and overwrite a field they should not touch.
Choose between httpOnly cookies and in-memory storage by the threat model, never localStorage for sensitive tokens, and defend against XSS and CSRF.
Name stored files by their SHA-256 hash so duplicate uploads deduplicate for free and the cache key is the content itself.