What does middleware do in SSR?
What middleware is in an SSR context
Middleware is a function that runs between:
the moment the server receives a request, and the moment it starts rendering HTML and sending the response.
You could say:
Middleware is a "filter" or "layer" that every SSR request passes through to perform common tasks: authentication, redirects, logging, caching, and so on.
Where middleware sits in the SSR chain
A typical SSR pipeline looks like this:
(1) Client request
↓
(2) Middleware (checks, tokens, redirects)
↓
(3) SSR page rendering (React/Vue → HTML)
↓
(4) Response to the clientThat is, middleware runs before (or sometimes alongside) the page render.
Main tasks of middleware in SSR
1. Authentication and authorization
Middleware often checks whether the user has access to the page.
Example:
export function middleware(req) {
const token = req.cookies.get('token');
if (!token) {
return Response.redirect('/login');
}
return NextResponse.next();
}If the token is valid, the request continues (the page is rendered). If not, redirect to
/login.
2. Redirects (redirect / rewrite)
Middleware can:
- redirect the user to another page,
- rewrite the request path without changing the URL in the address bar.
if (req.nextUrl.pathname === '/old') {
return NextResponse.redirect('/new');
}3. Localization and geo-targeting
Middleware can determine:
- the language (
Accept-Language), - the country (by IP),
- the UI theme (cookie, header).
and redirect to the corresponding version of the page:
if (req.geo.country === 'FR') {
return NextResponse.rewrite('/fr' + req.nextUrl.pathname);
}4. Handling sessions and cookies
Before SSR rendering, middleware can:
- read a
cookieand decrypt the token, - write new cookies (for example, a refresh token),
- pass the user's data into the SSR context.
const session = verifyJWT(req.cookies.get('token'));
req.user = session.user;5. Caching and edge optimization
Middleware can decide whether it's possible to return cached HTML instead of running the SSR render every time.
Example:
if (cache.has(req.url)) {
return new Response(cache.get(req.url));
}
return NextResponse.next();It's used on an edge server (Vercel Edge, Cloudflare Workers), closer to the user. It lets you serve the cache instantly without warming up SSR.
6. Logging, analytics, A/B testing
Middleware is convenient for:
- logging requests,
- adding a tracking ID,
- assigning users to A/B groups.
7. Preparing data for the SSR render
Sometimes middleware adds data to the request object (req.context, req.user, req.featureFlags)
that's later used during SSR rendering.
For example, if the user is an admin, the SSR render draws more UI elements.
An example chain in Next.js
// middleware.ts
import { NextResponse } from 'next/server';
export function middleware(req) {
const { pathname } = req.nextUrl;
// Authorization check
if (pathname.startsWith('/dashboard')) {
const token = req.cookies.get('session');
if (!token) return NextResponse.redirect('/login');
}
// Automatic localization
if (pathname === '/') {
const locale = req.headers.get('accept-language')?.split(',')[0];
return NextResponse.rewrite(`/${locale}/home`);
}
return NextResponse.next();
}Here:
- middleware runs before the SSR render,
- it can change the path (
rewrite), - it can return a response right away (a redirect, 403, cached content),
- or simply let the request continue.
Advantages of middleware in SSR
| Task | Why middleware is the best place for it |
|---|---|
| Checking authorization | No need to render the page for nothing |
| Redirects | Work before React loads |
| SEO redirects | Run on the server without JS |
| Caching | HTML can be served without SSR |
| Localization / A/B testing | Doesn't require a re-render |
What middleware does not do
- It doesn't render React, the SSR engine does that (for example,
renderToString()). - It has no access to the DOM or React components.
- It doesn't run on the client, only on the server (or an edge node).
Short summary
Middleware in SSR:
- runs before HTML rendering,
- handles general request tasks (authentication, redirects, caching, localization),
- can influence which page gets rendered, or even stop the SSR render,
- acts as a thin controller between the client and the rendering system.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.