Authentication in middleware helps check who a user is before they see a page. It keeps parts of your app safe by stopping strangers from getting in.
0
0
Authentication in middleware in NextJS
Introduction
When you want to protect private pages like user profiles or settings.
When you want to check if a user is logged in before showing content.
When you want to redirect users to login if they are not signed in.
When you want to run checks on every request to your app.
When you want to add security without repeating code in every page.
Syntax
NextJS
import { NextResponse } from 'next/server'; export function middleware(request) { // Check user authentication here const token = request.cookies.get('token'); if (!token) { // Redirect to login if no token return NextResponse.redirect(new URL('/login', request.url)); } // Allow request if authenticated return NextResponse.next(); } export const config = { matcher: ['/protected/:path*'], };
The middleware function runs before the page loads.
Use NextResponse.redirect() to send users to login if not authenticated.
Examples
Basic check for a token cookie. Redirects to login if missing.
NextJS
export function middleware(request) { const token = request.cookies.get('token'); if (!token) { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); }
Protects multiple routes by specifying them in
matcher.NextJS
export function middleware(request) { const token = request.cookies.get('token'); if (!token) { return NextResponse.redirect(new URL('/login', request.url)); } // You can add more checks here return NextResponse.next(); } export const config = { matcher: ['/dashboard/:path*', '/settings/:path*'], };
Sample Program
This middleware checks if a user has a 'token' cookie when they try to access any page under '/profile'. If no token is found, it sends them to the login page. Otherwise, it lets them continue.
NextJS
import { NextResponse } from 'next/server'; export function middleware(request) { const token = request.cookies.get('token'); if (!token) { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); } export const config = { matcher: ['/profile/:path*'], };
OutputSuccess
Important Notes
Middleware runs on the server before the page loads.
Cookies are a common way to store authentication tokens.
Use the matcher config to limit middleware to specific routes for better performance.
Summary
Middleware checks user identity before showing pages.
Redirect users to login if they are not authenticated.
Use matcher to protect only certain routes.