Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Set Up Custom Middleware in Django?
Next article icon

Middleware in NestJS: Implementing Custom Middleware for Request Processing.

Last Updated : 19 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Middleware in NestJS plays an important role in intercepting and processing HTTP requests before they reach route handlers. It allows developers to execute code logic before or after handling a request, making it a powerful tool for managing cross-cutting concerns such as logging, authentication, error handling, and more.

In this article, we will explore how to implement custom middleware in NestJS to enhance the functionality of your applications.

Prerequisites

  • Node.js and npm installed.
  • Basic knowledge of TypeScript.
  • NestJS CLI installed (npm install -g @nestjs/cli).

Understanding Middleware in NestJS

Middleware functions in NestJS are functions or classes that are invoked during the request-response cycle. They have access to the request and response objects as well as the next function, which is used to pass control to the next middleware function or route handler.

Middleware can be used for various purposes:

  • Logging: Capture information about incoming requests or outgoing responses.
  • Authentication: Verify the identity of users before allowing access to protected routes.
  • Error Handling: Catch and process errors that occur during request processing.
  • Request Processing: Modify request or response objects before they reach route handlers.

Types of Middleware in NestJS

NestJS supports three types of middleware:

  • Function Middleware: Simple functions that accept the request, response, and next function as arguments.
  • Middleware Classes: ES6 classes that implement the NestMiddleware interface. These classes can inject dependencies through the constructor and are more structured and reusable.
  • Route-scoped Middleware: Applied to specific routes or controllers using the @Use decorator.

Steps to Implement Middleware in NestJS

Step 1: Setup a Nest.js Project

First, ensure you have Node.js and npm installed. Then, install the Nest CLI if you haven't already:

npm install -g @nestjs/cli

Step 2: Create a new NestJS project:

nest new nest-gfg

Step 3: Navigate to the project directory:

cd nest-gfg

Step 4: Creating a Simple Middleware

Generate a new controller using the Nest CLI:

nest generate middleware logger

Folder Structure

ewret
Folder Structure

Dependencies

"dependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/mongoose": "^10.0.10",
"@nestjs/platform-express": "^10.0.0",
"dotenv": "^16.4.5",
"mongoose": "^8.5.1",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1"
}

Example: Implementing the basic middleware.

JavaScript
// src/app.module.ts  import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { LoggerMiddleware } from './logger/logger.middleware';  @Module({     imports: [],     controllers: [AppController],     providers: [AppService], }) export class AppModule implements NestModule {     configure(consumer: MiddlewareConsumer) {         consumer.apply(LoggerMiddleware).forRoutes('*');     } } 
JavaScript
// src/logger.middleware.  import { Injectable, NestMiddleware } from '@nestjs/common'; import { Request, Response, NextFunction } from 'express';  @Injectable() export class LoggerMiddleware implements NestMiddleware {     use(req: Request, res: Response, next: NextFunction) {         console.log(`Request...`);         console.log(`Method: ${req.method}`);         console.log(`URL: ${req.url}`);         next();     } } 

Output

etwrtt
Middleware in NestJS: Implementing Custom Middleware for Request Processing.

Next Article
How to Set Up Custom Middleware in Django?

S

sharmaroqty
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • NestJS

Similar Reads

  • Implementing Csurf Middleware in Node.js
    Csurf middleware in Node.js prevents the Cross-Site Request Forgery(CSRF) attack on an application. By using this module, when a browser renders up a page from the server, it sends a randomly generated string as a CSRF token. Therefore, when the POST request is performed, it will send the random CSR
    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
  • Writing Custom middlewares in React Redux
    Custom middleware in React Redux is like having a helper that can do things with actions before they're handled by our app. It allows us to intercept actions and apply custom logic before they reach the reducers. In this article, we are going to discuss how it is done. Table of Content What is Redux
    5 min read
  • Common middleware libraries used in Redux
    Middleware libraries play a crucial role in Redux applications, enabling users to extend and enhance Redux's capabilities. The middleware libraries offer a wide range of capabilities and cater to different use cases and preferences. users can choose the middleware that best fits their requirements a
    5 min read
  • Explain the concept of middleware in NodeJS
    Middleware in NodeJS refers to a software design pattern where functions are invoked sequentially in a pipeline to handle requests and responses in web applications. It acts as an intermediary layer between the client and the server, allowing for modularization of request processing logic and enabli
    2 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
  • 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
  • API Response Caching using apicache Middleware in Node.js
    APIs are a crucial part of modern web applications, providing the means for different software systems to communicate and exchange data. However, frequent API calls, especially to the same endpoints, can lead to increased server load, slower response times, and higher bandwidth usage. Caching is a s
    4 min read
  • How to Build Middleware for Node JS: A Complete Guide
    NodeJS is a powerful tool that is used for building high-performance web applications. It is used as a JavaScript on runtime environment at the server side. One of Its key features is middleware, which allows you to enhance the request and response object in your application. Building middleware for
    5 min read
  • Next JS Middleware: Extending Functionality in Your Application
    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. PrerequisitesJ
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences