0
0
NextJSframework~30 mins

Authentication in middleware in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Authentication in middleware
📖 Scenario: You are building a Next.js app that needs to protect certain pages so only logged-in users can access them.Middleware is a special place where you can check if a user is logged in before they see the page.
🎯 Goal: Create a Next.js middleware that checks if a user has a valid token cookie. If not, redirect them to the login page.
📋 What You'll Learn
Create a middleware function in middleware.ts
Check for a cookie named token
If token cookie is missing, redirect to /login
Allow access if token cookie exists
💡 Why This Matters
🌍 Real World
Middleware is used in real apps to protect pages and APIs by checking if users are logged in before showing content.
💼 Career
Understanding authentication middleware is important for building secure web apps and is a common task for frontend and full-stack developers.
Progress0 / 4 steps
1
Create the middleware file
Create a file named middleware.ts and export a function named middleware that takes a request parameter.
NextJS
Need a hint?

Middleware must be exported from middleware.ts and receive a request object.

2
Check for the token cookie
Inside the middleware function, create a variable named token that gets the token cookie from request.cookies.
NextJS
Need a hint?

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

3
Redirect if token is missing
Add an if statement that checks if token is undefined. If so, return NextResponse.redirect(new URL('/login', request.url)).
NextJS
Need a hint?

If the token cookie is missing, redirect the user to the login page.

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

Use NextResponse.next() to continue the request when the user is authenticated.