Using Middleware Functions

Learn about middleware functions and how to use them in a Deno application.

If you’ve used any HTTP framework, be it JavaScript or otherwise, you’re probably familiar with middleware functions. If not, no worries—that’s what we’ll explain in this section.

Let’s start with a definition borrowed from the Express.js documentation:

“Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.”

Middleware functions intercept requests and have the ability to act on them. They can be used in many different use cases, as follows:

  • Changing the request and response objects
  • Ending the request-response lifecycle (answering requests or skipping other handlers)
  • Calling the next middleware function

Middleware functions are commonly used in tasks such as checking authentication tokens and automatically responding according to the result, logging requests, adding a specific header to a request, enriching the request object with context, and error handling, among other things.

We’ll implement some of these examples in the application.

Get hands-on with 1200+ tech skills courses.