0
0
NextJSframework~5 mins

Protected routes with middleware in NextJS

Choose your learning style9 modes available
Introduction

Protected routes keep parts of your website safe. Middleware checks if a user can see a page before showing it.

You want only logged-in users to see their profile page.
You need to stop visitors from accessing admin pages.
You want to redirect users to login if they try to open a private page.
You want to check user permissions before loading certain pages.
Syntax
NextJS
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const token = request.cookies.get('token')?.value;
  if (!token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}

export const config = {
  matcher: ['/protected-route', '/another-protected-route'],
};

Middleware runs before the page loads to check conditions.

The matcher tells Next.js which routes to protect.

Examples
Simple check for a cookie named 'auth'. Redirects to login if missing.
NextJS
export function middleware(request) {
  const isLoggedIn = Boolean(request.cookies.get('auth'));
  if (!isLoggedIn) {
    return NextResponse.redirect('/login');
  }
  return NextResponse.next();
}
Checks user role cookie to allow only admins to proceed.
NextJS
export function middleware(request) {
  const role = request.cookies.get('role')?.value;
  if (role !== 'admin') {
    return NextResponse.redirect('/not-authorized');
  }
  return NextResponse.next();
}
Sample Program

This middleware protects the '/dashboard' and '/settings' pages. If the user has no 'token' cookie, they get sent to '/login'. Otherwise, they can see the page.

NextJS
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const token = request.cookies.get('token')?.value;
  if (!token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}

export const config = {
  matcher: ['/dashboard', '/settings'],
};
OutputSuccess
Important Notes

Middleware runs on the server side before the page loads.

Cookies are a common way to check if a user is logged in.

Always test your middleware to avoid blocking public pages by mistake.

Summary

Middleware helps protect routes by checking user info before loading pages.

Use cookies or tokens to decide if a user can access a page.

Configure which routes to protect using the matcher setting.