Developer Cookbook
“How would you do X?” — practical, production-ready recipes with the approach, full code, pitfalls and variations.
AI & LLM APIs
All AI & LLM APIs recipes →- Answer with citations that point at the source textShow users exactly which sentence in which document supports each part of the answer.
- Build hybrid RAG search on PostgreSQL with pgvectorAnswer questions from your documents using the database you already run, with good results for identifiers too.
- Cache a long system prompt and documentsStop paying full price for the same long instructions and reference documents on every request.
- Cache answers to frequent questions safelyServe the most common questions instantly and cheaply without serving stale or personal answers.
- Classify thousands of items with the Batch APIRun large, non-urgent jobs (tagging tickets, summarising documents) cheaper and without hitting rate limits.
- Compare two prompt versions with an unbiased model judgeDecide whether a new prompt is better without position bias deciding for you.
- Expose an internal API as an MCP serverMake an internal system (tickets, inventory) available to every MCP-capable AI app once, instead of per app.
- Extract structured data with a schemaTurn free-text emails or documents into validated objects your code can store.
- Fit conversation history into a token budgetLong chats eventually exceed the context window or cost too much; trim history before sending.
- Handle rate limits, overload and timeoutsKeep a feature working when the API returns 429 or 529 errors or responds slowly.
- Handle untrusted documents and emails safelySummarise or answer from content written by others without letting it instruct your model.
- Redact personal data before prompts and logsKeep card numbers, emails and keys out of model requests, logs and traces, and restore them where needed.
- Route easy requests to a smaller modelCut cost and latency by sending simple requests to a small model and hard ones to a large model.
- Run an eval set with pytestCheck a prompt change against real cases automatically before it ships.
- Store and trim chat history in a databaseKeep multi-turn conversations across requests and servers without sending ever-growing histories.
- Stream model answers to the browser with SSEShow the answer as it is generated instead of making users wait several seconds for the full reply.
- Trace LLM calls with OpenTelemetrySee every model and tool call with tokens, latency and errors in your existing tracing system.
- Track token usage and cost per feature and customerKnow which features and customers drive the AI bill, and catch runaway usage early.
- Use MCP server tools from your own appConnect to an MCP server, offer its tools to the model, and run the calls the model makes.
- Write a bounded tool-calling loopLet the model call your functions to answer, without infinite loops, crashes or invented results.
ASP.NET Core
All ASP.NET Core recipes →- Accept file uploads with size and type limitsUploads can fill the disk, overwrite files or carry the wrong content.
- Add OpenTelemetry traces and metricsLatency spikes and errors can't be traced across services and dependencies.
- Apply EF Core migrations safely during deploymentCalling Database.Migrate() at startup races between instances and needs schema permissions in the app.
- Bind and validate options at startupA missing or invalid setting only shows up when the code path runs in production.
- Cache responses with output caching and evict by tagPopular GET endpoints hit the database on every request, and cached data must refresh after edits.
- Call external APIs with typed HttpClients and resilienceOutbound calls exhaust sockets, have no timeouts, and fail on transient errors.
- Configure CORS for a browser front endThe SPA on another origin can't call the API, and someone suggests allowing every origin.
- Expose liveness and readiness health checksOrchestrators restart healthy pods or route traffic to instances whose database is down.
- Generate OpenAPI documents with Microsoft.AspNetCore.OpenApiAPI consumers need an accurate, up-to-date contract with auth requirements and examples.
- Handle concurrent updates with concurrency tokensTwo admins edit the same record and the second save silently overwrites the first.
- Map exceptions to ProblemDetails with IExceptionHandlerUnhandled exceptions leak stack traces, and domain errors all become 500s.
- Organize minimal API endpoints into groupsProgram.cs grows into hundreds of lines of endpoints with repeated prefixes, auth and tags.
- Protect APIs with JWT bearer tokens and policiesThe API must accept access tokens from an identity provider and enforce scopes and roles.
- Publish a container image without a DockerfileMaintaining Dockerfiles for many services is repetitive, and images run as root.
- Rate limit per user and per IPA single client can exhaust the API, and login endpoints are brute-forced.
- Run periodic background work with scoped servicesA background job needs the DbContext (scoped) and must stop cleanly on shutdown.
- Speed up EF Core reads with projections, no-tracking and poolingList endpoints load whole entity graphs, track them for no reason and run slowly under load.
- Stream updates to browsers with Server-Sent EventsThe UI polls every second for order status updates.
- Validate minimal API input with AddValidationHandlers start with lines of manual `if` checks and return inconsistent error formats.
- Write integration tests with WebApplicationFactoryUnit tests pass but routing, auth, validation and serialization bugs reach production.
Django
All Django recipes →- Add a required column without downtimeAdding a NOT NULL column (or renaming one) locks the table or breaks the running version during deploys.
- Add full-text search with PostgreSQLSearching with icontains is slow and returns poorly ranked results.
- Add health checks and structured loggingLoad balancers can't tell if the app is ready, and logs are unstructured text that's hard to search.
- Avoid N+1 queries with select_related and prefetch_relatedA list page runs one query per row because templates or serializers follow relationships.
- Cache expensive queries and invalidate on changeA dashboard query takes seconds, but caching it shows stale data after edits.
- Call external APIs concurrently in async viewsA view calls three slow services one after another, so the response takes the sum of their times.
- Configure settings from environment variablesKeep secrets and per-environment values out of settings.py and fail fast when something required is missing.
- Enforce rules with database constraintsValidation in forms and serializers isn't enough: scripts, imports and race conditions still create bad data.
- Harden security settings, including a Content Security PolicyThe app passes development checks but ships without HTTPS enforcement, secure cookies or a CSP.
- Import and update many rows efficientlySaving thousands of rows one by one takes minutes and floods the database with queries.
- Paginate and filter large API listsOffset pagination gets slow and inconsistent on large, frequently changing tables.
- Rate limit API endpoints in DRFLogin and expensive endpoints get hammered by scripts.
- Restrict API objects to their owners in DRFUsers can read or change other users' records by guessing IDs.
- Run background work with Django's tasks frameworkSending emails or generating reports inside requests makes them slow and fragile.
- Start a project with a custom user modelUse email as the login field and keep room to add profile fields later without a painful migration.
- Test views and APIs with pytest-djangoTests are slow, depend on each other, and don't catch query regressions.
- Update stock safely with transactions, F() and select_for_updateTwo customers buy the last item at the same time and both orders succeed.
- Validate uploads and store them in object storageUsers upload files that are too large, the wrong type, or end up on the web server's disk.
- Write an idempotent management commandOperational scripts (cleanups, backfills) are run ad hoc from shells and behave differently each time.
- Write a reversible data migrationA new column needs values computed from existing data, deployed safely with the schema change.
Docker
All Docker recipes →- Add a healthcheck to an HTTP serviceLet Docker and Compose know when a container is actually ready and when it has become unhealthy.
- Build a layered image for a Spring Boot appPackage a Java service so dependency layers are cached and only your classes change on rebuild.
- Build a production image for a Node.js servicePackage a Node.js or TypeScript service with only production dependencies and a non-root user.
- Build a production image for a Python web appPackage a Python API (FastAPI, Flask, Django) in a small, cache-friendly, non-root image.
- Build, cache and push images in GitHub ActionsBuild images in CI with layer caching and push them with immutable tags.
- Build one image tag for amd64 and arm64Run the same image on x86 servers, ARM servers and Apple Silicon laptops.
- Configure nginx from environment variablesUse one nginx image across environments with different upstream URLs and server names.
- Develop with Compose and live reloadEdit code on the host and see changes in the running container without rebuilding.
- Make containers cope with dependencies that start slowlyThe app crashes when the database isn't ready yet, in Compose and after database restarts.
- Run containers as non-root with a read-only filesystemReduce what a compromised container can do without breaking the app.
- Run PostgreSQL in Compose with a healthcheck and persistent dataStart a database for development that keeps data and that the app waits for.
- Scan images for vulnerabilities in CIFind known CVEs in base images and dependencies before images reach production.
- Serve a single-page app from a small imageBuild a React or Vue app and serve it with correct routing fallback and caching headers.
- Ship a Go service in a tiny distroless imageCompile a static Go binary and run it in an image with no shell or package manager.
- Shrink a bloated imageAn image is over 1 GB; make it smaller without breaking it.
- Speed up builds with BuildKit cache mountsStop re-downloading packages on every build when only one dependency changed.
- Start optional tools only when needed with Compose profilesKeep admin UIs, mail catchers and debug tools out of the default stack but one flag away.
- Stop container logs from filling the diskA chatty container filled the host disk with log files; configure rotation for every container.
- Use private package credentials in a build without leaking themInstall from a private npm, PyPI or Maven registry during the build without the token ending up in the image.
- Write an entrypoint script that handles signalsRun setup steps before the app without breaking graceful shutdown.
FastAPI
All FastAPI recipes →- Add liveness and readiness endpoints to FastAPITell Kubernetes or a load balancer when an instance is alive and ready to receive traffic.
- Add OpenTelemetry tracing to FastAPISee where time goes in a request across your API, database and outbound HTTP calls.
- Add request IDs and structured logs to FastAPICorrelate every log line from one request and return the ID to clients for support.
- Build a WebSocket chat endpoint in FastAPIBroadcast messages to all users in a room in real time, across multiple app instances.
- Cache FastAPI responses in RedisSpeed up an expensive read endpoint and invalidate the cache when data changes.
- Call external APIs with retries and timeouts from FastAPIIntegrate a flaky third-party API without blocking workers or hammering it during outages.
- Implement role-based access control in FastAPIRestrict endpoints by permission and make sure users only access their own resources.
- Isolate tenants in a multi-tenant FastAPI appServe many customer organizations from one database without any data leaking between them.
- Paginate with cursors in FastAPIReturn large result sets page by page, fast and stable even while new rows are inserted.
- Rate limit FastAPI endpoints with RedisLimit login attempts and API usage per user or IP across multiple workers and instances.
- Return RFC 9457 Problem Details from FastAPIMake every error response — validation, not found, conflicts, crashes — use one consistent JSON shape.
- Run background jobs from FastAPI with ARQGenerate reports and send emails asynchronously with retries, outside the request.
- Run scheduled tasks alongside FastAPIRun a cleanup every hour and a report every night without duplicating work across replicas.
- Stream responses with Server-Sent EventsStream progress updates or LLM tokens to the browser as they're produced.
- Support Idempotency-Key headers in FastAPILet clients retry POST requests (like creating payments) safely without duplicate side effects.
- Test FastAPI endpoints against a real databaseWrite fast, isolated API tests that hit PostgreSQL but leave no data behind.
- Upload files directly to S3 from a FastAPI appLet clients upload large files without streaming them through your API servers.
- Use refresh tokens in HttpOnly cookies with FastAPIKeep users signed in for weeks while access tokens stay short-lived and safe from XSS.
- Verify incoming webhooks in FastAPIAccept webhooks from a payment provider securely and process each event exactly once.
- Version a FastAPI API without breaking clientsIntroduce breaking changes (renamed fields, new semantics) while existing clients keep working.
- Benchmark code with testing.B.LoopYou want to know whether an optimisation helps and how many allocations it makes.
- Build a small, secure container image for a Go serviceGo images are large, run as root and include build tools.
- Decode and validate JSON request bodies safelyHandlers accept huge bodies, unknown fields and invalid values without complaint.
- Embed static files and templates in the binaryDeployments break because templates or assets aren't copied next to the binary.
- Load and validate configuration from environment variablesConfiguration is read ad hoc with os.Getenv all over the code, and typos are discovered in production.
- Log structured JSON with slog and redact secretsLogs are unstructured strings, and tokens or passwords end up in them.
- Process jobs concurrently with a bounded worker poolSpawning a goroutine per item overwhelms dependencies; processing sequentially is too slow.
- Profile a running service with pprofCPU or memory usage climbs in production and you need to see where.
- Rate limit requests per clientOne client sends bursts that degrade the service for everyone.
- Retry operations with exponential backoff and jitterTemporary failures (timeouts, 503s) fail requests that would succeed a moment later.
- Route HTTP requests with the standard library ServeMuxYou want method-based routes and path parameters without adding a router dependency.
- Run database transactions with database/sqlMulti-step writes leave partial data when one step fails, and connections leak.
- Shut down an HTTP server gracefullyDeploys kill the process mid-request, dropping connections and losing work.
- Stream results with range-over-func iteratorsPaginated APIs or database rows are loaded fully into memory before processing.
- Test HTTP handlers with httptestHandler tests start real servers on ports or skip routing and middleware.
- Use context deadlines for outbound callsA slow dependency makes requests pile up because calls never time out.
- Wrap, inspect and expose errors properlyErrors lose context as they bubble up, and handlers can't tell 'not found' from a database outage.
- Write HTTP middleware for logging, recovery and request IDsEvery handler repeats logging and panics crash the request without a useful log.
- Write small generic helpers with slices and mapsThe same filter, map and group-by loops are rewritten for every type.
- Write table-driven tests with subtestsTests for a function with many cases are long, repetitive and stop at the first failure.
Kubernetes
All Kubernetes recipes →- Autoscale a Deployment on CPU and memoryAdd and remove replicas automatically as load changes, without flapping.
- Debug a distroless pod with an ephemeral containerThe pod has no shell or tools; inspect it without changing the image.
- Default-deny network policies that keep DNS workingLock down pod traffic in a namespace without breaking name resolution.
- Enforce the restricted Pod Security StandardStop anyone from deploying privileged or root containers into application namespaces.
- Expose a service over HTTPS with automatic certificatesServe an app on a domain with TLS certificates that renew themselves.
- Give a CI pipeline least-privilege deploy accessCI deploys with cluster-admin; restrict it to one namespace and the resources it manages.
- Handle SIGTERM in your application for KubernetesPods drop in-flight requests or jobs when they're terminated.
- Manage dev, staging and prod with Kustomize overlaysCopies of manifests per environment drift apart.
- Restart pods automatically when configuration changesEdited ConfigMaps don't reach running pods; make configuration changes roll out like code.
- Right-size requests with VPA recommendationsRequests were guessed at launch; find better values from real usage without risking restarts.
- Roll out without dropping requestsDeploys and scale-downs cause a burst of 502 errors.
- Run a stateful service with stable identitiesPods of a clustered system need stable names and their own storage.
- Run database migrations as a Job before the new versionMigrations race with new pods, or run once per replica from the entrypoint.
- Run scheduled jobs reliably with CronJobsNightly jobs sometimes run twice, overlap, or silently stop running.
- Send a percentage of traffic to a new version with the Gateway APIRelease a new version to 10% of users first, then increase.
- Set namespace quotas and default resourcesTeams deploy pods without requests, and one namespace can consume the whole cluster.
- Survive node drains and zone outagesNode upgrades or a zone failure take all replicas of a service down at once.
- Sync secrets from a cloud secret managerKeep secret values out of Git while workloads still get Kubernetes Secrets.
- Wait for dependencies at startup without init container hacksPods crash-loop while a database or another service is still starting.
- Write a production-ready DeploymentStart new services from a Deployment that has the probes, resources and security settings production needs.
Laravel
All Laravel recipes →- Authorize actions with policiesPermission checks are scattered across controllers and views and drift apart.
- Cache expensive data with stale-while-revalidateCache expiry causes a stampede of slow recomputations at the same moment.
- Call external APIs with timeouts, retries and fakesCalls to a partner API hang, fail on temporary errors, and make tests depend on the network.
- Catch N+1 queries with strict Eloquent modePages slow down as data grows because relations are lazy loaded in loops.
- Delete old records automatically with prunable modelsTables of logs, sessions and soft-deleted rows grow forever.
- Dispatch events and listeners after the transaction commitsListeners send emails or sync data for records that are then rolled back.
- Issue scoped API tokens with SanctumIntegrations need long-lived API access with limited permissions that can be revoked.
- Make queued jobs reliable with retries, backoff and uniquenessJobs fail on temporary errors, run twice for the same record, or hang forever.
- Prevent race conditions with transactions and row locksTwo requests redeem the same voucher or oversell the same stock.
- Rate limit routes per user and per IPLogin and public APIs are abused by scripts, and one heavy user slows everyone down.
- Respect third-party API rate limits in queued jobsA burst of jobs hits a partner API's rate limit and most of them fail.
- Reuse query logic with local scopesThe same where-clauses are copied across controllers and drift apart.
- Schedule tasks safely on multiple serversCron jobs run on every server, overlap with themselves, and fail silently.
- Send queued notifications over several channelsEmails slow down requests and users want some messages by Slack or SMS instead.
- Shape JSON responses with API ResourcesReturning models directly leaks columns and makes response formats drift.
- Use backed enums and casts on modelsStatuses are free-form strings with typos, and money or JSON columns need manual conversion.
- Validate requests with Form RequestsControllers fill up with validation and authorization code, and rules differ between create and update.
- Validate uploads and serve private files with temporary URLsUploads land on local disks, accept any file type, and private files are publicly accessible.
- Verify incoming webhook signaturesAnyone can POST fake events to the webhook endpoint.
- Write feature tests with fakesTests hit real queues and mail servers, or only test happy paths.
Next.js
All Next.js recipes →- Add a Content Security Policy with nonces in Next.jsMitigate XSS by allowing only scripts that Next.js itself renders.
- Add dark mode to Next.js without a flashSupport system/light/dark themes in a server-rendered Next.js app without hydration warnings or flashes.
- Add SEO metadata, Open Graph and sitemapsGive every page correct titles, descriptions, social previews and a sitemap for search engines.
- Avoid data-fetching waterfalls in Server ComponentsA dashboard page is slow because it awaits user, stats and notifications one after another.
- Build a validated JSON API with Route HandlersExpose a REST endpoint from a Next.js app for a mobile client, with auth and input validation.
- Create encrypted session cookies in Next.jsImplement login sessions without a session store, using a signed/encrypted cookie readable only on the server.
- Handle errors and 404s in the App RouterShow friendly error pages per section, recover with a retry, and return real 404s for missing records.
- Handle forms with Server Actions and validationCreate a contact form that validates on the server, shows field errors, and works without client-side JavaScript.
- Keep secrets and server code out of the client bundleMake sure API keys and database code never ship to the browser in a Next.js app.
- Optimistic UI with Server ActionsMake liking a post or adding a comment feel instant while the Server Action runs.
- Optimize images with next/imageServe responsive, lazy-loaded images in modern formats without layout shift, including from a CMS.
- Paginate and filter with searchParams in Server ComponentsBuild a searchable, paginated product list rendered on the server and shareable via URL.
- Pre-render dynamic pages with generateStaticParams and ISRServe thousands of blog/product pages as static HTML that refreshes periodically.
- Protect routes in the Next.js App RouterRedirect signed-out users away from /dashboard and make sure server code never serves private data to them.
- Rate limit Route Handlers and Server ActionsProtect login, signup and AI endpoints from abuse in a serverless deployment.
- Receive Stripe webhooks in a Next.js Route HandlerProcess payment events securely in a Next.js app deployed to serverless.
- Revalidate cached data with tags after a mutationShow fresh product data right after an admin edits it, while keeping pages fast and cached.
- Stream slow sections with SuspenseRender the page shell instantly while slow data (recommendations, analytics) loads.
- Test a Next.js app with Vitest and PlaywrightSet up fast component tests and a few end-to-end tests for critical flows in a Next.js project.
- Upload files with a Server ActionLet users upload an avatar through a form that works even before JavaScript loads.
Node.js
All Node.js recipes →- Add health and readiness endpoints to a Node.js serviceLet Kubernetes restart stuck processes and route traffic only to instances that can serve it.
- Add JWT authentication to an Express APIProtect Express routes with bearer tokens and expose the authenticated user to handlers.
- Cache expensive lookups in Redis from Node.jsReduce database load for a hot endpoint while avoiding stampedes when entries expire.
- Call external APIs with timeouts and retries in Node.jsMake outbound HTTP calls that never hang and recover from transient failures.
- Centralize error handling in Express 5Return consistent error responses and never leak stack traces, including for async handler failures.
- Hash passwords and implement login safely in Node.jsStore user passwords securely and build a login endpoint resistant to brute force and enumeration.
- Implement cursor pagination with PostgreSQL in Node.jsPaginate an activity feed efficiently with node-postgres, without OFFSET.
- Offload CPU-heavy work with worker threadsKeep an Express API responsive while generating PDFs or hashing large files.
- Process background jobs with BullMQSend emails and generate thumbnails outside the request cycle with retries and concurrency control.
- Rate limit an Express API across instancesThrottle login attempts and API calls per client, shared across all Node processes.
- Run database transactions correctly with node-postgresTransfer money between accounts atomically and avoid leaking pooled connections.
- Scale real-time Socket.IO across instancesBroadcast chat messages to rooms when users are connected to different Node instances.
- Shut down a Node.js server gracefullyDeploy without dropping in-flight requests or leaving database connections and jobs half-done.
- Stream a large CSV export in Node.jsExport millions of database rows as CSV without loading them into memory.
- Structured logging with request IDs in Node.jsProduce fast JSON logs where every line from a request carries the same request ID.
- Test an Express API with node:test and supertestWrite fast API tests without a separate test framework, including auth and validation cases.
- Upload files to S3 with presigned URLs from Node.jsLet clients upload large files directly to S3 while the API controls keys, types and sizes.
- Validate environment configuration at startupFail fast with a clear message when an env variable is missing or malformed, and get typed config.
- Validate Express requests with ZodReject invalid bodies and query strings with clear 422 errors and get typed data in handlers.
- Verify webhook signatures in ExpressAccept signed webhooks safely: verify the raw body, prevent replays and drop duplicates.
- Add CSRF protection to PHP formsPrevent cross-site request forgery on session-authenticated forms without a framework.
- Add health check endpoints to a PHP appLet load balancers and Kubernetes know whether a PHP instance is alive and ready for traffic.
- Add structured logging with request IDs in PHPMake PHP logs searchable and correlate all log lines from one request.
- Build a secure password reset flow in PHPLet users reset forgotten passwords without enabling account takeover or email enumeration.
- Cache expensive queries with Redis in PHPSpeed up a slow product listing query with Redis while keeping data reasonably fresh.
- Call external APIs with timeouts and retries in PHPCall a flaky third-party API without hanging PHP-FPM workers or amplifying outages.
- Handle file uploads securely in PHPAccept user image uploads safely: validate type and size, avoid executable files, and store them outside the web root.
- Implement rate limiting in a PHP APILimit each client to N requests per minute across multiple PHP-FPM servers and return 429 with Retry-After.
- Make a PHP payment endpoint idempotentPrevent double charges when clients retry a POST /payments request after a timeout.
- Paginate large tables with cursors in PHPList orders efficiently in an API without slow OFFSET queries on large tables.
- Prevent XSS in PHP templatesRender user-generated content (names, comments, links) safely in HTML pages.
- Protect a PHP API with JWT bearer tokensValidate JWT access tokens on every API request and expose the authenticated user to controllers.
- Receive and verify webhooks in PHPProcess payment provider webhooks safely: verify signatures, avoid duplicates and respond quickly.
- Retry deadlocked transactions in PHPHandle deadlocks and serialization failures gracefully in high-concurrency write paths.
- Run scheduled jobs (cron) reliably in PHPRun nightly reports and cleanups without overlapping runs or silent failures.
- Send emails asynchronously with a queue in PHPSend welcome and receipt emails without slowing down requests or losing them when the mail provider is down.
- Set up a PHP dev environment with Docker ComposeGive every developer the same PHP, database and Redis versions with one command.
- Test database code in PHP with transactionsWrite fast, isolated PHPUnit tests for repository code against a real database.
- Validate JSON API input in PHPValidate and normalize a JSON request body, returning all errors in a consistent 422 response.
- Wire a PHP app with a DI containerStop creating dependencies with `new` all over the code and make classes testable.
React
All React recipes →- Add optimistic updates to a todo listMake toggling and deleting items feel instant while staying correct if the server request fails.
- Build an accessible modal dialogShow a confirmation dialog that traps focus, closes with Escape and restores focus afterwards.
- Build infinite scroll with TanStack QueryLoad more items automatically as the user scrolls a long feed, using cursor pagination.
- Call a cookie-authenticated API with CSRF protectionYour SPA uses session cookies; send the CSRF token required by the backend on every mutating request.
- Debounce a search input in ReactSearch an API as the user types without firing a request on every keystroke or showing stale results.
- Handle errors gracefully with error boundariesShow a friendly fallback with a retry button when part of the UI crashes or fails to load data.
- Implement dark mode that follows the systemSupport light/dark themes with a manual override, persisted, and without a flash of the wrong theme.
- Poll a long-running job's statusShow progress for a report generation job until it finishes, then stop polling.
- Protect routes in a React SPAShow some pages only to signed-in users (and some only to admins), redirecting others to login and back.
- Refresh expired access tokens automaticallyRetry API calls transparently when the access token expires, without firing multiple refresh requests at once.
- Render 10,000 rows smoothly with virtualizationDisplay a very long list or table without freezing the browser.
- Respond to media queries in ReactRender different components for mobile and desktop and react to changes like dark mode or reduced motion.
- Show live updates over WebSocketsUpdate a dashboard in real time when the server pushes events, with reconnects.
- Show toast notifications from anywhereDisplay success and error messages from any component or mutation without prop drilling.
- Split your bundle by routeReduce initial JavaScript so the first page loads faster.
- Sync filters and pagination with the URLMake a filtered product list shareable and keep filters when the user refreshes or goes back.
- Test a data-fetching component with MSWWrite reliable tests for a component that loads data, including loading and error states.
- Upload files with a progress bar in ReactUpload large files directly to storage with a progress indicator and cancel button.
- Validate forms with React Hook Form and ZodBuild a signup form with field-level errors, server error mapping and accessible messages.
- Warn users about unsaved changesPrevent users from losing a half-filled form when navigating away or closing the tab.
Spring Boot
All Spring Boot recipes →- Add correlation IDs to Spring Boot logsTrace every log line of a request (and its outbound calls) with one ID returned to clients.
- Add retries and a circuit breaker with Resilience4jKeep your service responsive when a downstream dependency becomes slow or fails.
- Authenticate machine clients with API keys in Spring SecurityAllow server-to-server clients to call your API with hashed, revocable API keys.
- Cache service results in Redis with @CacheableSpeed up slow product lookups with a shared Redis cache and per-cache TTLs.
- Consume Kafka messages with retries and a dead-letter topicProcess order events reliably: retry transient failures, park poison messages, and never process twice.
- Handle concurrent updates with optimistic lockingPrevent lost updates when two users edit the same record, and retry automatically for background updates.
- Implement soft delete with HibernateLet users 'delete' records that can be restored and excluded from normal queries.
- Make POST endpoints idempotent in Spring BootPrevent duplicate orders or charges when clients retry a request after a timeout.
- Map entities to DTOs with MapStructStop hand-writing repetitive mapping code between JPA entities and API records.
- Paginate and sort safely with Spring DataExpose a paginated list endpoint with client-chosen sorting, without leaking entities or allowing arbitrary sort fields.
- Publish events reliably with the transactional outboxSave an order and publish an OrderCreated message to Kafka/RabbitMQ without losing or duplicating events on failures.
- Rate limit a Spring Boot API with RedisLimit each API client to N requests per minute across all instances and return 429 with Retry-After.
- Run scheduled jobs once across replicas with ShedLockRun a nightly cleanup with @Scheduled without every instance executing it.
- Send emails after a transaction commits in SpringSend a confirmation email only if the order was actually saved, without slowing down the request.
- Shut down Spring Boot gracefully on KubernetesDeploy new versions without dropping in-flight requests or failing health checks.
- Stream progress updates with Server-Sent EventsShow live progress of a long-running import in the browser.
- Test external API integrations with WireMockTest your RestClient-based integration with a payment API, including errors and timeouts, without calling the real service.
- Track created/updated timestamps and users with JPA auditingAutomatically fill createdAt, updatedAt, createdBy and updatedBy on every entity.
- Upload files to S3 from Spring Boot with presigned URLsLet browsers upload large files directly to S3 while your API controls who can upload what.
- Verify webhook signatures in Spring BootAccept signed webhooks from a provider, reject forgeries and replays, and process each event once.
Tailwind CSS
All Tailwind CSS recipes →- Add a dark mode toggleLet users switch between light and dark themes with a button, using Tailwind's dark variant.
- Add breadcrumbs and paginationHelp users see where they are and move between pages of results.
- Build a dashboard layout with a sidebarCreate an app shell with a fixed-width sidebar, a top bar and a scrollable main area that adapts to small screens.
- Build a dropdown menuOpen a small menu of actions from a button, positioned below it and above other content.
- Build a hero section with a gradient headlineCreate an eye-catching landing-page hero with a large headline, supporting text and two call-to-action buttons.
- Build an FAQ accordionShow questions that expand to reveal answers, accessible to keyboard and screen-reader users, with a rotating arrow.
- Build a responsive navbar with a mobile menuShow links in a row on desktop and collapse them into a menu button on phones, without writing JavaScript.
- Create a card with a gradient borderGive a card a colourful gradient border while keeping a solid background inside.
- Create an accessible modal dialogShow a modal with a dimmed backdrop that traps focus and closes with Escape, using as little JavaScript as possible.
- Create a responsive card gridDisplay products or articles in a grid that shows one column on phones and more on larger screens, with equal-height cards.
- Design a pricing table with a highlighted planShow three pricing plans side by side, with the recommended plan visually emphasised and stacked cards on phones.
- Display an overlapping avatar groupShow a row of user avatars that overlap, with a '+N' counter for the rest.
- Keep the footer at the bottom of short pagesMake the footer sit at the bottom of the window when there's little content, and below the content when there's a lot.
- Lay out a two-column settings formBuild a clean, accessible form with labels, help text, inputs side by side on wide screens and stacked on phones.
- Make a responsive data tableDisplay tabular data that stays readable on phones, with a sticky header and zebra rows.
- Make tabs with radio inputs and no JavaScriptSwitch between panels of content with tab buttons, without writing JavaScript.
- Show a skeleton loader while content loadsDisplay a placeholder shape of the content while data is loading, instead of a spinner or empty space.
- Show a toast notificationDisplay a small success or error message in a corner of the screen that doesn't block the page.
- Show progress through a multi-step formIndicate which step of a checkout or onboarding flow the user is on, with completed and upcoming steps.
- Style a toggle switch from a checkboxTurn a checkbox into an accessible on/off switch with a sliding knob.
- Access child component methods with template refs and defineExposeA parent needs to focus an input or reset a form inside a child component.
- Add SEO metadata and structured data in NuxtProduct pages have generic titles, no social previews and no structured data.
- Build an accessible modal with TeleportModals render inside overflow-hidden containers, trap nobody's focus and can't be closed with Escape.
- Build custom inputs with defineModel and modifiersA custom input component needs v-model support with trimming or number conversion.
- Catch component errors with an error boundaryOne failing widget crashes the whole page with a blank screen.
- Debounce user input with a custom refExpensive work (search requests, validation) runs on every keystroke.
- Fetch data in a composable and cancel stale requestsTyping in a search box fires overlapping requests, and slow old responses overwrite newer results.
- Fetch, refresh and share data with Nuxt useFetchPages refetch data in the browser after SSR, and lists don't update after mutations.
- Implement a dark mode toggle that respects system settingsUsers want light, dark or system theme, remembered across visits, without a flash of the wrong theme.
- Lazy-load and lazily hydrate heavy componentsA chart library and comments widget make the initial page slow, even though they're below the fold.
- Lazy-load routes and keep navigation fastThe initial bundle includes every page, and the first visit to a page shows a blank screen.
- Load more items with infinite scrollA long list should load the next page as users approach the end, without scroll listeners.
- Manage configuration and secrets with Nuxt runtime configAPI keys end up in the client bundle, and changing a URL requires a rebuild.
- Persist a Pinia store to localStorageThe cart or preferences disappear when users reload the page.
- Protect routes with Vue Router navigation guardsLogged-out users can open account pages, and after login they lose the page they wanted.
- Render large lists efficientlyA table with thousands of rows makes typing and scrolling sluggish.
- Share state down the tree with typed provide/injectDeeply nested components need theme or form context without prop drilling.
- Test components with Vitest and Vue Test UtilsUI changes break forms and buttons without anyone noticing until production.
- Validate forms with zod in a composableForm validation logic is scattered across components with inconsistent messages.
- Validate input in Nuxt server routesAPI routes trust request bodies and query strings, returning 500s on bad input.