0
0
NextJSframework~30 mins

Protected routes with middleware in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Protected routes with middleware
📖 Scenario: You are building a Next.js app that has some pages only accessible to logged-in users. To keep your app safe, you want to block visitors who are not logged in from seeing these pages.Middleware in Next.js can help by checking if a user is logged in before letting them visit protected pages.
🎯 Goal: Build a simple Next.js middleware that checks if a user is logged in by looking for a cookie called token. If the cookie is missing, the user is redirected to the login page. Otherwise, they can access the protected page.
📋 What You'll Learn
Create a middleware file in the root of the Next.js app
Check for a cookie named token in the request
Redirect users without the token cookie to /login
Allow users with the token cookie to continue to the requested page
Apply middleware only to the /dashboard route
💡 Why This Matters
🌍 Real World
Middleware is used in real apps to protect pages that require login, like dashboards or user profiles.
💼 Career
Understanding middleware and route protection is important for building secure web applications and is a common task in frontend and full-stack developer roles.
Progress0 / 4 steps
1
Create middleware file and import NextResponse
Create a file named middleware.ts in the root of your Next.js project. Inside it, import NextResponse from next/server.
NextJS
Need a hint?

Middleware files in Next.js are named middleware.ts or middleware.js and live in the root folder.

2
Create middleware function and check for token cookie
Add an exported function named middleware that takes a request parameter. Inside it, get the token cookie from request.cookies and store it in a variable named token.
NextJS
Need a hint?

Use request.cookies.get('token') to read the cookie named token.

3
Redirect users without token to login page
Inside the middleware function, add an if statement that checks if token is undefined. If so, return NextResponse.redirect(new URL('/login', request.url)) to send the user to the login page.
NextJS
Need a hint?

Use !token to check if the token cookie is missing.

4
Apply middleware only to /dashboard route
Add an exported constant named config with a matcher property set to ['/dashboard'] to apply the middleware only to the /dashboard path.
NextJS
Need a hint?

The config export controls which routes the middleware runs on.