Next JS File Conventions: middleware.js
Last Updated :
02 Sep, 2024
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
Next.js File Conventions: layout.js
In Next.js, the layout.js file is a key component in the app directory, allowing developers to create shared UI elements that persist across multiple routes. This feature is part of the Next.js App Router, introduced to improve the organization and efficiency of React applications.Purpose of layout.
4 min read
File Conventions in Next.js
The Next.js file conventions include specific directories and filenames like pages, app, layout.js, and middleware.js, which automatically define routes, layouts, middleware, and other configurations, ensuring a structured and efficient project organization.In this article, we will learn about the d
5 min read
Next.js File Conventions: page.js
Next.js File Conventions are practices and rules for organizing files in a Next.js application to manage routing and components efficiently. In these conventions, the page.js file represents a specific route in the application, where each file in the pages or app directory corresponds to a route. Th
4 min read
Next JS File Conventions: route.js
In Next.js, the route.js file plays a crucial role in the App Router (introduced in Next.js 13) by defining and managing routing configurations. This file helps in customizing the behavior of routes, including rendering components, handling dynamic segments, and applying middleware.In this article,
3 min read
Next JS File Conventions: error.js
Next.js manages file conventions to perform error handling within your application. By using error.js, you can define how your application responds to errors at the page or application level. This file allows you to create custom error pages that handle exceptions gracefully and provide users with a
4 min read
Edge Functions and Middleware in Next JS
Next JS is a React-based full-stack framework developed by Vercel that enables functionalities like pre-rendering of web pages. Unlike traditional react apps where the entire app is loaded on the client. Next.js allows the web page to be rendered on the server, which is great for performance and SEO
3 min read
Next JS File Conventions: default.js
Default.js is a very important file in Next.js projects, serving as a default entry point of the project. Also, while using Next.js, sometimes you soft navigate (move between pages without fully reloading the page). In that case, Next.js keeps track of the pages you were on. However, In case of hard
4 min read
Next JS File Conventions: not-found.js
Next.js not-found.js allows you to create a "Not Found" UI for your application which is rendered whenever the "notFound" function is thrown within a route segment. This file is designed to display a custom "Page Not Found" message when users navigate to non-existent routes within your application.N
4 min read
Middlewares in Next.js
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.Table of ContentMiddleware in Next.jsConv
7 min read
Next.js next.config.js File
The next.config.js file in a Next.js application is a configuration file used to customize and extend the behavior of Next.js. It allows developers to adjust various settings such as routing, environment variables, image optimization, and more to tailor the application to their specific needs.What i
3 min read