Recipes
106 recipes, each run and tested on the exact versions shown. Receipts come straight from the test runs. Browse by library.
Anthropic SDK message streaming with text deltas, tested with a mocked SSE fetch
Stream Claude responses with the Anthropic TypeScript SDK (messages.stream, text events, finalMessage), tested offline with a fake fetch returning Anthropic SSE events.
Anthropic TypeScript SDK tool use loop, tested with a mocked fetch
Run a Claude tool_use loop with the official Anthropic SDK and Zod-validated tool inputs, tested offline with an injected fetch.
Astro 7 component rendering tests with the Container API (Vitest)
Render Astro components to HTML in Vitest with the Container API and getViteConfig, checking props, slots and conditional markup.
Auth.js Drizzle adapter on PGlite Postgres (database sessions)
Set up @auth/drizzle-adapter with the standard Postgres tables on Drizzle, and test user, account linking and database session lifecycle against in-memory PGlite.
Axios + axios-retry with exponential backoff, tested with nock
Configure axios-retry for idempotent requests and 429/5xx responses, tested offline with nock intercepts.
bcryptjs password hashing + jose JWT sessions
Hash passwords with bcryptjs and issue and verify signed JWT session tokens with jose. Framework-agnostic auth core.
Celery 5 on Redis with fakeredis-backed idempotency, tested offline in eager mode
Configure a Celery app on a Redis broker and result backend for production, guard a task with a Redis SET NX idempotency lock, and test it offline with task_always_eager and fakeredis.
Celery 5 tasks, chains and groups tested in eager mode
Define Celery tasks, chain and fan them out with groups, then test them offline with task_always_eager and the in-memory broker.
Click CLI for RRULE next run times, tested with freezegun and CliRunner
A Click command that computes the next run times of an RFC 5545 rule in any IANA zone with dateutil rrule and zoneinfo, with DST gaps normalized and time frozen with freezegun in tests.
CSV import with PapaParse + Zod row validation
Parse CSV uploads with PapaParse (headers, BOM, quoted fields), validate each row with Zod and report row-numbered errors instead of failing the whole file.
date-fns 4 + @date-fns/tz time zone math (DST-safe)
Schedule and format across time zones with date-fns v4 and TZDate from @date-fns/tz: local-midnight boundaries, DST transitions and UTC storage.
Django 6 + Django REST Framework model API with pytest-django
A DRF ModelViewSet with a serializer, router and token-free permissions, tested with pytest-django and APIClient on in-memory SQLite.
Drizzle ORM + better-sqlite3 CRUD
Typed schema, migrations-free table creation and CRUD with Drizzle on an in-memory SQLite database.
Drizzle ORM + drizzle-zod validated inserts on SQLite
Generate Zod insert and select schemas from Drizzle tables with drizzle-zod, refine them, and validate input before inserting into SQLite.
Drizzle ORM + PGlite in-memory Postgres
Real Postgres semantics in tests with no server: Drizzle ORM on PGlite (WASM Postgres) with relations, returning() and transactions.
Drizzle ORM migrations on PGlite (in-memory Postgres)
Apply versioned SQL migrations with Drizzle's PGlite migrator, use Postgres features (jsonb, enums, arrays, onConflictDoUpdate) and test against a fresh in-memory database.
Excel .xlsx export and import with ExcelJS
Generate styled .xlsx reports (header row, number formats, formulas, frozen panes) and read uploaded workbooks back into typed rows with ExcelJS, all in memory.
Express 5 + express-session login flow, e2e-style over real HTTP with a cookie jar
Session login/logout with express-session (regenerate on login, httpOnly cookies), tested end to end against a real listening server using fetch-cookie, no browser or Playwright.
Express 5 + Helmet + express-rate-limit hardening
Add security headers with Helmet and per-IP rate limiting with express-rate-limit to an Express 5 API.
Express 5 + jsonwebtoken auth middleware
Issue HS256 JWTs on login and protect routes with a bearer-token middleware.
Express 5 + Multer 2 file uploads with limits
Accept multipart file uploads in Express 5 with Multer memory storage, size limits and a MIME type filter.
Express 5 + Passport JWT strategy
Protect Express 5 routes with passport-jwt (bearer tokens signed by jsonwebtoken), stateless sessions and role checks.
Express 5 + pino-http structured request logging
Structured JSON request logs in Express 5 with pino-http: request ids, redacted auth headers and per-request child loggers.
Express 5 + Stripe webhook signature verification
Verify Stripe webhook signatures in Express 5 using the raw body, then dispatch on event type. Tested offline with generated test headers.
Express 5 + Zod 4 request validation
Validate JSON bodies in Express 5 with a reusable Zod middleware that returns 400 with field errors.
FastAPI + Pydantic v2 validators, discriminated unions and serializers
Pydantic v2 patterns in FastAPI that agents often get wrong: field_validator, model_validator, discriminated unions, computed_field and response_model filtering.
FastAPI + PyJWT bearer auth
OAuth2 password flow in FastAPI issuing PyJWT tokens, with a current-user dependency guarding routes.
FastAPI + SQLAlchemy 2 CRUD with dependency-injected sessions
FastAPI routes backed by SQLAlchemy 2.x typed models, a per-request session dependency, and TestClient tests on SQLite.
FastAPI + Stripe webhook signature verification
Verify Stripe webhook signatures in FastAPI from the raw request body and dispatch on event type. Tested offline with locally signed payloads.
FastAPI background tasks + dependency overrides
FastAPI BackgroundTasks for post-response work, with dependency_overrides to swap services in tests.
FastAPI config via pydantic-settings as a cached dependency
Load config from env vars with pydantic-settings, inject it into FastAPI routes through a cached dependency, and test it offline with monkeypatch and dependency_overrides.
FastAPI OAuth2 password flow with PyJWT tokens and scope checks
OAuth2 password login issuing PyJWT access tokens, Argon2 hashes via pwdlib, and per-route scope checks with SecurityScopes, tested offline with TestClient.
FastAPI request ids in structlog contextvars, tested with capture_logs
Pure ASGI middleware binds a request id into structlog contextvars, echoes it in an X-Request-ID header, and is tested offline with TestClient and structlog.testing.capture_logs.
FastAPI WebSockets with token auth and broadcast, tested with TestClient
FastAPI WebSocket endpoint that authenticates via query token, rejects with a close code and broadcasts to connected clients; tested with TestClient.websocket_connect.
FastAPI with async SQLAlchemy 2 on aiosqlite, tested offline with per-test in-memory DBs
A FastAPI app using AsyncSession and async_sessionmaker on aiosqlite, tested with httpx.AsyncClient over ASGITransport, overriding the session dependency with a fresh in-memory database for each test.
Fastify 5 + @fastify/jwt protected routes
Sign and verify JWTs in Fastify 5 with @fastify/jwt and an authenticate preHandler that guards routes.
Fastify 5 + Zod 4 type provider for typed routes
Use fastify-type-provider-zod so Zod 4 schemas validate requests, serialize responses and type handlers in Fastify 5.
Fastify 5 routes with JSON Schema validation
Fastify 5 route validation and response serialization with JSON Schema, tested via app.inject().
Flask 3 + Flask-JWT-Extended access and refresh tokens
Login, protected routes, refresh tokens and custom claims in Flask 3 using Flask-JWT-Extended, with an app factory.
Flask 3 app factory + Flask-SQLAlchemy
Flask application factory with Flask-SQLAlchemy 3, a JSON API and pytest fixtures using an in-memory database.
Flask API with Flask-SQLAlchemy and marshmallow-sqlalchemy, validation errors as 422
A Flask JSON API that loads and dumps SQLAlchemy models through SQLAlchemyAutoSchema, returns validation errors as 422, and is tested offline with the Flask test client on in-memory sqlite.
GraphQL Yoga 5 schema, context and errors tested via fetch
Build a GraphQL Yoga server with SDL resolvers, per-request context auth and GraphQLError codes, tested in-process with yoga.fetch.
graphql-request client with typed operations, mocked by MSW graphql handlers
Call a GraphQL API with graphql-request (variables, headers, error handling) and test offline with MSW's graphql.link(url).query/mutation handlers (msw 3 API). graphql stays on 16.x: graphql-request 7 peers on graphql 14 - 16.
Hono + @hono/zod-openapi typed routes with generated OpenAPI docs
Define Hono routes with createRoute and Zod schemas so requests are validated, handlers are typed and an OpenAPI 3.1 document is generated at /doc.
Hono + Drizzle ORM + SQLite REST API (Vitest)
CRUD REST API in Hono backed by Drizzle ORM on better-sqlite3, with Zod validation, tested with Vitest and app.request().
Hono + hono/jwt bearer auth with Zod login
Issue HS256 JWTs from a Zod-validated login route in Hono and guard routes with the built-in jwt middleware.
Hono + Valibot request validation (Vitest)
Validate JSON bodies and query strings in Hono with Valibot schemas via @hono/valibot-validator, with custom error responses, tested with Vitest.
Hono + Zod validator API
Hono routes with @hono/zod-validator for JSON and query validation, tested with app.request().
httpx + tenacity async retries honoring Retry-After, tested with respx
Wrap async httpx calls in tenacity AsyncRetrying that retries 429 and 5xx, honors Retry-After, and patches the wait to zero in tests with respx mocks.
httpx async API client + respx mocks
A typed async API client on httpx with retries on 5xx and Pydantic parsing, tested offline with respx route mocks.
httpx client + tenacity retries with backoff, tested with respx
Retry transient HTTP failures (5xx, 429, timeouts) with tenacity around an httpx client, honoring a max attempt count, tested offline with respx.
httpx OAuth2 client-credentials client with cached tokens and Link pagination
A sync httpx client that fetches and caches an OAuth2 client-credentials token, refreshes it on 401, and follows Link-header pagination, tested offline with respx routes.
Hypothesis property tests for Pydantic v2 models
Property-based tests with Hypothesis on Pydantic v2 models: JSON round trips, validator invariants, and a stateful RuleBasedStateMachine for a small inventory class.
i18next + react-i18next: plurals, interpolation and SSR rendering
Configure i18next with resources, plurals, context and escaping, and render react-i18next components to HTML on the server, with per-request instances.
ioredis cache-aside with TTL, tested with ioredis-mock (Vitest)
Cache-aside helper on ioredis with JSON values, TTLs, stampede-safe single flight and invalidation, tested offline with ioredis-mock in Vitest.
ky HTTP client with hooks and retries, tested with MSW + Vitest
A ky 2 API client (prefix option, state-object hooks) with auth hooks, retry on 5xx and typed JSON, tested offline with MSW's Node server in Vitest.
Kysely + better-sqlite3 typed queries
Type-safe SQL with Kysely on SQLite, including a schema migration, joins and a transaction.
LangChain (Python) LCEL chain with structured parsing, tested with a fake chat model
Compose ChatPromptTemplate, a chat model and a Pydantic output parser with LCEL in langchain-core, tested offline using GenericFakeChatModel.
LangChain.js prompt + model + parser chain tested with a fake chat model
Compose a ChatPromptTemplate, chat model and output parser with LCEL in @langchain/core, tested offline with FakeListChatModel.
LangChain.js tools with Zod schemas and a manual tool-calling loop
Define LangChain.js tools with tool() and Zod schemas, run model tool_calls through them, and feed ToolMessages back, tested with a scripted fake chat model.
Luxon DateTime zones, durations and intervals
Parse, convert and format with Luxon across zones, do calendar-aware math, business-hours checks and Interval overlap, all DST-safe.
NestJS 12 + TypeORM 1 on in-memory SQLite, tested with @nestjs/testing
A NestJS module with a TypeORM entity, repository-backed service and controller, wired to in-memory SQLite and tested end to end through the Nest app with supertest. better-sqlite3 stays on 12.x because TypeORM 1.1 peers on ^12.
Next.js 16 App Router route handler + Zod validation
Validate JSON bodies and search params in a Next.js App Router route handler with Zod, returning typed 400s; tested by calling the handler with NextRequest.
Next.js 16 server actions + Zod with useActionState-shaped results
A 'use server' form action that validates FormData with Zod and returns field errors in the shape useActionState expects, tested by calling the action directly.
Next.js App Router + Stripe webhook handler
A Next.js route handler that verifies Stripe webhook signatures from the raw body and handles checkout.session.completed.
Next.js middleware + Supabase SSR session refresh
Refresh Supabase auth cookies in Next.js middleware with @supabase/ssr and redirect signed-out users away from protected routes.
NextAuth.js v4 credentials provider + JWT/session callbacks (mocked)
NextAuth v4 authOptions for Next.js with a Credentials provider, bcrypt-checked users and role claims flowing through jwt and session callbacks, unit-tested without a server.
Nodemailer email sending tested with jsonTransport
Send multipart (HTML + text) emails with attachments through Nodemailer, swapping SMTP for jsonTransport in tests so nothing leaves the machine.
OpenAI Node SDK streaming chat completions, tested with a mocked SSE fetch
Stream chat completion deltas with the OpenAI SDK (for await over chunks), accumulate text and usage, and handle aborts, tested offline with a fake fetch that returns an SSE body.
OpenAI Node SDK tool calling + Zod, tested with a mocked fetch
Run an OpenAI chat tool-calling loop with Zod-validated tool arguments, tested offline by injecting a fake fetch into the official SDK.
OpenAI Python SDK structured outputs, tested with respx
Call the OpenAI Python SDK and validate JSON output with Pydantic, testing success, malformed output and API errors offline by mocking HTTP with respx.
pandas + Pandera DataFrame schema validation
Validate pandas DataFrames with Pandera DataFrameModel schemas: dtypes, coercion, value checks, custom dataframe checks and lazy error reports.
Pandas pyarrow-backed dtypes with partitioned Parquet round trips
Write and read partitioned Parquet with pyarrow, enforce a pa.schema on write, and keep nullable ints intact using dtype_backend=pyarrow, tested offline on tmp_path.
Polars DataFrame validation with pandera, collecting all errors
Validate Polars DataFrames with a pandera.polars DataFrameModel, collect every failing check with lazy validation, and test the schema offline with in-memory frames.
Prisma 7 + SQLite via better-sqlite3 adapter
Prisma Client 7 with the better-sqlite3 driver adapter, schema push and relational queries on a local SQLite file.
Prisma 7 + SQLite: nested writes, interactive transactions and unique errors
Prisma Client 7 on SQLite (better-sqlite3 adapter): nested creates, an interactive $transaction that rolls back, and handling P2002 unique-constraint errors.
Pure-JS image resize, crop and thumbnails with Jimp (no Sharp)
Create thumbnails with Jimp (no native deps): cover-crop to a square, resize keeping aspect ratio, and re-encode PNG/JPEG buffers, tested with generated images.
Pydantic Settings typed config from env and .env
Typed app configuration with pydantic-settings: env prefixes, nested settings, secrets and validation errors.
pydantic-settings v2 config from env, YAML and defaults with SecretStr
Nested pydantic-settings models loaded with precedence init > env > YAML > defaults, with env_nested_delimiter, SecretStr masking, and offline tests using tmp_path and monkeypatch.
pytest fixtures + factory_boy with SQLAlchemy 2 sessions
Transactional pytest fixtures that roll back per test, plus factory_boy SQLAlchemy factories with sequences, SubFactory and traits.
React Hook Form + Zod 4 resolver schemas (no DOM)
Share one Zod schema between React Hook Form (via @hookform/resolvers) and the server, with cross-field refinements, tested by calling the resolver directly.
React Router 8 data loaders and actions tested with createStaticHandler
Route loaders and actions with redirects, validation errors and 404 responses in React Router's data APIs, tested offline with createStaticHandler and plain Requests.
Resend email sending with React-free templates, tested with MSW
Send transactional email with the Resend Node SDK (HTML + text, tags, idempotency), handling API errors, tested offline by intercepting the Resend API with MSW.
RQ background jobs tested with fakeredis
Enqueue Redis Queue (RQ) jobs and process them with a SimpleWorker against fakeredis, so queue tests run offline with no Redis server.
Socket.IO 4 rooms with handshake auth
Socket.IO server with token auth in the handshake middleware and room-scoped broadcasts, tested with socket.io-client.
SQLAlchemy 2 + Alembic programmatic migrations
Alembic migrations driven from Python (upgrade, downgrade, autogenerate check) against SQLite, with SQLAlchemy 2 models.
SQLAlchemy 2 async ORM + aiosqlite with pytest-asyncio
SQLAlchemy 2.x typed async ORM (Mapped, mapped_column, async_sessionmaker, selectinload) on aiosqlite, with pytest-asyncio fixtures.
SQLAlchemy 2 ORM rows serialized with Pydantic v2 from_attributes
Map SQLAlchemy 2 models, expose nested relationships through Pydantic v2 schemas with from_attributes=True and a computed_field, and test them offline against in-memory SQLite.
SQLModel + FastAPI CRUD with in-memory SQLite
Full CRUD API with SQLModel table models, separate create/update schemas and a session dependency overridden for tests.
SQLModel one-to-many and many-to-many relationships tested on in-memory SQLite
Model one-to-many and link-table many-to-many relationships with SQLModel, load them with selectinload, and test offline on in-memory SQLite with StaticPool.
Streaming CSV transform with csv-parse + csv-stringify
Transform large CSV files without loading them into memory: csv-parse in columns mode, a Node Transform for row logic, csv-stringify output, wired with stream/promises pipeline.
Stripe Node SDK Checkout Sessions with a mocked HTTP client
Create Stripe Checkout Sessions with line items, metadata and idempotency keys, tested offline by plugging a fake fetch into Stripe.createFetchHttpClient.
supabase-js queries and auth tested with a mocked fetch (Vitest)
Use @supabase/supabase-js for table queries and auth in app code, and unit-test it offline by passing a fake fetch to createClient.
SvelteKit form actions with fail() and Zod, unit-tested (Vitest)
SvelteKit +page.server.ts form actions that validate with Zod, return fail(400) with field errors, and redirect on success, tested by calling the actions with a fake RequestEvent.
TanStack Query + React Testing Library hooks and components (Vitest + jsdom)
Test React components and hooks that use TanStack Query v5 with Testing Library on jsdom: fresh QueryClient per test, retries off, mocked fetchers, mutations with invalidation.
tRPC 11 + Zod router with server-side caller
A typed tRPC router with Zod inputs, an auth middleware, and tests through createCaller.
tRPC 11 client + server over fetch with superjson (Vitest)
End-to-end typed tRPC 11: fetch adapter server, createTRPCClient with httpBatchLink and superjson transformer for Dates and Maps, tested in-process with Vitest.
tRPC 11 context, auth middleware and createCaller tests
tRPC 11 router with a request context, a protectedProcedure built from middleware, Zod inputs and TRPCError codes, tested with createCaller (no HTTP).
Typed fetch API client tested with MSW + Zod
A typed fetch client that parses responses with Zod, tested offline by intercepting requests with MSW's Node server.
Typer CLI with Rich tables, progress and --json output
A Typer command that renders Rich tables and progress on stderr, with a --json mode for piping, tested offline with CliRunner and no-color Rich output.
Typer CLI with subcommands, options and CliRunner tests
Build a Typer CLI with subcommands, typed options, env var fallbacks and exit codes, tested with typer.testing.CliRunner.
Vanilla DOM form testing with Testing Library + user-event on happy-dom (Vitest)
Test framework-free DOM code (a validated signup form) the way users use it, with @testing-library/dom queries and user-event typing on happy-dom.
Verify JWTs against a JWKS with jose (RS256, key rotation) in Vitest
Verify third-party RS256 access tokens (Auth0, Cognito, Clerk style) with jose's JWKS key sets, checking issuer, audience, expiry and key rotation, tested offline with a local JWKS.
Vue 3 + Pinia store and component tests with @pinia/testing (Vitest)
Test a Pinia setup store directly and a Vue 3 component that uses it with @vue/test-utils and createTestingPinia (stubbed actions, initial state), on jsdom.
Zod 4 + dotenv typed environment config
Load .env files with dotenv and validate process.env with Zod 4 at startup: coercion, defaults, enums, URLs and readable errors.
Zustand 5 store with persist middleware, tested with Vitest
A typed Zustand 5 vanilla store with actions, derived selectors and persist middleware on a custom storage, tested with Vitest including state reset between tests.