Middlewares in Next.js provide a powerful mechanism to execute custom code before a request is completed. They enable you to perform tasks such as authentication, logging, and request manipulation, enhancing the functionality and security of your application.
Middleware in Next.js
Middleware is a mechanism that is used to perform tasks before rendering a page. It allows you to intercept requests before they reach the page component. It enables you to perform operations like authentication, authorization, data fetching, and modifying the request or response objects.
In Next.js, middleware functions are executed before the request reaches the final route handler. They can be used to intercept and modify requests and responses. Middleware is defined in the middleware.js file at the root of your project. It allows you to write custom logic for tasks like authentication, rate limiting, and more. Middleware runs on the Edge Runtime, ensuring low latency and high performance.
Convention
In Next.js, you can implement middleware by creating middleware.js (or .ts) file in a project root directory(you have to create a middleware.js file inside src folder.).
You can only create a one middleware.js (or .ts) file per project, but you can still divide it's logic in a different modules.
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
return NextResponse.redirect(new URL('/home', request.url))
}
// See "Matching Paths" below to learn more
export const config = {
matcher: '/about/:path*',
}
Matching Paths
The middleware file will be invoked for every route in your project, If you want to apply to any specific route then you have to mention a route matcher inside middleware.js file
route matcher (specific path):
...Main Middleware Function....
......
export const config = {
matcher: '/profile/:path*',
}
route matcher (multiple path):
...Main Middleware Function....
......
export const config = {
matcher: [ '/profile/:path*', '/about/:path*' ]
}
Syntax:
import { NextResponse } from 'next/server'
export function middleware(request) {
return NextResponse.redirect(new URL('/home', request.url))
}
//Matching Path
export const config = {
matcher: '/about/:path*',
}
NextResponse
The NextResponse API empowers you to:
- Redirect incoming requests to an alternate URL.
- Revise responses by showcasing a specified URL.
- Configure request headers for API Routes, getServerSideProps, and rewrite destinations.
- Implement response cookies.
- Define response headers.
For generating a response from Middleware, you can:
- Rearrange to a route (Page or Route Handler) responsible for generating a response.
- Directly yield a NextResponse. Refer to the section on Producing a Response.
Using Cookies
Cookies function as standard headers. During a request, they reside in the Cookie header, while in a response, they are located within the Set-Cookie header. Next.js simplifies cookie management with its cookies extension on NextRequest and NextResponse.
For incoming requests, cookies offer the following methods: get, getAll, set, and delete, enabling you to retrieve, manipulate, and remove cookies. You can verify the presence of a cookie with has or clear all cookies with remove.
For outgoing responses, cookies provide methods such as get, getAll, set, and delete, facilitating the handling and modification of cookies before sending the response.
import { NextResponse } from 'next/server';
export function middleware(request) {
// Assume a "Cookie:nextjs=fast" header to be present on the incoming request
// Getting cookies from the request using the `RequestCookies` API
let cookie = request.cookies.get('nextjs');
console.log(cookie); // => { name: 'nextjs', value: 'fast', Path: '/' }
const allCookies = request.cookies.getAll();
console.log(allCookies); // => [{ name: 'nextjs', value: 'fast' }]
request.cookies.has('nextjs'); // => true
request.cookies.delete('nextjs');
request.cookies.has('nextjs'); // => false
// Setting cookies on the response using the `ResponseCookies` API
const response = NextResponse.next();
response.cookies.set('vercel', 'fast');
response.cookies.set({
name: 'vercel',
value: 'fast',
path: '/',
});
cookie = response.cookies.get('vercel');
console.log(cookie); // => { name: 'vercel', value: 'fast', Path: '/' }
// The outgoing response will have a `Set-Cookie:vercel=fast;path=/` header.
return response;
}
Indeed, with the NextResponse API, you can effectively manage both request and response headers. This capability has been available since Next.js version 13.0.0.
import { NextResponse } from 'next/server';
export function middleware(request) {
// Clone the request headers and set a new header `x-hello-from-middleware1`
const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-hello-from-middleware1', 'hello');
// You can also set request headers in NextResponse.rewrite
const response = NextResponse.next({
request: {
// New request headers
headers: requestHeaders,
},
});
// Set a new response header `x-hello-from-middleware2`
response.headers.set('x-hello-from-middleware2', 'hello');
return response;
}
CORS
This middleware function adds CORS headers to the response to allow requests from any origin, methods, and headers. For preflighted requests (OPTIONS method), it responds immediately with appropriate headers and a status code of 200.
import { NextResponse } from 'next/server';
export function middleware(request) {
// Set CORS headers to allow requests from any origin
const response = NextResponse.next();
response.headers.set('Access-Control-Allow-Origin', '*');
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// For preflighted requests, respond immediately with appropriate headers
if (request.method === 'OPTIONS') {
response.status = 200;
return response;
}
// Continue processing other requests
return response;
}
Producing Response
Directly responding from Middleware is supported by returning either a Response or NextResponse instance. This functionality has been available since Next.js version 13.1.0.
import { isAuthenticated } from '@lib/auth';
// Limit the middleware to paths starting with `/api/`
export const config = {
matcher: '/api/:function*',
};
export function middleware(request) {
// Call our authentication function to check the request
if (!isAuthenticated(request)) {
// Respond with JSON indicating an error message
return new Response(
JSON.stringify({ success: false, message: 'authentication failed' }),
{ status: 401, headers: { 'Content-Type': 'application/json' } }
);
}
}
Steps to Setup a NextJS App
Step 1: Create a NextJS application using the following command and answer some few questions.
npx create-next-app@latest app_name
Step 2: After creating your project folder, move to it using the following command.
cd app_name
Project Structure:

Example
The below example demonstrate the use of middleware in next.js.
Note: Remove included CSS file from layout.js.
In this example, we have created a form which will take username and password from the user, When a user submits the form middleware.js file will match the input with the already defined username and password. If it matches then, it procced next and request will be sent to the server(route.js) and it will display Welcome message else it will directly response a Invalid Username & Password message.
JavaScript
//File path: src/app/page.js
export default function Home() {
return (
<>
<h1>Login Page</h1>
<form method="post" action="/submit">
<label>Username</label>
<input type="text"
placeholder="Enter Username"
name="username" required />
<br />
<label>Password</label>
<input type="password"
placeholder="Enter Password"
name="password" required />
<br />
<button type="submit">Submit</button>
</form>
</>
);
}
JavaScript
//File path: src/app/[submit]/route.js
import { NextResponse } from "next/server";
//Handling POST request
export async function POST(req, res) {
//Response
return new NextResponse(`<h1>Welcome</h1>`,
{
status: 200,
headers: { 'content-type': 'text/html' }
}
);
}
JavaScript
//File path: src/middleware.js
import { NextResponse } from "next/server"
export async function middleware(req) {
//Get the Form Data
const Formdata = await req.formData();
let username = Formdata.get('username');
let password = Formdata.get('password');
if (username == "gfg" & password == "123") {
return NextResponse.next()
} else {
return new NextResponse(
`<h1>Invalid Username & Password</h1>`,
{
status: 401,
headers: { 'content-type': 'text/html' }
}
);
}
}
export const config = {
matcher: '/submit/:path*',
}
Start your application using the command:
npm run dev
Output:
Benefits of Middleware
- It can handle user authentication and authorization processes.
- It is used to manage user sessions and handle session creation, tracking, and expiration.
- It is used to validate user input to prevent common security vulnerabilities such as cross-site scripting (XSS), and SQL injection.
- It can add, modify, or remove HTTP headers in incoming or outgoing requests and responses.
- It can be used to redirect users at the server level based on user role.
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.React.jsWhy Use React?Before React, web development faced issues like slow DOM updates
7 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 methods to interact with the Document Object Model or DOM. This package allows developers to access and modify the DOM. Let's see in brief what is the need to have the package. Table of ContentWhat is ReactDOM ?How to use ReactDOM ?Why ReactDOM is used
3 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 ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 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. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.What are Reactjs Functio
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
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