Open In App

Next JS File Conventions: middleware.js

Last Updated : 02 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Next.js, the middleware.js file is one powerful tool to add custom functionality through the request/response cycle of the application. It is able to run some code before finalizing a request, which may involve actions such as authentication, logging, or even rewriting of URLs. Middleware can be applied globally, per route, or even to groups of routes.

What is middleware.js?

middleware.js in Next.js allows you to execute code before a request is completed. It provides a way to control the flow of requests, modify incoming requests or responses, and even redirect users based on certain conditions. Middleware runs before the request reaches the final destination, such as a page component or API route.

Syntax:

Here's a basic syntax example of a middleware function:

import { NextResponse } from 'next/server';

export function middleware(request) {
// Middleware logic here
return NextResponse.next();
}

Middleware Function

The middleware function is the core of middleware.js. It receives the request object as an argument and is expected to return a NextResponse object, which determines the outcome of the request.

Syntax:

export function middleware(request) {
// Example: logging the request URL
console.log('Request URL:', request.url);

// Example: redirecting based on the path
if (request.nextUrl.pathname === '/old-path') {
return NextResponse.redirect('/new-path');
}

return NextResponse.next();
}

Config Object (Optional)

You can optionally export a config object to define specific behaviors for your middleware, such as applying it to specific routes.

Syntax:

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

Matcher

Explanation:

The matcher property in the config object specifies which routes the middleware should apply to. It uses a pattern matching syntax to target specific paths.

Syntax:

export const config = {
matcher: ['/about/:path*', '/dashboard/:path*'],
};

Params

Params allows you to extract dynamic parameters from the URL in your middleware.

Syntax:

export function middleware(request) {
const { params } = request.nextUrl;
console.log('Dynamic segment:', params.path);

return NextResponse.next();
}

Request

The request object in middleware.js represents the incoming HTTP request and provides detailed information about it. This object is crucial for performing operations like logging, validation, and modification of requests.

Syntax:

export function middleware(request) {
console.log('Request method:', request.method);

return NextResponse.next();
}

NextResponse

The NextResponse class in Next.js makes it easy to create and manage HTTP responses when using middleware. With NextResponse, you can handle things like redirects, rewrites, or custom responses right in your middleware code. It simplifies how you manage responses, making the code cleaner and more straightforward to understand.

Syntax:

export function middleware(request) {
return NextResponse.redirect('/new-path');
}

Runtime

The middleware runtime is determined by the environment where your Next.js app is running. Middleware can be run in Edge Functions, which are optimized for low-latency, or in the Node.js runtime.

Syntax:

export const config = {
runtime: 'edge', // 'nodejs' for Node.js runtime
};

Version History

Middleware was introduced in Next.js 12, offering new ways to control the flow of requests. Each subsequent version has introduced improvements and bug fixes related to middleware.

Primary Terminology :

  • Middleware: A code that will run just before a request is fully processed, so that you can either modify the request or response. Middleware executes before server-side logic or API Routes are handled in Next.js.
  • NextResponse: It is a helper class provided by Next.js that can easily manipulate the response, in your middleware, like redirections and header modifications.
  • Request Object: An object that represents an incoming HTTP request: it includes details such as URL, headers, and the body of the request. Request objects are passed into middleware functions.
  • Next.js API Routes: Server-side functions in Next.js to handle the HTTP requests. Used very widely to create APIs within a Next.js application.
  • Page Component (page.tsx): The most important component in a Next.js app. It defines the content and layout for a particular route.

Steps to Create a Next.js Application

Install Node.js and npm:

  • Ensure you have Node.js installed on your machine. You can download it from Node.js official website. npm (Node Package Manager) is included with Node.js.

Create a New Next.js Application:

  • Open your terminal or command prompt.
  • Navigate to the directory where you want to create your project.
  • Run the following command to create a new Next.js application:
  • Initialize a New Next.js Project by using below command
npx create-next-app@latest my-nextjs-app --typescript

Select the Prefered options:

√ Would you like to use TypeScript? ... Yes
√ Would you like to use ESLint? ... Yes
√ Would you like to use Tailwind CSS? ... Yes
√ Would you like to use `src/` directory? ... Yes
√ Would you like to use App Router? (recommended) ... Yes
√ Would you like to customize the default import alias (@/*)? ... No

After the project is created, navigate to the project directory:

cd my-nextjs-app

Project Structure:

Middleware_project_structure

the updated dependencies in package.json file are:

"dependencies": {
"next": "14.2.5",
"react": "^18",
"react-dom": "^18"
},
"devDependencies": {
"@types/react": "18.3.4",
"eslint": "^8",
"eslint-config-next": "14.2.5",
"postcss": "^8",
"tailwindcss": "^3.4.1"
}

Set Up Middleware:

Create a middleware.js file inside the src/ directory

JavaScript
// src/middleware.js
import { NextResponse } from 'next/server';
export function middleware(request) {
  if (request.nextUrl.pathname.startsWith('/old-path')) {
    const url = new URL('/new-path', request.url);
    return NextResponse.redirect(url);
  }

  return NextResponse.next();
}
JavaScript
// src/app/page.js
import React from 'react';
import ExampleComponent from '../components/ExampleComponent';

const Page = () => {
  return (
    <div className="container mx-auto p-4">
      <h1 className="text-3xl font-bold text-center mb-6">Welcome to My Next.js App</h1>
      <ExampleComponent />
    </div>
  );
};

export default Page;
JavaScript
// src/components/ExampleComponent.tsx
import React from 'react';
import Link from 'next/link';

const ExampleComponent = () => {
  return (
    <div className="bg-gray-100 p-4 rounded shadow-md">
      <h2 className="text-2xl font-semibold mb-4" style={{color:"black"}}>Example Component</h2>
      <p className="mb-4" style={{color:"black"}}>
        This is an example component that demonstrates how to use components within a Next.js application.
      </p>
      <Link href="/old-path">
        <a className="text-blue-500 hover:underline">Go to Old Path</a>
      </Link>
    </div>
  );
};

export default ExampleComponent;
JavaScript
// src/app/new-path/page.tsx:
export default function NewPathPage() {
  return (
    <div>
      <h1>Welcome to the New Path</h1>
      <p>This is the new path page.</p>
    </div>
  );
}


Explanation:

  • The Page component is the main component for your application. It serves as the entry point and includes a heading and the ExampleComponent.
  • The layout is styled using Tailwind CSS classes, which provide responsive and modern design out of the box.
  • The ExampleComponent includes a heading, a paragraph of text, and a link.
  • The link uses Next.js’s Link component to navigate to the /old-path route, which will trigger the middleware and redirect to /new-path.
  • Tailwind CSS is also used here for styling, making it easy to create a consistent design.

Output:

Conclusion

Middleware is very powerful in Next.js, and you will be able to handle a request before it even reaches your server-side logic. Regardless of whether you are redirecting the users, handling the authentication, or logging requests, middleware provides the flexibility for you to control the flow of an application at a low level. Through effective understanding and implementation of middleware, one can easily optimize their Next.js application towards improved performance and greater user experience.


Next Article

Similar Reads