Next JS Middleware: Extending Functionality in Your Application
Last Updated :
02 Aug, 2024
Middleware plays an important role in creating backend applications which are used to intercept incoming requests, perform actions, and modify responses before send to routing handlers. In this article, we will understand middleware in Next.js by creating an authentication middleware.
Prerequisites
What are Middlewares?
Middleware is a piece of code that redefines the functionality of your written logic. It enhances the logic and provides an additional capability. It has access to the request object (req
), the response object (res
), and the next
function in the application's request-response cycle. Middleware modifies a request before it reaches the destination. It is very helpful in performing tasks like authentication and data manipulation.
Syntax:
// Define your middleware function
const myMiddleware = (req: Request, res: Response, next: NextFunction) => {
// Middleware logic
console.log('Middleware executed');
// Call the next middleware function in the stack
next();
};
Functioning of a Middleware
- HOC Initialization - When using a middleware function with a component, the middleware function runs first.
- Middleware Logic - Middleware contains special logic related to middleware purposes. This logic may be authentication, authorization, or data fetching.
- Component Rendering - After the middleware logic runs, it decides whether to render a wrapped component or not.
- Conditional Rendering - If the middleware allows, the wrapped component is rendered with necessary props.
- Redirect or Alternative rendering - If the middleware logic denies rendering the wrapped component, the middleware performs a redirect to another page, an alternative component.
Example: In this example, We will secure the profile page within an authentication middleware with the help of a higher-order component (HOC) to envelop the profile page component. This higher-order component will interfere with the request to the profile page, ensuring that only users with valid credentials can access it.
Steps to Create a Next.js app
Step 1: Create a Next.js app by using the command provided below.
npx create-next-app next-middleware

Enter into the app directory created.
cd next-middleware
Step 2: Create the required files and folders as suggested in file structure.
File Structure:
file structureThe updated dependencies in package.json file will look like:
"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.1.0"
},
"devDependencies": {
"autoprefixer": "^10.0.1",
"postcss": "^8",
"tailwindcss": "^3.3.0"
}
Example: Add the following codes in the respective files.
JavaScript
//authMiddleware.js
import React, { useEffect, useState } from "react";
import { useRouter } from "next/router";
const authMiddleware = (WrappedComponent) => {
const AuthComponent = (props) => {
const router = useRouter();
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
// Check for your authentication criteria here
const username = localStorage.getItem("username");
const password = localStorage.getItem("password");
if (username === "geeksforgeeks" && password === "1234") {
setIsAuthenticated(true);
} else {
router.replace("/login");
}
}, []);
if (isAuthenticated) {
return <WrappedComponent {...props} />;
} else {
return null;
}
};
return AuthComponent;
};
export default authMiddleware;
JavaScript
//Profile.js
import React from 'react'
import authMiddleware from '../middlewares/authMiddleware'
const profile = () => {
return (
<div className='max-w-sm mx-auto mt-12
text-3xl bg-blue-400 text-white
shadow-3xl rounded-xl border p-10'>
<h1>
Hi I am the User, and I am Logged In
</h1>
</div>
)
}
export default authMiddleware(profile)
JavaScript
//Login.js
import { useState } from "react";
import { useRouter } from "next/router";
const Login = () => {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const router = useRouter();
const handleLogin = () => {
// Check the username and password and perform login logic
localStorage.setItem("username", username);
localStorage.setItem("password", password);
// Redirect to the profile page
router.push("/profile");
};
const handleKeyPress = (e) => {
if (e.key === "Enter") {
handleLogin();
}
};
return (
<div className="flex flex-col max-w-sm mt-12 space-y-3 mx-auto">
<h1 className="text-gray-600 text-2xl">Login</h1>
<input
className="border p-2"
placeholder="Enter username"
value={username}
onChange={(e) => setUsername(e.target.value)}
onKeyPress={handleKeyPress}
/>
<input
className="border p-2"
placeholder="Enter password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
onKeyPress={handleKeyPress}
/>
<button
onClick={handleLogin}
className="border p-2 focus:bg-white focus:text-gray-400
focus:border bg-sky-600 text-white"
>
Submit
</button>
</div>
);
};
export default Login;
Step 3: To start the application run the following codes.
npm run dev
Output:
Similar Reads
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
Built-in Middleware Functions in Express.js
Express.js is a Node.js framework used to develop the backend of web applications. While you can create custom middleware in Express.js using JavaScript, Express.js also provides several built-in middleware functions for use in Express applications. Middleware are functions that are executed when ca
4 min read
Next JS File Conventions: middleware.js
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
7 min read
Difference between application level and router level middleware in Express?
If youâve used Express even a little, you know how important middleware is. Those little functions run on every request and let you do stuff like logging, authentication, file uploads, and more. In this article, we will see what is Application-level middleware and Router-level middleware and what ar
3 min read
Introduction to ALE(Application Link Enabling) in SAP
We often come across some terminology such as SAP HANA, SAP EDI, SAP ALE, SAP ABAP, SAP CO, and other SAP-related products. In this article, we would like to focus on ALE(Application Link Enabling) in SAP. It is an emerging technology for remote connections that enables business processes to be dece
7 min read
What is the role of next(err) in error handling middleware in Express JS?
Express is the most popular framework for Node.js which is used to build web-based applications and APIs. In application development, error handling is one of the important concepts that provides the aspect to handle the errors that occur in the middleware. The middleware functions have access to th
4 min read
How to Set Up Custom Middleware in Django?
One of the key and must feature of Django is the concept of middleware, which allows us to process requests and responses across the entire web application. Middleware in Django acts as a layer between the requests and view or between the view and the response, including it's useful for tasks like l
5 min read
Creating custom middlewares in React Redux
In React-Redux applications, managing the flow of data is crucial for building efficient and scalable apps. Redux provides a powerful state management solution, and custom middleware adds an extra layer of flexibility to handle complex scenarios effectively. Let's understand custom middleware in sim
5 min read
Optimize Your NestJS Applications
NestJS is a popular framework for building scalable and maintainable server-side applications with Node.js. NestJS offers many out-of-the-box features to enhance performance. In this article, we will cover several key techniques, tools, and best practices to ensure your NestJS application runs effic
4 min read
What is The Difference Between Interceptor, Middleware and Filter in Nest.js?
Nest.js is a popular framework for building server-side applications in Node.js. While working with Nest.js, we'll often come across terms like Interceptor, Middleware, and Filter. These are important concepts that help in managing requests, responses, and errors in your application. What is Middlew
5 min read