0
0
NextJSframework~10 mins

Middleware.ts file convention in NextJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Middleware.ts file convention
Request Received
Middleware.ts Runs
Check URL/Headers
Allow Request
Continue to Route Handler
Modify Request/Response
Redirect or Block
Response Sent
Middleware.ts runs on every request, checks or modifies it, then decides to continue, redirect, or block.
Execution Sample
NextJS
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  if (request.nextUrl.pathname.startsWith('/admin')) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}
This middleware redirects users trying to access '/admin' to '/login', otherwise lets requests continue.
Execution Table
StepRequest URLConditionActionResult
1/admin/dashboardURL starts with '/admin'Redirect to '/login'Redirect response sent
2/aboutURL does not start with '/admin'ContinueRequest continues to route handler
3/admin/settingsURL starts with '/admin'Redirect to '/login'Redirect response sent
4/homeURL does not start with '/admin'ContinueRequest continues to route handler
💡 Middleware ends by either redirecting or allowing request to continue.
Variable Tracker
VariableAfter 1After 2After 3After 4
request.nextUrl.pathname/admin/dashboard/about/admin/settings/home
Action takenRedirectContinueRedirectContinue
Key Moments - 2 Insights
Why does the middleware redirect only some URLs?
Because it checks if the URL path starts with '/admin' (see execution_table rows 1 and 3). Only those matching URLs trigger the redirect.
What happens if middleware returns NextResponse.next()?
It means the middleware lets the request continue to the next handler or page (see execution_table rows 2 and 4). No redirect or block occurs.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what action is taken at step 2 when the URL is '/about'?
ARedirect to '/login'
BAllow request to continue
CBlock the request
DModify the request URL
💡 Hint
Check the 'Action' column in execution_table row 2.
At which step does the middleware send a redirect response?
ASteps 1 and 3
BStep 4
CStep 2
DAll steps
💡 Hint
Look at the 'Result' column for redirect responses in execution_table.
If the condition changed to check for '/user' instead of '/admin', what would happen at step 1?
ARedirect to '/login'
BBlock the request
CAllow request to continue
DError occurs
💡 Hint
Refer to variable_tracker for request URL and condition logic.
Concept Snapshot
Middleware.ts runs on every request in Next.js.
It checks request details like URL or headers.
Based on conditions, it can redirect, modify, or allow requests.
Use NextResponse to control flow.
Place middleware.ts in the root of the project.
It runs before route handlers or pages.
Full Transcript
Middleware.ts in Next.js is a special file that runs on every incoming request. It checks the request URL or headers and decides what to do next. For example, it can redirect users trying to access protected routes like '/admin' to a login page. If the URL does not match the condition, the middleware lets the request continue to the intended page or API. This behavior is controlled by returning NextResponse.redirect or NextResponse.next. The middleware file should be placed in the root of the project. This setup helps control access and modify requests globally before they reach your pages or API routes.