0
0
NextjsHow-ToBeginner · 3 min read

How to Protect Pages in Next.js: Simple Authentication Methods

To protect pages in Next.js, use middleware for server-side route guarding or implement client-side authentication checks with React hooks like useEffect. Middleware runs before rendering and can redirect unauthorized users, while client-side checks control access after page load.
📐

Syntax

Next.js page protection mainly uses middleware or client-side authentication checks. Middleware is a special file named middleware.js or middleware.ts placed in the root or src folder. It intercepts requests and can redirect users based on authentication status.

Client-side protection uses React hooks like useEffect to check user login state and redirect if unauthorized.

javascript
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();
}
💻

Example

This example shows how to protect a page using middleware that checks for a cookie named token. If the token is missing, the user is redirected to the login page. Otherwise, the page loads normally.

javascript
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: ['/protected/:path*'],
};
Output
User visiting '/protected/dashboard' without 'token' cookie is redirected to '/login'. With 'token', the page loads normally.
⚠️

Common Pitfalls

  • Not using middleware or client-side checks together can leave pages unprotected.
  • Forgetting to set the matcher config in middleware means it won't run on desired routes.
  • Relying only on client-side checks is insecure because users can bypass them by disabling JavaScript.
  • Not handling token expiration or invalid tokens can cause unauthorized access.
javascript
/* Wrong: Middleware without matcher - runs on all routes, may cause issues */
export function middleware(request) {
  const token = request.cookies.get('token');
  if (!token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}

/* Right: Specify matcher to protect only certain routes */
export const config = {
  matcher: ['/protected/:path*'],
};
📊

Quick Reference

  • Middleware: Runs before page loads, good for secure redirects.
  • Client-side checks: Use useEffect to redirect if user not logged in.
  • Cookies or tokens: Store auth info securely, check in middleware or client.
  • Redirect unauthorized users: Send them to login or error pages.

Key Takeaways

Use Next.js middleware to protect pages server-side by redirecting unauthorized users.
Always specify the matcher config in middleware to target specific routes.
Combine middleware with client-side checks for better user experience and security.
Never rely only on client-side checks as they can be bypassed.
Store authentication tokens securely and validate them before granting access.