0
0
NextJSframework~10 mins

Protected routes with middleware in NextJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Protected routes with middleware
User Request URL
Middleware Intercepts Request
Check Authentication Token
Allow Access
Render Page
The middleware checks if the user is authenticated before allowing access to protected pages. If not authenticated, it redirects to login.
Execution Sample
NextJS
import { NextResponse } from 'next/server';

export function middleware(request) {
  const pathname = request.nextUrl.pathname;
  if (pathname.startsWith('/dashboard') || pathname.startsWith('/profile')) {
    const token = request.cookies.get('token');
    if (!token) return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}
Middleware checks for a token cookie; if missing, redirects to login; otherwise, allows the request.
Execution Table
StepRequest URLToken Present?Action TakenResult
1/dashboardNoRedirect to /loginUser sent to login page
2/dashboardYesAllow accessDashboard page rendered
3/profileNoRedirect to /loginUser sent to login page
4/profileYesAllow accessProfile page rendered
5/loginNoAllow accessLogin page rendered
6/loginYesAllow accessLogin page rendered
💡 Middleware stops by either redirecting unauthenticated users or allowing authenticated users to proceed.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5After Step 6
tokenundefinedundefinedstring_tokenundefinedstring_tokenundefinedstring_token
request.url/dashboard/dashboard/dashboard/profile/profile/login/login
actionnoneredirectallowredirectallowallowallow
Key Moments - 2 Insights
Why does the middleware redirect some requests but not others?
Because the middleware checks if the token cookie exists (see execution_table rows 1 and 2). If no token, it redirects to login; if token exists, it allows access.
What happens if a user tries to access the login page while authenticated?
The middleware allows access (see execution_table rows 5 and 6). Middleware does not block login page regardless of token presence.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what action is taken at step 3 when token is missing?
ARender dashboard
BRedirect to /login
CAllow access
DThrow error
💡 Hint
Check the 'Action Taken' column at step 3 in the execution_table.
At which step does the middleware allow access to the profile page with a token?
AStep 4
BStep 3
CStep 5
DStep 6
💡 Hint
Look for the row with Request URL '/profile' and Token Present? 'Yes' in the execution_table.
If the token cookie is always missing, what will happen to requests for protected pages?
AThey will cause an error
BThey will be allowed
CThey will be redirected to /login
DThey will load normally
💡 Hint
Refer to the 'Token Present?' and 'Action Taken' columns in the execution_table for missing tokens.
Concept Snapshot
Protected routes use middleware to check authentication.
Middleware runs before page loads.
If token cookie missing, redirect to login.
If token present, allow page access.
This protects pages from unauthenticated users.
Full Transcript
This visual execution shows how Next.js middleware protects routes by checking for an authentication token cookie. When a user requests a page, the middleware intercepts the request and looks for the token. If the token is missing, the middleware redirects the user to the login page. If the token exists, the middleware allows the request to continue and the page renders normally. The execution table traces requests to different URLs with and without tokens, showing when redirects happen and when access is allowed. The variable tracker shows how the token and action variables change at each step. Key moments clarify why redirects happen and how login page access is handled. The quiz tests understanding of middleware decisions based on token presence. This helps beginners see step-by-step how protected routes work in Next.js middleware.