0
0
NextJSframework~30 mins

Why middleware intercepts requests in NextJS - See It in Action

Choose your learning style9 modes available
Understanding Why Middleware Intercepts Requests in Next.js
📖 Scenario: You are building a Next.js app that needs to check user access before showing pages. Middleware helps by intercepting requests to decide what to do next.
🎯 Goal: Build a simple Next.js middleware that intercepts requests to check if a user is logged in before allowing access to a protected page.
📋 What You'll Learn
Create a middleware function in middleware.ts
Set a config variable to specify which paths the middleware should run on
Use the middleware to check for a cookie named userToken
Redirect to /login if the cookie is missing
Allow the request to continue if the cookie exists
💡 Why This Matters
🌍 Real World
Middleware is used in real apps to protect pages, check user login status, and redirect users before they see content.
💼 Career
Understanding middleware is important for Next.js developers to build secure and user-friendly web applications.
Progress0 / 4 steps
1
Create the middleware function
Create a file named middleware.ts and write a middleware function called middleware that takes a request parameter.
NextJS
Need a hint?

Middleware is a function that runs before your page loads. Start by defining it with export function middleware(request).

2
Configure middleware to run on protected paths
Add a config export with a matcher array that includes the path /protected so the middleware runs only on that path.
NextJS
Need a hint?

Use export const config = { matcher: ['/protected'] } to tell Next.js where to run the middleware.

3
Check for userToken cookie in middleware
Inside the middleware function, get the cookie named userToken from request.cookies. If the cookie is missing, return a redirect response to /login.
NextJS
Need a hint?

Use request.cookies.get('userToken') to read the cookie. If it is missing, redirect to /login using NextResponse.redirect.

4
Allow request to continue if userToken exists
At the end of the middleware function, return NextResponse.next() to let the request continue if the userToken cookie exists.
NextJS
Need a hint?

Use return NextResponse.next() to let the request continue when the user is logged in.