Learn Nest.js Middleware

take your code to the next() level

JT Earl
4 min readOct 19, 2019

What is it?

I view middleware as a layer of code that sits between a request and a response on a web server. Middleware can:

  • execute code
  • make changes to request and response objects
  • return a response
  • continue the request-response cycle by calling another middleware

How does it work in Nest.js?

Nest.js builds on top of Express. If you understand how to use middleware in Express you can apply many of those same concepts to Nest. You can implement Nest middleware as a class or in a function (also known as functional middleware). I almost always create my middleware in a class. Implementing in a class lets me organize all my middleware in a specific folder. Keeping middleware in classes feels a little closer to the single responsibility principle than having them in modules.

If you create your middleware in a class you will need to use the @Injectable() decorator. @Injectable() lets you use dependency injection to apply your middleware. Your middleware class will also need to implement the NestMiddleware.

If you decide to go the function route instead of creating a class Nest doesn’t have any…

--

--

JT Earl

Programmer Since 17. Currently working in front-end and mid-tier programming for a finance company. Check out my Tech blog @ documentobject.com