How to Rotate JWT Signing Keys Without Downtime
Publish a new key to a JWKS endpoint, accept tokens signed by both keys during overlap, then retire the old key once traffic clears.
Step-by-step guides and in-depth articles to level up your skills.
Page 4 of 9
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.
Write a progress bar to stderr with a carriage return so it updates in place and does not pollute stdout when the output is piped to a file.
Parse a JSON stream incrementally so the UI renders the first items before the full response arrives and the user sees progress not a spinner.
Pipe a multipart upload straight to storage with Node streams so a 2 GB file never sits in memory and the server stays responsive under load.
Add the new credential, switch the app, then remove the old so a password change does not break in-flight connections.
Share one Zod schema between client and server so the validation rules never drift and a change in one place updates both sides.
Capture stdout and stderr in a test, run the command, and snapshot the output so a change to the format is caught in review.
Extract validation logic from the component, test it with plain data, and assert the error shape so UI and logic tests stay separate.
Track type-2 changes with valid-from and valid-to so a dimension row preserves history and a query can point-in-time the join.
Generate a presigned S3 URL so the browser uploads directly to the bucket and your server never proxies the bytes or pays for the bandwidth.
Hold fetch state in a context with a reducer so deep components read loading and error without prop drilling or a global store.
Use Zod array schemas with object elements to validate dynamic lists where each row has its own errors and the UI renders them inline.
Compute a checksum on the source and verify on the destination so a truncated or corrupted transfer is caught before it is committed.
Make a field required only when another field has a specific value using Zod superRefine so the rule lives in the schema not the UI.
Parse and validate config before the app serves so a bad key crashes the boot, not the first request that needs it.
Implement the Luhn checksum to validate credit card numbers client-side, strip spaces, and reject obviously invalid input early.
Define a shared schema for the data a service emits and the consumer expects so a change that breaks the contract is caught in CI.
Write SQL assertions that check invariants and fail the load on violation so a broken batch is stopped before it reaches the report.
Parse, normalize, and compare dates across timezones with a library so a midnight UTC date does not become the wrong day locally.
Store in UTC and convert at the boundary so a query for today returns the same rows regardless of the session timezone.
Cascade the options of a second select from the value of the first, validate the combination, and clear the dependent field on change.
Validate select and radio inputs against an enum so a tampered POST with an out-of-range value is rejected at the boundary, not in the UI.
Sniff the magic bytes and reject if they do not match the claimed type so a renamed executable does not pass as an image.
Check file size, type, and name in the browser before the upload starts so wasted requests never leave the client.
Parse and validate international phone numbers with libphonenumber, handle country codes, and reject malformed input at the boundary.
Parse with libphonenumber, normalize to E.164, and reject invalid so a phone field is a real number not a free-text string.
Check the issuer, audience, expiry, and required claims on every token so a token from the wrong audience or a missing role is rejected at the boundary.
Parse multipart form data with a streaming parser that enforces boundary and part limits so a malformed request cannot exhaust the server.
Compose Zod object schemas to validate deeply nested data and collect every error path so the user sees all problems at once.
Compose AJV custom keywords to validate nested JSON, report every issue at once, and test the error shape your UI renders.
Fetch the discovery keys, verify the signature and claims of the ID token, and extract the user identity so a server trusts the OIDC flow.
Choose when validation fires so blur gives early feedback without blocking typing and submit gives the full check before the request leaves.
Check the Origin header against an allowlist so a cross-site request from a disallowed origin is rejected before it runs.
Score password strength with a rule set for length, character classes, and entropy, show feedback live, and reject weak passwords at submit.
Check that a foreign key exists before accepting a write so a service does not store a reference to a resource another service never had.
Validate every input at the entry point with a schema so the handler receives typed data and never re-checks what the boundary already checked.
Check the Content-Type and the actual bytes server-side so a client lying about the type is rejected before the file is stored or served.
Add field and model validators in Pydantic v2 for rules the types cannot express so validation lives in the schema not the handler.
Validate form fields against the server without blocking typing, debouncing requests and cancelling stale ones with AbortController.
Isolate pools of connections by tenant or feature so one slow tenant cannot exhaust the shared pool and take down everyone.
Open the circuit after failures, probe with one request in half-open, and close only if the probe succeeds so a flapping dependency does not get flooded.
Layer configuration from defaults, file, environment, and flags with explicit precedence so users can override at the right level.
Add color to CLI output only when stdout is a TTY, respecting NO_COLOR and force-color so pipes and logs stay clean.
Show a progress bar for long tasks by writing carriage returns to the same line, and hide it when stdout is not a TTY.
For each step that mutates state, define an inverse that undoes it, so a failed multi-step flow can roll back to a consistent state.
Show and hide form fields based on other field values, keeping hidden fields out of validation and the submitted payload.
Lock down inline scripts with per-request nonces and strict-dynamic so injected scripts without the nonce cannot run, even with DOM bugs.
Store state as a sequence of events and rebuild by replaying, with periodic snapshots so replay does not read the entire history.
Achieve exactly-once semantics by combining at-least-once delivery with idempotent processing keyed by message ID, not true once delivery.
Roll out a feature to a percentage of users with a sticky bucket and a kill switch, so you can ramp up or abort without a deploy.
Serve a reduced experience when a dependency is down by falling back to cached data or a default, never showing an error page for a non-critical feature.
Ensure a tenant token can never access another tenant data by binding the tenant ID into the token and enforcing it at the query layer.
Secure public-client authorization with PKCE by generating a code verifier, sending its challenge, and validating on token exchange.
Detect concurrent modifications with a version number or vector clock, rejecting stale writes so the last writer does not silently clobber earlier work.
Update the UI immediately before the server confirms, rolling back on error so the app feels fast without showing stale data.
Set Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy to isolate your origin from cross-origin documents and enable crossOriginIsolated.
Use signals to make data fetches reactive so dependent computations update automatically when the source changes, without manual subscriptions.
Save form drafts automatically as the user types, debouncing writes, resolving conflicts, and showing a subtle save indicator.
Upload large files resumably with the tus protocol, handling interruptions, PATCH continuation, and upload-creation once per file.
Retry transient failures with exponential backoff plus random jitter and a max attempt cap to avoid thundering herds.
Authorize requests by mapping user roles to permissions with a hierarchy, checking both the role and the specific action before executing.
Coordinate a multi-step transaction across services with compensating actions on failure, so a partial failure does not leave the system inconsistent.
Add a cryptographic hash to external script and style tags so a compromised CDN cannot inject modified code into your page.
Layer per-tenant config on top of the base so one instance serves many tenants with isolated settings, without a config per instance.
Issue short access tokens and rotating refresh tokens, detecting reuse to revoke the whole session on replay.
Require all DOM XSS sinks like innerHTML to receive a TrustedTypes policy, so raw strings cannot reach them even with a bug.
Use opaque cursor pagination instead of offset so inserts and deletes during paging do not skip or duplicate rows.
Set CSP frame-ancestors to none or self so your page cannot be framed by an attacker who overlays invisible buttons on your content.
Use a conditional write that only applies if the current value matches the expected, so a concurrent update cannot be silently lost.
Validate the next parameter against an allowlist before redirecting, so an attacker cannot craft a link that bounces users to a malicious site.
Handle uploads larger than memory by piping the request stream through transforms, never buffering the whole file.
When a downstream service is down, enqueue the work in a durable queue and process it on recovery instead of failing the user request.
Show real upload progress by reading the request body stream, updating a progress bar without XMLHttpRequest.
Encode data on output, not input, and use a context-aware encoder so values inserted into HTML, attributes, or script contexts are all safe.
Strip dangerous HTML from rich-text input using DOMPurify with an allowlist, preventing XSS while preserving safe formatting.
Validate and restrict outbound URLs from user input to prevent server-side request forgery to internal metadata and admin endpoints.
Store JWT in an httpOnly cookie with SameSite=strict and a double-submit token for stateless CSRF defense, not in localStorage.
Choose between httpOnly cookie and in-memory storage for JWTs, understanding the XSS and CSRF tradeoffs of each location.
Deduplicate uploads by their SHA-256 hash, storing each unique blob once and referencing it by digest to save space.
Parse a large JSON stream incrementally as chunks arrive, so the UI can render the first items before the whole response downloads.
Resolve concurrent edits to the same record with last-write-wins per field or a CRDT merge, so collaboration does not silently drop changes.