Skip to content
tezvyn:

Middleware

49 bites tagged Middleware — interview questions with model answers, and 60-second explainers.

Go & Rust1 min read

In-memory rate limiter middleware in Go

Use a token-bucket limiter (golang.org/x/time/rate), guard a per-client map with sync.Mutex, wrap http.Handler so requests over the limit get 429. rate limiting and middleware design.

React & Next.js2 min read

Implement A/B testing with Middleware rewrites and cookies

Sticky cookie, internal rewrite, vary cache on cookie, server-side analytics. Using Next.js Middleware to split traffic and the cache or analytics impact. Client redirects or ignoring cache collisions.

React & Next.js2 min read

Where Next.js Middleware executes and Edge Runtime limits

Tests your grasp of Edge Runtime constraints. Middleware runs at the Edge before route matching, with no Node.js APIs, require, Buffer, or dynamic eval, only Web APIs. Red flag: treating it as Node.js and suggesting fs or npm packages.

React & Next.js2 min read

What is Next.js Middleware and a real-world auth use case?

This tests request interception before a route renders. A good answer defines Middleware as pre-request code using NextRequest and NextResponse, often on the Edge Runtime, with auth redirects as an example.

React & Next.js2 min read

How would you use Next.js Middleware to protect /api/admin/* routes?

Match /api/admin/:path*, read the secure cookie, validate the token, return 401 or proceed. Edge auth and why client session objects cannot secure API routes. Using useSession or the client session object in Middleware.

React & Next.js2 min read

Zustand Middleware: Intercept Every Set Call

Zustand middleware intercepts set calls to add logging, persistence, or devtools without touching business logic. Use it when updates need the same side effect, like localStorage sync.

Python & FastAPI2 min read

Design DB transaction middleware and identify the background-task pitfall

Tests request-scoped DB lifecycle awareness. Strong answer: middleware closes the session on response, yet BackgroundTasks run afterward, so sharing that session causes crashes or leaks. Red flag: saying background tasks can reuse the request transaction.

Python & FastAPI2 min read

Which FastAPI CORSMiddleware parameters beyond allow_origins fix a PUT preflight?

Configure allow_methods for PUT and allow_headers for Authorization so the browser approves the cross-origin call. CORS preflight mechanics for non-simple requests.

Python & FastAPI2 min read

Write a FastAPI middleware that adds X-Process-Time header

Tests FastAPI lifecycle and header mutation. Strong answers use the http middleware decorator, await call_next, compute elapsed time, and inject X-Process-Time before returning. Red flag: forgetting to await call_next or mutating headers after the return.

Python & FastAPI2 min read

Purpose of await next(request) in FastAPI middleware and timing effects

Tests ASGI middleware lifecycle. await next(request) forwards the request downstream to the endpoint and returns the response. Pre-call code touches the request; post-call code touches the response.

Node.js & Express2 min read

express-validator: Validate at the Edge

express-validator stops garbage before it hits your logic. Use it on any route that accepts user input like form data, query strings, or JSON payloads. The biggest mistake is validating but forgetting to check validationResult, so invalid requests pass.

Node.js & Express2 min read

Validation Checks Rules; Sanitization Cleans Input

Validation checks if input fits your rules and rejects failures. Sanitization cleans allowed input so it cannot cause harm. Validate at the boundary to enforce shape, then sanitize before rendering. Never swap them; scrubbing a bad date does not make it valid.

Vue, Angular & Svelte2 min read

SvelteKit Hooks: Intercepting Requests and Events

SvelteKit Hooks are like middleware, letting you intercept requests and events to run app-wide logic. Use them for tasks like authentication checks, initializing DB clients, or custom routing.

React & Next.js2 min read

Next.js Middleware: Your App's Edge Bouncer

Think of Next.js Middleware as a bouncer at your app's door. It runs code on the edge before a request is processed, letting you redirect, rewrite, or block it. The main footgun is forgetting it runs in a limited Edge Runtime, not a full Node.js.

React Native2 min read

Redux Middleware: Intercepting Actions Before Reducers

Redux middleware is like an Express middleware for your state, intercepting actions before they hit the reducer. It's used for logging, crash reporting, or async API calls. The footgun is forgetting to call `next(action)`, which silently blocks the action.

Python & FastAPI2 min read

Custom FastAPI Middleware: The BaseHTTPMiddleware Helper

FastAPI's BaseHTTPMiddleware lets you wrap endpoints to run code before and after they execute. Use it to add custom headers or log request times. The footgun: reading `request.body()` in the middleware will break the endpoint, as the body can only be read…

Node.js & Express2 min read

Socket.IO Middleware: Your Connection Gatekeeper

Socket.IO middleware is a gatekeeper for new connections, running before a client is fully connected. It's ideal for authentication, rate limiting, or logging. The key footgun: you must always call `next()`, or the connection will hang until it times out.

Node.js & Express2 min read

Mongoose Middleware (Hooks): Intercepting Database Operations

Mongoose middleware (hooks) lets you intercept database operations. Think of them as "before" or "after" scripts for actions like `save` or `find`. Use them to hash passwords before saving a user.

Node.js & Express2 min read

API Rate Limiting: Protecting Your Express Endpoints

Rate limiting acts as a bouncer for your API, preventing any single user from overwhelming it. It's crucial for public APIs and sensitive endpoints like password resets to block abuse. The default in-memory store won't work across multiple server instances.

Node.js & Express2 min read

cookie-parser: From Header String to Usable Object

The cookie-parser middleware translates the raw Cookie header string into a usable `req.cookies` object. It's used in Express apps to read session IDs or user preferences.

Node.js & Express2 min read

Morgan: One-Line Request Logging for Express

Morgan is a plug-and-play stenographer for your Express app, automatically logging every incoming HTTP request. Use its predefined formats for quick debugging or create custom formats for production access logs.

Node.js & Express2 min read

CORS Middleware: Unlocking Cross-Origin Requests in Express

The `cors` middleware tells browsers which external websites can read your Express API's responses. Use it when a frontend on one domain needs to fetch data from your API on another.

Node.js & Express2 min read

Express Middleware: Intercepting Requests Before Your Route Handler

Express middleware is like a bouncer for your routes, running code before your main handler. Use it for logging, authentication, or parsing request bodies. The biggest footgun is forgetting to call `next()` or send a response, which leaves requests hanging.

Node.js & Express2 min read

Express Error Middleware: Your App's Safety Net

Express error middleware is a safety net that intercepts unhandled errors, preventing crashes. It's used to centralize logging and format consistent error responses. The biggest footgun is placement: it must be defined *after* all other routes and middleware.

Get Middleware bites daily.

Five a day, five minutes, offline. With quizzes so it sticks.

Open testing — you’ll join as an early tester.