Next JS File Conventions: middleware.js
Last Updated :
23 Jul, 2025
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
- 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
Navigate to the Project Directory:
After the project is created, navigate to the project directory:
cd my-nextjs-app
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.
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. "Hello, World!" Program in ReactJavaScriptimport React from 'react'; function App() {
6 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides DOM-specific methods to interact with and manipulate the Document Object Model (DOM), enabling efficient rendering and management of web page elements. ReactDOM is used for: Rendering Components: Displays React components in the DOM.DOM Manipulation: Al
2 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsIn lists, React makes it easier to render multiple elements dynamically from arrays or objects, ensuring efficient and reusable code. Since nearly 85% of React projects involve displaying data collectionsâlike user profiles, product catalogs, or tasksâunderstanding how to work with lists.To render a
4 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. When rendering a list, you need to assign a unique key prop to each element in th
4 min read
Components in React
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects