0
0
NextJSframework~10 mins

Authentication in middleware in NextJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Authentication in middleware
Request arrives
Middleware runs
Check for auth token
Validate
Allow
request
The middleware checks each request for an authentication token. If found, it validates it and allows the request. If not, it redirects to login.
Execution Sample
NextJS
import { NextResponse } from 'next/server';

export function middleware(request) {
  const token = request.cookies.get('authToken');
  if (!token) return NextResponse.redirect(new URL('/login', request.url));
  return NextResponse.next();
}
Middleware checks for 'authToken' cookie; if missing, redirects to login; otherwise, allows request to continue.
Execution Table
StepActionToken Present?ResultResponse
1Request arrives with cookiesYesToken foundContinue request
2Middleware reads cookiesYesToken validNextResponse.next()
3Request proceeds to pageYesAccess grantedPage rendered
4Request arrives without cookiesNoToken missingRedirect to /login
5Middleware redirectsNoNo token to validateNextResponse.redirect(new URL('/login', request.url))
6Request stopsNoAccess deniedLogin page shown
💡 Execution stops when token is missing and redirect happens, or continues if token is valid.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 4After Step 5
tokenundefined'abc123' (present)'abc123' (valid)undefined (missing)undefined (redirect)
Key Moments - 2 Insights
Why does the middleware redirect instead of allowing the request when the token is missing?
Because the middleware checks if the token exists (see execution_table row 4). If it doesn't, it immediately returns a redirect response to '/login' (row 5), stopping the request from continuing.
What happens if the token is present but invalid?
In this simple example, the middleware only checks presence, not validity. To handle invalid tokens, you would add validation logic after step 2 before allowing the request.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the response at Step 2 when the token is present?
ANextResponse.redirect('/login')
BNextResponse.next() to continue
CRequest stops with error
DNo response sent
💡 Hint
Check the 'Response' column at Step 2 in the execution_table.
At which step does the middleware decide to redirect the user to the login page?
AStep 5
BStep 3
CStep 1
DStep 6
💡 Hint
Look for 'NextResponse.redirect' in the 'Response' column.
If the token variable was always undefined, what would happen according to the variable_tracker?
ARequests always continue
BRequests sometimes continue
CRequests always redirect to login
DMiddleware crashes
💡 Hint
See variable_tracker values for 'token' and how missing token triggers redirect in execution_table.
Concept Snapshot
Authentication in Next.js middleware:
- Middleware runs on every request
- Check for auth token in cookies
- If token missing, redirect to login
- If token present, allow request
- Use NextResponse.next() to continue
- Use NextResponse.redirect() to redirect
Full Transcript
In Next.js, middleware runs on every incoming request. It checks if the request has an authentication token in its cookies. If the token is missing, the middleware redirects the user to the login page, stopping the request from continuing. If the token is present, the middleware allows the request to proceed to the requested page. This process helps protect pages by ensuring only authenticated users can access them. The key steps are reading the token, deciding based on its presence, and responding with either a redirect or continuation.