Enterprise software, security and engineering notes
What is middleware? Request layer in Next.js and enterprise use
Engineering ·
Author: Mehmet DOĞAN
Editor: Mehmet DOĞAN
What is middleware?
Middleware is software that runs before your application code (pages, APIs, Server Components) handles a web request. The request arrives from a browser or mobile app; before business rules, database queries or rendering start, middleware can decide whether to continue, redirect or reject. Teams often compare it to a building security desk: identity, locale, path and simple policy checks happen before the visitor reaches the floors inside.
This article answers what is middleware for general web architecture
and for Next.js App Router middleware.ts: what it does,
what it is not, request-flow diagrams, and patterns we see in
enterprise projects. For a business-language summary, see
security and control layer on web requests; here we focus on technical definition and boundaries.
• • •
What middleware is not
Stuffing everything into middleware is a common mistake. Clear boundaries:
- Not a business-rule engine. Invoicing, stock reservation and approval chains belong in pages/APIs or domain services.
- Not a place for heavy persistent writes. Database writes on every request inflate latency and failure surface; edge runtimes discourage it.
- Not an API gateway or load balancer. Cloud gateways handle TLS, WAF and traffic shaping; app middleware applies product rules (locale, session, matcher). They complement each other; they are not synonyms.
- Not full authorization (RBAC). “Is the user signed in?” is a thin gate; “can this role delete this record?” is usually solved inside the app with an RBAC model.
In short: middleware is for early, thin, repeatable decisions. Pushing thick domain logic here harms maintainability and makes tests brittle.
• • •
Diagram: where middleware sits on the request path
The diagram below shows client, middleware and application handler order. Middleware may short-circuit (redirect, early response) or pass the request on.
In classic Node/Express stacks, middleware is a chain via
app.use: each function receives (req, res, next),
does work, then calls the next function or ends the response. In Next.js App
Router, a root-level middleware.ts (or
src/middleware.ts) plays this role on the Edge Runtime, scoped by
a matcher. The goal is the same: shared decisions before application
render.
• • •
Next.js middleware and the matcher
Next.js middleware can inspect URL, headers and cookies, then rewrite,
redirect or continue with NextResponse.next(). Critically, it
does not have to run on every request. If static assets
(/_next/static), images and noisy paths are left inside the
matcher, you pay unnecessary cost and latency.
On enterprise multilingual sites the matcher often covers
/tr/* and /en/*: missing locale prefixes redirect,
legacy slugs get 301s, admin routes get a session gate. Keeping those rules in
one place improves SEO and security consistency. For when to discuss this
layer in discovery, see
web software development process.
• • •
Typical enterprise uses
1. Locale and URL consistency (i18n)
If a user hits a locale-less path like /blog/…, middleware can
redirect to the preferred or default /tr route. Legacy
prefix-free URLs may also be 301’d here (or alongside an edge redirect table).
Goal: one canonical path for users and search engines.
2. Session gate (auth)
For admin or customer portals, middleware checks “is there a session cookie?” If not, redirect to login; if yes, continue. Fine-grained role checks usually stay in a later layer.
3. Security headers and light traffic rules
Adding security headers, disabling cache on sensitive paths, or cutting crude bot/rate signals early are common middleware jobs. Heavy threat intel and WAF still belong in infrastructure; app middleware encodes product policy.
4. Experiments and feature flags
Reading a cookie/header and rewriting to a variant path enables A/B tests without forking the whole page tree. Still avoid burying domain rules inside the flag file.
• • •
Good practices and common pitfalls
- Keep it thin. Early decisions only: redirect, reject, set headers, continue. Do not generate reports or send email here.
- Avoid heavy I/O. Remote APIs or slow DB calls on every request spread latency across the site. Prefer cached short-TTL reads or checks deferred to the next layer.
- Write the matcher deliberately. Exclude static and noisy paths or cost and cold-start effects grow.
- Know Edge constraints. Next.js middleware runs on Edge Runtime; Node-only packages and some APIs are unavailable. Clarify runtime in discovery.
- Observability. Bad redirect loops burn SEO. You should be able to ask “how many requests did middleware short-circuit?” — see observability.
- Test. Automate or checklist matcher + redirect scenarios; locale and auth edge cases are easy to miss manually.
Used well, middleware improves consistency and security signal; used poorly it becomes the “put everything here” anti-pattern. When building enterprise web apps, write this layer into the discovery output as part of a transparent web software development engagement.
• • •
Middleware vs API route / Server Action
An API route or Server Action performs a specific job (form save, report). Middleware is an early filter shared across many paths. “Register the user” lives in an API; “block unsigned admin access” lives in middleware. Mixing them creates security holes and duplicated code.
Likewise CDN/WAF rules belong to infrastructure; product locale, session and panel paths live in application middleware. Clear boundaries make incident response clearer: is a 301 loop an app redirect or an edge rule?
• • •
FAQ
Is middleware required on every project?
No. A single-locale, public static site can live without it. Multilingual URLs, admin panels, session gates or central redirects are when middleware (or an equivalent edge rule) pays off.
Is middleware the whole security layer?
No. It is one early control. RBAC, validation, audit trails, encryption and infrastructure WAF are separate pieces. For business language see security and control layer.
Should middleware query the database?
Sometimes technically possible, but the default advice is no: latency, failure surface and Edge limits favour thin cookie/JWT checks; heavy queries stay in the application layer.
Is Express middleware the same as Next.js middleware?
The idea is the same (a step in the request chain); runtime and API differ.
Express uses a Node next() chain; Next.js App Router middleware
runs on Edge and is scoped by matcher. Port the pattern, not the code
line-by-line.
How does Aksiyon Soft treat middleware?
Discovery documents which paths are public vs session/locale-gated; matcher and redirect tables enter the sprint definition. Our Samsun-based teams apply this discipline on enterprise web and custom software projects across Turkey. Request a discovery via contact.
• • •
Summary
What is middleware? A thin early-decision layer that runs before
application business logic. What it is not: a domain engine, thick
authorization, or a magic replacement for an API gateway. In Next.js,
middleware.ts plus a matcher centralises locale, session and
security-header rules; the diagrams show the pipeline, matcher and auth gate.
Right boundaries raise SEO, security and operational clarity — wrong ones
inflate latency and complexity.
To design the request layer together on an enterprise web or custom software project, see web software development and custom software development, or use the contact form.
Subscribe to blog and news
Get an email when we publish. Unsubscribe any time.
Related posts
Software Buyer Guides
Gaziantep Software Partner: Export ERP, e-Invoicing and B2B Portals
A guide to Gaziantep software needs for textile, carpet and food exporters: export ERP, e-invoice and customs integration, multi-plant production and B2B dealer portals.
Software Buyer Guides
Malatya Software Partner: Apricot Exports, Traceability and Business Continuity
How Malatya software projects can support apricot processing and exports, OIZ textiles and post-earthquake rebuilding: traceability, export documents, cloud backups and business continuity.