Next JS Middleware Complete Guide

Next JS Middleware
Spread the love

Welcome to the world of Next JS middleware! If you’re new to web development using Next JS, you might have come across the term “middleware” but are unsure of what it is and how it can be used in your application. But don’t worry, we’re here to help you understand its role in your application.

Next JS v12 introduced middleware, which has since been improved in Next JS v13. In the latest version, middleware can be used to directly respond to requests without the need to go through the route handler. This can improve performance and security. Moreover, middleware can be utilized to work with Vercel Edge Functions.

Next JS Guide For Beginners

What is Next JS Middleware?

Middleware functions as a bridge for different parts of web applications, acting as a series of filters or handlers that block incoming requests before they reach their final destination.

Imagine yourself at a fancy restaurant. Before your order is sent to the chef, it goes through different stations. A waiter takes your order, a wine expert suggests wine pairings and a sous chef prepares the ingredients. Each step adds something to the process, confirming that your meal is just right when it finally arrives at your table. This is similar to how middleware works in a web application.

How is Middleware Used in Next JS?

In Next JS, you can use middleware functions to manage different tasks such as authentication, error handling, logging, and more. These functions intercept requests before they reach your API routes or pages, allowing you to perform operations like checking if a user is logged in or logging details about incoming requests.

If you have a Next JS application that requires authentication, you can implement middleware to verify if a user is authenticated before granting them access to specific pages. If a user is not authenticated, you can redirect them to a login page or display a message asking them to log in.

Middleware can also serve logging purposes. You can write a middleware function that logs details about each request, including the URL, request method, and timestamp. This information can be of great value in debugging issues or analyzing traffic patterns in your application.

Advantages and disadvantages of middleware

Middleware is a powerful tool that allows you to improve the functionality of your application without making changes to the code. This means that you can easily add new features or address any bugs without having to deploy a new version of the application. Also, middleware can help you scale your application by distributing tasks to other servers.

This middleware can improve performance and add security features to your application, reducing the load on servers, protecting from attacks and unauthorized access.

Although there are numerous benefits of including middleware into your application, there are also some drawbacks to it. One of the major weaknesses of middleware is that it can make your application more complex, which can make it challenging to develop, deploy, and maintain. Also, middleware can increase the overall cost of your application as you need to purchase and maintain the middleware software.

Creating middleware in Next JS

Define Middleware in the root of your project with middleware.ts (or middleware.js). Place it at the same level as pages or app, or inside src if applicable.

import { NextResponse } from 'next/server'
 
// This function can be marked `async` if using `await` inside
export function middleware(request) {
  return NextResponse.redirect(new URL('/home', request.url))
}
 
// See "Matching Paths" below to learn more
export const config = {
  matcher: '/about/:path*',
}

NextResponse API

NextResponse is an API in Next JS that provides methods for handling responses in Middleware. It allows you to redirect requests, set headers, cookies, and more.

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

export function myMiddleware(request: NextRequest) {
  // Redirect to different URL
  return NextResponse.redirect('/new-url-hello');
  // Rewrite response to display content from different URL
  return NextResponse.rewrite('/new-content');
  // Set response headers and cookies
  const response = NextResponse.next();
  response.headers.set('X-Custom-Header', 'Custom Header');
  response.cookies.set('cookie', 'example');
  return response;
}

Using middleware in Next JS

Next JS middleware functions have access to both incoming requests and responses. These objects can be modified to tailor the application’s behavior.

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

export function authenticationMiddleware(request: NextRequest) {
  // Check if the user is authenticated
  if (!request.headers.cookie?.includes('authenticated=true')) {
    return NextResponse.redirect('/login');
  }
  return NextResponse.next(); // Continue to the next Middleware or route handler
}

Setup Header to response

Middleware can modify headers and cookies for incoming requests and outgoing responses, which is helpful for tasks like customizing the response or managing user sessions.

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

export function customHeadersMiddleware(request: NextRequest) {
  const response = NextResponse.next();
  response.headers.set('X-Custom-Header', 'My Custom Header');
  response.cookies.set('cookie', 'value of cookie');
  return response;
}

Make your custom response

Middleware can return Response or NextResponse instance to control client response with custom logic.

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

export function customResponseMiddleware(request: NextRequest) {
  if (/* user has is not admin */) {
    return new Response('You are not authorize for this page', { status: 400 });
  }
  return NextResponse.next();
}

CORS in Next JS Middleware

You can enable cross-origin requests by setting CORS headers in Middleware, including simple and preflighted requests.

import { NextResponse } from 'next/server'
 
const allowedOrigins = ['https://acme.com', 'https://my-app.org']
 
const corsOptions = {
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type, Authorization',
}
 
export function middleware(request) {
  // Check the origin from the request
  const origin = request.headers.get('origin') ?? ''
  const isAllowedOrigin = allowedOrigins.includes(origin)
 
  // Handle preflighted requests
  const isPreflight = request.method === 'OPTIONS'
 
  if (isPreflight) {
    const preflightHeaders = {
      ...(isAllowedOrigin && { 'Access-Control-Allow-Origin': origin }),
      ...corsOptions,
    }
    return NextResponse.json({}, { headers: preflightHeaders })
  }
 
  // Handle simple requests
  const response = NextResponse.next()
 
  if (isAllowedOrigin) {
    response.headers.set('Access-Control-Allow-Origin', origin)
  }
 
  Object.entries(corsOptions).forEach(([key, value]) => {
    response.headers.set(key, value)
  })
 
  return response
}
 
export const config = {
  matcher: '/api/:path*',
}

In Next JS Middleware you can configure CORS headers in individual routes

Conclusion

Next JS middleware is a powerful tool that enhances the functionality, security, and performance of web applications. It works by intercepting incoming requests before they reach their final destination. This allows you to perform various tasks like authentication, logging, and managing cross-origin requests. Middleware streamlines the development process by enabling modular and reusable code. It also empowers you to address a wide range of requirements without extensive modification of existing codebases. In conclusion, Next JS middleware is an essential tool for any developer looking to improve the quality of their web applications.

FAQs

What is Next jS middleware?

Next JS middleware acts as a bridge between different parts of web applications, intercepting incoming requests before they reach their final destination. It allows for tasks like authentication, logging, and request filtering.


Spread the love

Similar Posts