DEV Community

Cover image for Next.js: Creating a Middleware for Advanced Request Handling.
Reme Le Hane
Reme Le Hane

Posted on • Originally published at remejuan.substack.com

Next.js: Creating a Middleware for Advanced Request Handling.

What is Middleware in Next.js?

Middleware is a feature that lets you run logic before a request is completed. You can use it to:

  • Redirect users.

  • Protect routes (authentication).

  • Modify responses.

  • Handle custom headers or logging.


Example: Protecting Routes with Middleware

Imagine you have a dashboard that should only be accessible to authenticated users. Middleware makes it easy to check the authentication token and redirect unauthorized users.

Step 1: Create Middleware

Middleware files must be named middleware.ts and placed in the root of your app.

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

export function middleware(request: NextRequest) {
  // Check for a token in cookies (example: `authToken`)
  const token = request.cookies.get('authToken')?.value;

  // If no token, redirect to login
  if (!token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }

  // Allow request to continue
  return NextResponse.next();
}

// Specify routes where middleware applies
export const config = {
  matcher: ['/dashboard/:path*'], // Apply middleware to all /dashboard routes
};
Enter fullscreen mode Exit fullscreen mode

Step 2: Test Protected Routes

Now, if a user accesses /dashboard or any subpage like /dashboard/settings, they will be redirected to /login unless they have a valid authToken cookie.


Advanced: Custom Headers and Logging

You can also modify the request or response directly in middleware. For example, logging user details or setting custom headers:

export function middleware(request: NextRequest) {
  // Log the user's IP
  console.log('User IP:', request.ip);

  // Add a custom header to the response
  const response = NextResponse.next();
  response.headers.set('X-Custom-Header', 'Middleware Works!');

  return response;
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Debug Middleware

Run your app locally (npm run dev or yarn dev) and try accessing the protected routes. If you’re using cookies, you can simulate adding an authToken in your browser’s dev tools.


Use Cases for Middleware

  1. Authentication and Authorization: Redirect unauthorized users or check user roles.

  2. Localization: Dynamically redirect users based on their location or language preference.

  3. Rate Limiting: Throttle requests to APIs or routes.

  4. Logging and Monitoring: Log request details (e.g., IP address or user agent).

  5. Dynamic Content Delivery: Serve different versions of content based on request headers or cookies.


Why This Is Useful

  • Performance: Middleware runs before rendering, reducing client-side overhead.

  • Scalability: Centralizes logic for route handling and request validation.

  • Security: Helps enforce route protection and authentication without cluttering your page code.

Mastering middleware opens up a whole new layer of possibilities in Next.js for building secure, dynamic, and efficient apps!

Image of Stellar post

How a Hackathon Win Led to My Startup Getting Funded

In this episode, you'll see:

  • The hackathon wins that sparked the journey.
  • The moment José and Joseph decided to go all-in.
  • Building a working prototype on Stellar.
  • Using the PassKeys feature of Soroban.
  • Getting funded via the Stellar Community Fund.

Watch the video

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay