Redirect middleware is a software component inserted into a web server's request-processing pipeline that forwards requests to another URL based on specific conditions. In URL shorteners, it is used as the part responsible for resolving slugs and executing redirects.
In Express.js, you register a middleware function with app.use(), extract the slug from the request path, look up the original URL in the database, and respond with res.redirect(). In Next.js, redirect handling can be defined with the redirects setting in next.config.js (308 if permanent is true, 307 if false) or with a file that runs code on the server before a request completes. According to the Next.js documentation (updated September 2026), this file was renamed from middleware to proxy (proxy.ts) in v16.0.0, and its default runtime is Node.js. In Django, you write middleware as a callable object that takes get_response and returns HttpResponseRedirect when the conditions match (the Django documentation positions MiddlewareMixin as a way to migrate from the style used before 1.10).
The advantage of the middleware pattern is that it separates the redirect logic from the application's other concerns (authentication, logging, rate limiting). By controlling the order of the pipeline, flexible control becomes possible, such as recording access logs before the redirect, rejecting illegitimate requests with rate limiting, and allowing specific redirects only for authenticated users.
In redirect middleware for URL shorteners, performance is one of the challenges. One example is a design that, to minimize database queries, places a cache layer with Redis or Memcached in between to speed up the resolution of hot links and queries the database only on cache misses.
Error handling within the middleware is also part of the design. Building in processing that returns appropriate error pages or fallback URLs for access to nonexistent slugs, disabled links, and expired links keeps the user experience from degrading.