Skip to main content

Command Palette

Search for a command to run...

Using Middleware in Next.js

Updated
3 min read
Using Middleware in Next.js
S

Full-stack developer with a passion for building scalable web applications using Next.js, TypeScript, and modern technologies. Experienced in ServiceNow development and scripting. Sharing knowledge and insights on web development and programming.

Middleware in Next.js allows you to run code before a request is completed. It’s a powerful tool for tasks like authentication, logging, redirects, and more. With middleware, you can enhance your application’s behavior on both server-side and edge functions, improving performance and user experience.


What is Middleware in Next.js?

Middleware is a function that executes during the request lifecycle. It allows you to modify the request or response before it reaches its destination.

Key Features:

  • Runs on Edge: Middleware executes on Vercel’s Edge Network for optimal performance.

  • Dynamic Control: Modify responses, redirect users, or authenticate requests dynamically.

  • File-Based: Like routes, middleware is file-based.


Creating Your First Middleware

Step 1: Add a Middleware File

Middleware is defined in a middleware.ts file at the root of your src directory.

src/middleware.ts

Step 2: Define Your Middleware Logic

Here’s an example of middleware that redirects users who are not logged in to a login page:

import { NextRequest, NextResponse } from 'next/server';

export function middleware(request: NextRequest) {
  const isAuthenticated = request.cookies.get('auth-token');

  if (!isAuthenticated) {
    return NextResponse.redirect(new URL('/login', request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/dashboard/:path*'], // Apply middleware to specific routes
};

Explanation:

  • NextRequest: Represents the incoming request.

  • NextResponse: Used to send responses like redirects or modifications.

  • matcher: Specifies the routes where the middleware should apply.


Use Case: Authentication Middleware

One common use case for middleware is protecting routes that require authentication.

Example:

import { NextRequest, NextResponse } from 'next/server';

export function middleware(request: NextRequest) {
  const token = request.cookies.get('auth-token');

  if (!token) {
    return NextResponse.redirect(new URL('/signin', request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/profile/:path*', '/settings/:path*'],
};
  • If the auth-token cookie is missing, the user is redirected to the /signin page.

  • Middleware is applied to routes like /profile and /settings.


Use Case: Redirect Middleware

You can use middleware to dynamically redirect users based on conditions, such as locale or device type.

Example:

import { NextRequest, NextResponse } from 'next/server';

export function middleware(request: NextRequest) {
  const country = request.geo?.country || 'US';

  if (country === 'FR') {
    return NextResponse.redirect(new URL('/fr', request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/'],
};
  • request.geo: Provides geolocation information.

  • Users from France (FR) are redirected to a localized /fr page.


Debugging Middleware

To debug your middleware, use console.log() statements. However, remember that middleware runs on the Edge, so logs appear in the Vercel dashboard or terminal during local development.


Limitations of Middleware

  • Middleware does not have access to environment variables.

  • Middleware cannot fetch data from APIs.

  • Middleware runs before static files are served, so it won’t apply to images or other public assets.


Conclusion

Middleware in Next.js provides a versatile way to handle authentication, redirection, and more. By running code before requests are completed, you can enhance your app’s functionality and user experience. Start experimenting with middleware today to see how it can streamline your Next.js applications!

More from this blog

S

Strnge Blogs

27 posts

Welcome to my Hashnode blog! I'm a passionate technologist with a background in web dev. Through my blog, I aim to share insights and thoughts on various tech topics that intrigue me.