<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Simon Plenderleith</title>
    <description>The latest articles on Forem by Simon Plenderleith (@simonplend).</description>
    <link>https://forem.com/simonplend</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F443047%2F76f1efab-546e-4a44-9e59-421aa6e595f1.jpg</url>
      <title>Forem: Simon Plenderleith</title>
      <link>https://forem.com/simonplend</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/simonplend"/>
    <language>en</language>
    <item>
      <title>Guidelines for choosing a Node.js framework</title>
      <dc:creator>Simon Plenderleith</dc:creator>
      <pubDate>Mon, 04 Oct 2021 09:07:00 +0000</pubDate>
      <link>https://forem.com/simonplend/guidelines-for-choosing-a-node-js-framework-1ifk</link>
      <guid>https://forem.com/simonplend/guidelines-for-choosing-a-node-js-framework-1ifk</guid>
      <description>&lt;p&gt;I often see the question "What’s the best Node.js framework?" crop up on message boards and social media. The replies tend to be full of strong opinions. Some developers will even get into arguments about it. If you’re trying to figure out the right framework for your project, none of this is going to be much help.&lt;/p&gt;

&lt;p&gt;With lots of frameworks to choose from, and all those strong opinions, it’s easy to feel a little lost. Comparing frameworks based on the features they list can be a headache, and features are only part of the picture. It would be awesome if you had a clear checklist you could evaluate Node.js frameworks against.&lt;/p&gt;

&lt;p&gt;I can’t provide you with an exhaustive checklist, as every project, team and developer have different needs. I do have some guidelines though to help you think about what matters to you when choosing a Node.js framework.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Thank you to the following folks who shared &lt;a href="https://twitter.com/simonplend/status/1438479239041404932"&gt;on Twitter&lt;/a&gt; what they consider when choosing a Node.js framework: &lt;a href="https://twitter.com/i_like_robots"&gt;Matt Hinchcliffe&lt;/a&gt;, &lt;a href="https://twitter.com/AlexWilsonV1"&gt;Alex Wilson&lt;/a&gt;, &lt;a href="https://twitter.com/_aantipov"&gt;Alexey Antipov&lt;/a&gt; and &lt;a href="https://twitter.com/58bits"&gt;Anthony Bouch&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Jump links
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;What’s your use case?&lt;/li&gt;
&lt;li&gt;Framework styles&lt;/li&gt;
&lt;li&gt;Support for promises and async / await&lt;/li&gt;
&lt;li&gt;Documentation&lt;/li&gt;
&lt;li&gt;Practical examples&lt;/li&gt;
&lt;li&gt;Community and ecosystem&lt;/li&gt;
&lt;li&gt;Project health&lt;/li&gt;
&lt;li&gt;Conclusion&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What’s your use case?
&lt;/h2&gt;

&lt;p&gt;Context is everything. Try and get clear on your requirements before you start looking at frameworks and their features. This will help you you figure out if a framework is designed to support your intended use case. If it’s not, you could find yourself fighting against it when building your application.&lt;/p&gt;

&lt;p&gt;Here are some use cases you might want to consider:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Full stack application vs API.&lt;/strong&gt; Will your application be serving up HTML pages or will it be an API sending JSON responses? If it’s an API, will it be &lt;a href="https://en.wikipedia.org/wiki/Representational_state_transfer"&gt;REST&lt;/a&gt; or &lt;a href="https://graphql.org/"&gt;GraphQL&lt;/a&gt; based?&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Server-side rendering.&lt;/strong&gt; Do you plan to use React or Vue components in your application? Some frameworks provide helpers to simplify integrating these frameworks in your applications.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Serverless.&lt;/strong&gt; Will you be deploying your application to a serverless platform? For some serverless platforms like AWS Lambda, &lt;a href="https://www.techtalksbyanvita.com/post/serverless-cold-starts-can-we-mitigate-these"&gt;cold start time&lt;/a&gt; really matters. If a framework has a lot of initialisation to do before it can handle a request, it could have a big impact on your response times.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Real-time.&lt;/strong&gt; If you want to use WebSockets, look for built-in framework support, or a community maintained library which you integrate with the framework.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;TypeScript.&lt;/strong&gt; Do you want to write your application in &lt;a href="https://www.typescriptlang.org/"&gt;TypeScript&lt;/a&gt;? Some frameworks are designed only for TypeScript, some include type definitions, and others only have third-party types available which are maintained by the community. Even if you don’t intend to write your application in TypeScript, your code editor might be able to give you helpful hints based on a framework’s type definitions.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Framework styles
&lt;/h2&gt;

&lt;p&gt;Some developers love frameworks which come with "batteries included", whereas others loathe them. "Batteries" in this context refers to features beyond HTTP request/response handling and routing. This might include things like validation, logging, authentication, database abstractions and dependency injection. Frameworks in this category tend to be highly opinionated about how applications should be built. They require you to structure things in a specific way so you can take advantage of the features which they offer.&lt;/p&gt;

&lt;p&gt;At the other end of the spectrum you’ll find minimal frameworks. They tend to offer HTTP request/response handling, routing, and not a whole lot more. They’re not particularly opinionated and provide you with the freedom to structure your applications as you wish. As they provide a limited amount of functionality "out-of-the-box", you will need to choose and integrate other packages to provide any other functionality you require.&lt;/p&gt;

&lt;p&gt;There are some frameworks which sit in the middle. They have &lt;em&gt;some&lt;/em&gt; opinions and provide &lt;em&gt;some&lt;/em&gt; additional functionality beyond the basics, such as logging and validation.&lt;/p&gt;

&lt;p&gt;The style of framework you choose can be guided by the use cases I’ve mentioned above. It’s also likely to come down to your personal preferences (or those of your team). You might not have any preferences yet, but it will help if you pay attention to each framework’s style.&lt;/p&gt;

&lt;h2&gt;
  
  
  Support for promises and async / await
&lt;/h2&gt;

&lt;p&gt;As Node.js and &lt;a href="https://en.wikipedia.org/wiki/ECMAScript"&gt;ECMAScript&lt;/a&gt; have evolved, applications designed around the &lt;a href="https://nodejs.dev/learn/javascript-asynchronous-programming-and-callbacks"&gt;callback pattern&lt;/a&gt; have faded away. Instead, we can now happily write applications with promises and &lt;code&gt;async&lt;/code&gt; / &lt;code&gt;await&lt;/code&gt;. This means it’s important for Node.js frameworks to be promise-aware. They should allow you to write &lt;code&gt;async&lt;/code&gt; route handler functions and safely handle uncaught promise rejections for you.&lt;/p&gt;

&lt;p&gt;If a framework doesn’t meet these basic requirements, it increases the risk of memory leaks or crashes in your applications. I’ve written an &lt;a href="https://simonplend.com/are-you-using-promises-and-async-await-safely-in-node-js/"&gt;in-depth article&lt;/a&gt; which explains why this matters and what to look out for.&lt;/p&gt;

&lt;h2&gt;
  
  
  Documentation
&lt;/h2&gt;

&lt;p&gt;Firstly, does the framework have documentation?! You’re likely to struggle building an application with a framework if it doesn’t have documentation. If you don’t see any, you should probably avoid using it.&lt;/p&gt;

&lt;p&gt;Once you’ve established that a framework has documentation, try and get a sense of its quality. Not all documentation is created equal, so here are some things to consider:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Can you comfortably navigate and search it?&lt;/strong&gt; The structure of documentation really matters. It can also be a big help if there’s a built-in search feature.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Does it make sense to you?&lt;/strong&gt; There might be lots of documentation, but if it’s poorly written it’s not going to be much help.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Do you think you will be able to apply it when writing your own code?&lt;/strong&gt; It’s one thing to read and understand how to do something, and totally another to apply it yourself when building a real application.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Practical examples
&lt;/h2&gt;

&lt;p&gt;Reading through endless documentation to learn how to use a framework can feel overwhelming. Once you’ve got a general sense of what a framework can do, it really helps if there are &lt;em&gt;practical&lt;/em&gt; examples available which show you how to use it. A "hello world" example might show you the basics of how to use a framework, but it’s often not much help if you want to do something more complex. Practical examples will show solutions for real problems you might need to solve. Ideally they’ll also demonstrate the "best practices" for using that particular framework.&lt;/p&gt;

&lt;p&gt;You might find practical examples in the framework documentation, or perhaps in an &lt;code&gt;examples&lt;/code&gt; folder in the project’s GitHub repository. Some frameworks even have full example applications on GitHub which you can browse, run and pick apart.&lt;/p&gt;

&lt;p&gt;Seeing how the people who created a framework use it can be an excellent way of learning how to use it yourself. Instead of just grinding your way through documentation, practical examples will help you accelerate your learning curve with a new framework.&lt;/p&gt;

&lt;h2&gt;
  
  
  Community and ecosystem
&lt;/h2&gt;

&lt;p&gt;The community which exists around a framework really matters. When shit hits the fan and you get really stuck or run into a weird bug, it’s important to know where you can go for help. Check if there’s a message board, Slack or Discord server for the framework you’re looking at. Dip into it and get a feel for the community. Do the people there seem welcoming and supportive? Are they happy to accept contributions? The community around a framework might not matter to you on day one, but you’ll definitely need it in the long term.&lt;/p&gt;

&lt;p&gt;Framework popularity isn’t everything, but you’ll be building your whole application around it, so it’s important to check that it’s used by other developers. If a framework has widespread adoption it will make it easier to find libraries which have been written to work with it (e.g. middleware or plugins). It can be fairly straightforward to swap out one library for another in your application, but that’s generally not the case with a framework.&lt;/p&gt;

&lt;p&gt;The stars for a repository on GitHub are often cited as an indicator of popularity, but I think they’re better viewed as a measure of general interest rather than actual usage. A simple way to determine if a framework is being used is by looking at its package download counts. They can’t be taken as a measure of how many projects are &lt;em&gt;using&lt;/em&gt; a framework — many frameworks are bundled with other libraries but not used — but they can give you an idea of whether a framework is widely used. You can view weekly downloads on a package’s npm page, and the tool &lt;a href="https://www.npmtrends.com/"&gt;npm trends&lt;/a&gt; shows package downloads over time. It also allows you to compare packages.&lt;/p&gt;

&lt;h2&gt;
  
  
  Project health
&lt;/h2&gt;

&lt;p&gt;When choosing a framework to build your application with, you want to be confident that the project is in good health and will continue to be maintained for the foreseeable future. Here are some indicators to look for:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Releases.&lt;/strong&gt; Some developers hold the opinion that a framework doesn’t need new releases if it’s already "feature complete", but security updates and bug fixes are necessary. There is always the potential that major vulnerabilities exist in a framework (or one of its dependencies). It’s wise to avoid any framework which is unmaintained and no longer putting out releases.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Activity on issues.&lt;/strong&gt; Lots of issues with no recent responses from maintainers could be an indicator that the project is unmaintained. On the flip side, if there are no issues at all, it could suggest that usage of the framework is very low.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Pull requests.&lt;/strong&gt; A healthy project will typically have some recent pull request activity. Lots of old and inactive open pull requests could indicate that the project is no longer being maintained.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Contributors.&lt;/strong&gt; If there are only one or two contributors to a framework it could suggest there isn’t much of a community around it. It also creates a risk around the long term maintenance of that framework if those contributors step back from the project. A healthy project will have numerous contributors, adding changes large and small.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Dependency graph.&lt;/strong&gt; The more dependencies a framework has, the larger the attack surface area. It can also make debugging issues in your applications much more difficult. You don’t need to find a framework with zero dependencies, but you should have some awareness of a framework’s dependency graph. The tool &lt;a href="https://npmgraph.js.org"&gt;npmgraph&lt;/a&gt; can provide you with an excellent overview.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The following tools can help you determine the health of a framework project:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&lt;a href="https://snyk.io/advisor/"&gt;Snyk Open Source Advisor&lt;/a&gt;.&lt;/strong&gt; This tool generates a "health score" for packages. It pulls in data from several difference sources and summarises them to help you determine the health of a project.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The ‘Insights’ tab on GitHub repositories.&lt;/strong&gt; This tab provides a comprehensive overview of recent project activity (releases, pull requests, issues and contributors).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;a href="https://moiva.io/"&gt;Moiva&lt;/a&gt;.&lt;/strong&gt; This is an open source tool which provides similar data to the Snyk and GitHub tools, but it conveniently allows you to compare metrics between frameworks.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;If you’re looking for a list of Node.js frameworks, check out the list on &lt;a href="https://github.com/sindresorhus/awesome-nodejs#web-frameworks"&gt;Awesome Node.js&lt;/a&gt;. It includes popular Node.js frameworks, as well as some lesser known alternatives.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;It turns out there are plenty of things to consider when choosing a Node.js framework. There’s one last thing, however, which you might want to ask yourself when evaluating a framework: do you think you’ll enjoy writing applications with it? Personally, if I don’t enjoy using a framework, every time I need to work with it becomes a chore. The sweet spot is a framework which meets your requirements &lt;em&gt;and&lt;/em&gt; which you enjoy using.&lt;/p&gt;

&lt;p&gt;Choosing a Node.js framework can be tricky, but hopefully the guidelines I’ve shared will help you refine your own personal checklist. Good luck choosing the "best" framework for your project!&lt;/p&gt;

&lt;h2&gt;
  
  
  Want to create better Node.js applications?
&lt;/h2&gt;

&lt;p&gt;I write articles to help you level up as a Node.js developer. I'll send practical advice straight to your inbox every couple of weeks if you &lt;a href="https://simonplend.com/subscribe/"&gt;get on the list&lt;/a&gt;!&lt;/p&gt;

</description>
      <category>node</category>
      <category>frameworks</category>
    </item>
    <item>
      <title>How does middleware work in Express?</title>
      <dc:creator>Simon Plenderleith</dc:creator>
      <pubDate>Mon, 10 May 2021 12:11:00 +0000</pubDate>
      <link>https://forem.com/simonplend/how-does-middleware-work-in-express-359f</link>
      <guid>https://forem.com/simonplend/how-does-middleware-work-in-express-359f</guid>
      <description>&lt;p&gt;&lt;em&gt;This article is an adapted excerpt from my book, &lt;a href="https://expressapivalidation.com/"&gt;Express API Validation Essentials&lt;/a&gt;. It teaches you a complete API validation strategy which you can start applying in your Express applications today.&lt;/em&gt;&lt;/p&gt;




&lt;p&gt;The Express documentation tells us that "an Express application is essentially a series of middleware function calls". It sounds simple on the surface, but honestly, middleware can get pretty confusing. You've probably found yourself wondering:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Where is the right place to add this middleware in my application?&lt;/li&gt;
&lt;li&gt;When should I call the &lt;code&gt;next&lt;/code&gt; callback function, and what happens when I do?&lt;/li&gt;
&lt;li&gt;Why does the order of middleware matter?&lt;/li&gt;
&lt;li&gt;How can I write my own code for handling errors?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The middleware pattern is fundamental to building applications with Express, so you want to have a solid understanding of what middleware is and how it works.&lt;/p&gt;

&lt;p&gt;In this article we're going to dig into the middleware pattern. We'll also look at the different types of Express middleware and how to effectively combine them when we build our applications.&lt;/p&gt;

&lt;h2&gt;
  
  
  Jump links
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
The middleware pattern

&lt;ul&gt;
&lt;li&gt;Middleware syntax&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;
The two types of middleware

&lt;ul&gt;
&lt;li&gt;Plain middleware&lt;/li&gt;
&lt;li&gt;Error handling middleware&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;
Using middleware

&lt;ul&gt;
&lt;li&gt;At the route level&lt;/li&gt;
&lt;li&gt;At the router level&lt;/li&gt;
&lt;li&gt;At the application level&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Wrapping up&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  The middleware pattern
&lt;/h2&gt;

&lt;p&gt;In Express, middleware are a specific style of function which you configure your application to use. They can run any code you like, but they typically take care of processing incoming requests, sending responses and handling errors. They are the building blocks of every Express application.&lt;/p&gt;

&lt;p&gt;When you define a route in Express, the route handler function which you specify for that route is a middleware function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="kd"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/user&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;routeHandlerMiddleware&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// execute something&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;(Example 1.1)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Middleware is flexible. You can tell Express to run the same middleware function for different routes, enabling you to do things like making a common check across different API endpoints.&lt;/p&gt;

&lt;p&gt;As well as writing your own middleware functions, you can also install third-party middleware to use in your application. The Express documentation lists some &lt;a href="https://expressjs.com/en/resources/middleware.html"&gt;popular middleware modules&lt;/a&gt;. There are also a wide variety of Express middleware modules available on &lt;a href="https://www.npmjs.com/"&gt;npm&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Middleware syntax
&lt;/h3&gt;

&lt;p&gt;Here is the syntax for a middleware function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="cm"&gt;/**
 * @param {Object} request - Express request object (commonly named `req`)
 * @param {Object} response - Express response object (commonly named `res`)
 * @param {Function} next - Express `next()` function
 */&lt;/span&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;middlewareFunction&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// execute something&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;(Example 1.2)&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Note: You might have noticed that I refer to &lt;code&gt;req&lt;/code&gt; as &lt;code&gt;request&lt;/code&gt; and &lt;code&gt;res&lt;/code&gt; as &lt;code&gt;response&lt;/code&gt;. You can name the parameters for your middleware functions whatever you like, but I prefer verbose variable names as I think that it makes it easier for other developers to understand what your code is doing, even if they're not familiar with the Express framework.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;When Express runs a middleware function, it is passed three arguments:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;An Express request object (commonly named &lt;code&gt;req&lt;/code&gt;) - this is an extended instance of Node.js' built-in &lt;a href="https://nodejs.org/api/http.html#http_class_http_incomingmessage"&gt;http.IncomingMessage&lt;/a&gt; class.&lt;/li&gt;
&lt;li&gt;An Express response object (commonly named &lt;code&gt;res&lt;/code&gt;) - this is an extended instance of Node.js' built-in &lt;a href="https://nodejs.org/api/http.html#http_class_http_serverresponse"&gt;http.ServerResponse&lt;/a&gt; class.&lt;/li&gt;
&lt;li&gt;An Express &lt;code&gt;next()&lt;/code&gt; function - Once the middleware function has completed its tasks, it must call the &lt;code&gt;next()&lt;/code&gt; function to hand off control to the next middleware. If you pass an argument to it, Express assumes it to be an error. It will skip any remaining non-error handling middleware functions and start executing error handling middleware.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Middleware functions should not &lt;code&gt;return&lt;/code&gt; a value. Any value returned by middleware will not be used by Express.&lt;/p&gt;

&lt;h2&gt;
  
  
  The two types of middleware
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Plain middleware
&lt;/h3&gt;

&lt;p&gt;Most middleware functions that you will work with in an Express application are what I call "plain" middleware (the Express documentation doesn't have a specific term for them). They look like the function defined in the middleware syntax example above (&lt;em&gt;Example 1.2&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;Here is an example of a plain middleware function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;plainMiddlewareFunction&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;`The request method is &lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;method&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;`&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="cm"&gt;/**
     * Ensure the next middleware function is called.
     */&lt;/span&gt;
    &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;(Example 1.3)&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Error handling middleware
&lt;/h3&gt;

&lt;p&gt;The difference between &lt;a href="https://expressjs.com/en/guide/using-middleware.html#middleware.error-handling"&gt;error handling middleware&lt;/a&gt; and plain middleware is that error handler middleware functions specify four parameters instead of three i.e. &lt;code&gt;(error, request, response, next)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Here is an example of an error handling middleware function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;errorHandlingMiddlewareFunction&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;message&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="cm"&gt;/**
     * Ensure the next error handling middleware is called.
     */&lt;/span&gt;
    &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;(Example 1.4)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This error handling middleware function will be executed when another middleware function calls the &lt;code&gt;next()&lt;/code&gt; function with an error object e.g.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;anotherMiddlewareFunction&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nb"&gt;Error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Something is wrong&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="cm"&gt;/**
     * This will cause Express to start executing error
     * handling middleware.
     */&lt;/span&gt;
    &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;(Example 1.5)&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Using middleware
&lt;/h2&gt;

&lt;p&gt;The order in which middleware are configured is important. You can apply them at three different levels in your application:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The route level&lt;/li&gt;
&lt;li&gt;The router level&lt;/li&gt;
&lt;li&gt;The application level&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you want a route (or routes) to have errors which they raise handled by an error handling middleware, you must add it after the route has been defined.&lt;/p&gt;

&lt;p&gt;Let's look at what configuring middleware looks like at each level.&lt;/p&gt;

&lt;h3&gt;
  
  
  At the route level
&lt;/h3&gt;

&lt;p&gt;This is the most specific level: any middleware you configure at the route level will only run for that specific route.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="kd"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;someMiddleware&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;routeHandlerMiddleware&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;errorHandlerMiddleware&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;(Example 1.6)&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  At the router level
&lt;/h3&gt;

&lt;p&gt;Express allows you to create &lt;a href="https://expressjs.com/en/api.html#router"&gt;Router&lt;/a&gt; objects. They allow you to scope middleware to a specific set of routes. If you want the same middleware to run for multiple routes, but not for all routes in your application, they can be very useful.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;express&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;express&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;router&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;express&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;Router&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="nx"&gt;router&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;use&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;someMiddleware&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nx"&gt;router&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;post&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/user&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;createUserRouteHandler&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nx"&gt;router&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="kd"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/user/:user_id&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;getUserRouteHandler&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nx"&gt;router&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;put&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/user/:user_id&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;updateUserRouteHandler&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="nx"&gt;router&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;delete&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/user/:user_id&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;deleteUserRouteHandler&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nx"&gt;router&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;use&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;errorHandlerMiddleware&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;(Example 1.7)&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  At the application level
&lt;/h3&gt;

&lt;p&gt;This is the least specific level. Any middleware configured at this level will be run for all routes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;use&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;someMiddleware&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// define routes&lt;/span&gt;

&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;use&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;errorHandlerMiddleware&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;(Example 1.8)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Technically you can define some routes, call &lt;code&gt;app.use(someMiddleware)&lt;/code&gt; , then define some other routes which you want &lt;code&gt;someMiddleware&lt;/code&gt; to be run for. I don't recommend this approach as it tends to result in a confusing and hard to debug application structure.&lt;/p&gt;

&lt;p&gt;You should only configure middleware at the application level if absolutely necessary i.e. it really must be run for every single route in your application. Every middleware function, no matter how small, takes &lt;em&gt;some&lt;/em&gt; time to execute. The more middleware functions that need to be run for a route, the slower requests to that route will be. This really adds up as your application grows and is configured with lots of middleware. Try to scope middleware to the route or router levels when you can.&lt;/p&gt;

&lt;h2&gt;
  
  
  Wrapping up
&lt;/h2&gt;

&lt;p&gt;In this article we've learnt about the middleware pattern in Express. We've also learnt about the different types of middleware and how we can combine them when building an application with Express.&lt;/p&gt;

&lt;p&gt;If you'd like to read more about middleware, there are a couple of guides in the Express documentation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://expressjs.com/en/guide/using-middleware.html"&gt;Guide: Using middleware&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://expressjs.com/en/guide/writing-middleware.html"&gt;Guide: Writing middleware for use in Express apps&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;&lt;em&gt;This article is an adapted excerpt from my book, &lt;a href="https://expressapivalidation.com/"&gt;Express API Validation Essentials&lt;/a&gt;. It teaches you a complete API validation strategy which you can start applying in your Express applications today.&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Tired of wasting time reading Node.js blog posts which don't actually help you improve your projects?
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://simonplend.com/newsletter/"&gt;Sign up to my weekly-ish newsletter&lt;/a&gt; and I'll let you know when I publish a new blog post which helps solve your real developer problems. I'll also send you an awesome tip so we can level up together, as well as a handful of excellent things by other people.&lt;/p&gt;

</description>
      <category>node</category>
      <category>express</category>
      <category>middleware</category>
    </item>
    <item>
      <title>Learn how to handle validation in Express</title>
      <dc:creator>Simon Plenderleith</dc:creator>
      <pubDate>Thu, 22 Apr 2021 14:56:11 +0000</pubDate>
      <link>https://forem.com/simonplend/learn-how-to-handle-validation-in-express-3blb</link>
      <guid>https://forem.com/simonplend/learn-how-to-handle-validation-in-express-3blb</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;These two free lessons are from 'Express API Validation Essentials'. &lt;a href="https://expressapivalidation.com/"&gt;Get the book&lt;/a&gt;.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  Integrating Ajv into your Express application
&lt;/h2&gt;

&lt;p&gt;You can use the Ajv library directly, however for an Express based API it's nice to be able to use middleware to validate request data which has been sent to an endpoint before that endpoint's route handler is run. This allows you to prevent things like accidentally storing invalid data in your database. It also means that you can handle validation errors and send a useful error response back to the client. The &lt;a href="https://github.com/vacekj/express-json-validator-middleware"&gt;express-json-validator-middleware&lt;/a&gt; package can help you with all of this.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;express-json-validator-middleware&lt;/code&gt; package uses Ajv and allows you to pass configuration options to it. This is great as it means you have full control to configure Ajv as if you were using it directly.&lt;/p&gt;

&lt;p&gt;Before we integrate this middleware into our application, let's get it installed:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npm &lt;span class="nb"&gt;install &lt;/span&gt;express-json-validator-middleware
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once you have it installed you need to require it in your application and configure it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/middleware/json-validator.js&lt;/span&gt;

&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Validator&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;express-json-validator-middleware&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * Create a new instance of the `express-json-validator-middleware`
 * `Validator` class and pass in Ajv options if needed.
 *
 * @see https://github.com/ajv-validator/ajv/blob/master/docs/api.md#options
 */&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;validator&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nx"&gt;Validator&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt; &lt;span class="nx"&gt;validator&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;validate&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;(Example 2.6)&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Using a JSON schema to validate a response body
&lt;/h2&gt;

&lt;p&gt;In this next piece of code we're going to do two things:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Define a JSON schema to describe the data we expect to receive when a client calls our API endpoint to create a new user. We want the data to be an object which always has a &lt;code&gt;first_name&lt;/code&gt; and a &lt;code&gt;last_name&lt;/code&gt; property. This object can optionally include an &lt;code&gt;age&lt;/code&gt; property, and if it does, the value of that property must be an integer which is greater than or equal to 18.&lt;/li&gt;
&lt;li&gt;Use the user schema which we've defined to validate requests to our &lt;code&gt;POST /user&lt;/code&gt; API endpoint.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/schemas/user.schema.js&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;userSchema&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;object&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;required&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;first_name&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;last_name&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;age&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
    &lt;span class="na"&gt;properties&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="na"&gt;first_name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;string&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="na"&gt;minLength&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="na"&gt;last_name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;string&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="na"&gt;minLength&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="na"&gt;age&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;number&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt; &lt;span class="nx"&gt;userSchema&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// src/server.js&lt;/span&gt;

&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;validate&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;./middleware/json-validator.js&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;userSchema&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;./schemas/user.schema.js&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;post&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/user&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nx"&gt;validate&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;body&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;userSchema&lt;/span&gt; &lt;span class="p"&gt;}),&lt;/span&gt;
    &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;createUserRouteHandler&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="cm"&gt;/**
         * Normally you'd save the data you've received to a database,
         * but for this example we'll just send it back in the response.
         */&lt;/span&gt;
        &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;json&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;body&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

        &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;(Example 2.7)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In the route definition above we're calling the &lt;code&gt;validate()&lt;/code&gt; method from our &lt;code&gt;Validator&lt;/code&gt; instance. We pass it an object telling it which request properties we want to validate, and what JSON schema we want to validate the value of each property against. It is configured to validate the &lt;code&gt;body&lt;/code&gt; property of any requests to the &lt;code&gt;POST /user&lt;/code&gt; endpoint against our &lt;code&gt;userSchema&lt;/code&gt; JSON schema.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;validate()&lt;/code&gt; method compiles the JSON schema with Ajv, and then returns a middleware function which will be run every time a request is made to this endpoint. This middleware function will take care of running the validation which we've configured.&lt;/p&gt;

&lt;p&gt;If the request &lt;code&gt;body&lt;/code&gt; validates against our &lt;code&gt;userSchema&lt;/code&gt;, the middleware function will call the &lt;code&gt;next()&lt;/code&gt; Express function which was passed to it and our route handler function will be run. If Ajv returns a validation error, the middleware  will call the &lt;code&gt;next()&lt;/code&gt; Express function with an error object which has a &lt;code&gt;validationErrors&lt;/code&gt; property containing an array of validation errors. Our route handler function will &lt;em&gt;not&lt;/em&gt; be run. We'll look at where that error object gets passed to and how we can handle it in the next part of this book.&lt;/p&gt;




&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;If you've enjoyed these free lessons from 'Express API Validation Essentials', &lt;a href="https://expressapivalidation.com/"&gt;get the book&lt;/a&gt;.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>node</category>
      <category>express</category>
      <category>validation</category>
    </item>
    <item>
      <title>Are you using promises and async / await safely in Node.js?</title>
      <dc:creator>Simon Plenderleith</dc:creator>
      <pubDate>Tue, 09 Mar 2021 18:15:48 +0000</pubDate>
      <link>https://forem.com/simonplend/are-you-using-promises-and-async-await-safely-in-node-js-1d27</link>
      <guid>https://forem.com/simonplend/are-you-using-promises-and-async-await-safely-in-node-js-1d27</guid>
      <description>&lt;p&gt;You're building your Node.js server applications with a framework, and using promises and &lt;code&gt;async&lt;/code&gt; / &lt;code&gt;await&lt;/code&gt;. Mostly everything's working well, but it can get confusing at times, especially when you need to handle errors. How do you know if you're writing your async code correctly? And what happens if you're not?!&lt;/p&gt;

&lt;p&gt;Promises and &lt;code&gt;async&lt;/code&gt; / &lt;code&gt;await&lt;/code&gt; are a fundamental part of writing Node.js applications with modern JavaScript. If only you could be confident that you're using them correctly in your applications. And wouldn't it be great to know that your framework has got you covered when you mess up? (hey, we all do!)&lt;/p&gt;

&lt;p&gt;If a framework has "native support" for promises and &lt;code&gt;async&lt;/code&gt; / &lt;code&gt;await&lt;/code&gt; then things are in good shape, but what does that actually mean? In this article I'll bring you up to speed on what you need from your framework. Then we'll run through which frameworks have native support, and look at how you can write async code safely in Node.js.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;In this article I'm going to refer to promises and &lt;code&gt;async&lt;/code&gt; / &lt;code&gt;await&lt;/code&gt; collectively as "async code".&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Jump links
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Support for async code in Node.js&lt;/li&gt;
&lt;li&gt;What does framework "native support" for async code look like?&lt;/li&gt;
&lt;li&gt;What happens when a framework doesn't natively support async code?&lt;/li&gt;
&lt;li&gt;Which Node.js frameworks natively support async code?&lt;/li&gt;
&lt;li&gt;
How to write async code safely in Node.js

&lt;ul&gt;
&lt;li&gt;Build new projects with a framework which natively supports it&lt;/li&gt;
&lt;li&gt;Migrate existing applications to a framework which natively supports it&lt;/li&gt;
&lt;li&gt;Let unhandled promise rejections crash your node process!&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;Learn more&lt;/li&gt;

&lt;/ul&gt;

&lt;h2&gt;
  
  
  Support for async code in Node.js
&lt;/h2&gt;

&lt;p&gt;Node.js has had support for promises since &lt;a href="https://nodejs.org/en/blog/release/v4.0.0/" rel="noopener noreferrer"&gt;v4.0.0&lt;/a&gt; (released September 2015) and &lt;code&gt;async&lt;/code&gt; / &lt;code&gt;await&lt;/code&gt; since &lt;a href="https://github.com/nodejs/node/blob/master/doc/changelogs/CHANGELOG_V7.md#7.6.0" rel="noopener noreferrer"&gt;v7.6.0&lt;/a&gt; (released February 2017). These JavaScript language features are now widely used across the Node.js ecosystem.&lt;/p&gt;

&lt;h2&gt;
  
  
  What does framework "native support" for async code look like?
&lt;/h2&gt;

&lt;p&gt;In this context, "native support" means that a framework supports a certain set of behaviours or features by default, without the need for you to add any extra code.&lt;/p&gt;

&lt;p&gt;Here are the things which a Node.js framework should natively support for your async code to function safely and correctly:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Your route handler functions can use &lt;code&gt;async&lt;/code&gt; / &lt;code&gt;await&lt;/code&gt;&lt;/strong&gt; - The framework will explicitly wait for the promise wrapping the route handler function to resolve or reject (all JavaScript functions using the &lt;code&gt;async&lt;/code&gt; keyword are &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#return_value" rel="noopener noreferrer"&gt;automatically wrapped in a promise&lt;/a&gt;).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;You can &lt;code&gt;throw&lt;/code&gt; errors from within a route handler function&lt;/strong&gt; - The error will be caught and gracefully handled by the framework i.e. sending back an appropriate error response to the client and logging the error.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Uncaught promise rejections from a route handler function will be handled for you&lt;/strong&gt; - When a rejected promise is not caught and handled by your code within a route handler function, the framework will catch it and gracefully handle it in the same way as if an error has been thrown.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Bonus points: Return values from route handler functions are sent as a response body&lt;/strong&gt; - This means you don't need to explicitly call a method to send a response e.g. &lt;code&gt;response.send()&lt;/code&gt;. This is a nice to have though.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What happens when a framework doesn't natively support async code?
&lt;/h2&gt;

&lt;p&gt;The asynchronous control flow of your application will behave unpredictably, especially when things go wrong i.e. if there's a promise rejection which you haven't caught. Because the framework has no awareness of promises, it won't catch promise rejections for you. If an unhandled promise rejection occurs, it's most likely that a response will never be sent back to the client. In most cases this will cause the client's request to hang.&lt;/p&gt;

&lt;p&gt;Here is an example route defined in the style supported by some Node.js frameworks:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/user/:user_id&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;async &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;user&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;getUser&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;params&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;json&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;user&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the route above is defined on a server instance created by a framework which doesn't natively support async code, you're very likely to run into problems. The route handler function doesn't implement any error handling code (either intentionally or by accident). If the promise returned by the &lt;code&gt;getUser()&lt;/code&gt; function rejects, it will result in an unhandled promise rejection.&lt;/p&gt;

&lt;p&gt;Unhandled promise rejections can cause memory leaks in your application. If the memory leak is bad enough, the &lt;code&gt;node&lt;/code&gt; process will eventually run out of memory and your application will no longer be able to handle requests.&lt;/p&gt;

&lt;p&gt;From Node.js v15.0.0 onwards an unhandled promise rejection will throw an error, causing the &lt;code&gt;node&lt;/code&gt; process to exit i.e. your application will crash (in previous versions a warning message would be emitted to &lt;code&gt;stderr&lt;/code&gt;).&lt;/p&gt;

&lt;h2&gt;
  
  
  Which Node.js frameworks natively support async code?
&lt;/h2&gt;

&lt;p&gt;Many Node.js frameworks now support async code, so I think it's more useful to highlight popular frameworks which &lt;em&gt;don't&lt;/em&gt; support async code:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://expressjs.com/" rel="noopener noreferrer"&gt;Express&lt;/a&gt; - No native support for async code. There's not been a release of Express for almost 2 years now, so it looks unlikely that this framework will support async code any time soon. If you are unable to move away from Express at the moment, you can &lt;a href="https://simonplend.com/5-best-practices-for-building-a-modern-api-with-express/" rel="noopener noreferrer"&gt;monkey patch in support&lt;/a&gt; for &lt;code&gt;async&lt;/code&gt; / &lt;code&gt;await&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;a href="http://restify.com/" rel="noopener noreferrer"&gt;Restify&lt;/a&gt; - No native support yet. Support &lt;a href="https://github.com/restify/node-restify/pull/1833" rel="noopener noreferrer"&gt;merged mid-2020&lt;/a&gt;, scheduled for a v9 release.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;An excellent alternative to Express or Restify is the &lt;a href="https://www.fastify.io/" rel="noopener noreferrer"&gt;Fastify&lt;/a&gt; framework. It has full native support for async code and is in active development. There is also a &lt;a href="https://github.com/fastify/fastify-express" rel="noopener noreferrer"&gt;fastify-express&lt;/a&gt; plugin available which can help ease your migration path away from Express.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to write async code safely in Node.js
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Build new projects with a framework which natively supports it
&lt;/h3&gt;

&lt;p&gt;If you can, you should absolutely use a Node.js framework which has native support for async code. This should be one of your minimum requirements when choosing a Node.js framework for a new project.&lt;/p&gt;

&lt;h3&gt;
  
  
  Migrate existing applications to a framework which natively supports it
&lt;/h3&gt;

&lt;p&gt;If your existing Node.js applications are using a framework which doesn't natively support async code, you should strongly consider migrating them to one which does.&lt;/p&gt;

&lt;p&gt;If you're using Express, the '&lt;a href="//2021-03-01%20-%20Are%20you%20using%20promises%20and%20async-await%20safely%20in%20Node.js?.md#which-nodejs-frameworks-natively-support-async-code"&gt;Which Node.js frameworks natively support async code?&lt;/a&gt;' section in this article has tips on migrating away from it.&lt;/p&gt;

&lt;h3&gt;
  
  
  Let unhandled promise rejections crash your node process!
&lt;/h3&gt;

&lt;p&gt;This is really important.&lt;/p&gt;

&lt;p&gt;You shouldn't set an event handler for &lt;code&gt;unhandledRejection&lt;/code&gt; events, unless the event handler will exit the &lt;code&gt;node&lt;/code&gt; process. You risk memory leaks in your application if the &lt;code&gt;node&lt;/code&gt; process doesn't exit when an unhandled promise rejection occurs.&lt;/p&gt;

&lt;p&gt;Until you start using Node.js &amp;gt;= v15.0.0, you should use the &lt;a href="https://github.com/mcollina/make-promises-safe" rel="noopener noreferrer"&gt;make-promises-safe&lt;/a&gt; module in your Node.js applications. When an unhandled promise rejection occurs in your application, this module "prints the stacktrace and exits the process with an exit code of 1" (i.e. crashes your application).&lt;/p&gt;

&lt;h2&gt;
  
  
  Learn more
&lt;/h2&gt;

&lt;p&gt;If you want to read more on the subject, the official Learn Node.js website has an excellent page which covers the path from callbacks ➜ promises ➜ &lt;code&gt;async&lt;/code&gt; / &lt;code&gt;await&lt;/code&gt; in JavaScript: &lt;a href="https://nodejs.dev/learn/modern-asynchronous-javascript-with-async-and-await" rel="noopener noreferrer"&gt;Modern Asynchronous JavaScript with Async and Await&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If you want to learn more about how to use promises correctly in Node.js and avoid some common pitfalls, I recommend watching the talk &lt;a href="https://www.nearform.com/blog/broked-promises-james-snell-tech-talk-video/" rel="noopener noreferrer"&gt;Broken Promises&lt;/a&gt; by &lt;a href="https://twitter.com/jasnell/" rel="noopener noreferrer"&gt;James Snell&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Meanwhile, on a less technical note...&lt;/p&gt;

&lt;p&gt;&lt;a href="https://twitter.com/simonplend/status/1359523477783511040" rel="noopener noreferrer"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fsimonplend.com%2Fwp-content%2Fuploads%2F2021%2F03%2Ftweet-simonplend-unhandled-rejection.png" alt="Screenshot of a tweet by @simonplend: "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Tired of wasting time reading Node.js blog posts which don't actually help you improve your projects?
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://simonplend.com/newsletter/" rel="noopener noreferrer"&gt;Sign up to my weekly-ish newsletter&lt;/a&gt; and I'll let you know when I publish a new blog post which helps solve real developer problems ✨&lt;/p&gt;

</description>
      <category>node</category>
    </item>
    <item>
      <title>How to securely call an authenticated API from your front end</title>
      <dc:creator>Simon Plenderleith</dc:creator>
      <pubDate>Fri, 05 Feb 2021 14:20:00 +0000</pubDate>
      <link>https://forem.com/simonplend/how-to-securely-call-an-authenticated-api-from-your-front-end-19md</link>
      <guid>https://forem.com/simonplend/how-to-securely-call-an-authenticated-api-from-your-front-end-19md</guid>
      <description>&lt;p&gt;&lt;em&gt;Credit: Key icon by Gregor Cresnar from the Noun Project&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Your front end needs to access data from an API which requires an API key. If you put this API key in your client side JavaScript, you know that anyone viewing your website could view this API key (with a little help from their browser's Developer Tools). This doesn't seem secure at all, but what can you do instead?&lt;/p&gt;

&lt;p&gt;Only applications running on a server - i.e. a back end - should have access to secrets like an API key. This means that requests with an API key can only be made from the server side. The thing is, you want your &lt;em&gt;front end&lt;/em&gt; to be able to request and use data from the API in a secure way.&lt;/p&gt;

&lt;p&gt;One way of achieving this is to create a "proxy" server. Instead of directly calling the API, your client side JavaScript will make requests to the proxy server. The proxy server can add an API key to every request and forward it on to the API. This keeps the API key secure and away from your front end.&lt;/p&gt;

&lt;p&gt;In this article I'll show you how to use the &lt;a href="https://www.fastify.io/"&gt;Fastify&lt;/a&gt; framework and the &lt;a href="https://github.com/fastify/fastify-http-proxy"&gt;fastify-http-proxy&lt;/a&gt; plugin to create a proxy server.&lt;/p&gt;

&lt;p&gt;The full code for this article is &lt;a href="https://github.com/simonplend/example-nodejs-api-proxy-server"&gt;on GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;This article uses ECMAScript (ES) module syntax. ES modules are well supported in v12.20.0 / v14.13.0 (and higher) releases of Node.js. &lt;a href="https://simonplend.com/what-you-need-to-know-about-es-modules-in-node-js/"&gt;Learn more about ES module support in Node.js&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Jump links
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Request flow with a proxy server&lt;/li&gt;
&lt;li&gt;Create a server with Fastify&lt;/li&gt;
&lt;li&gt;Add and configure the fastify-http-proxy plugin&lt;/li&gt;
&lt;li&gt;
Add an API key to proxied requests

&lt;ul&gt;
&lt;li&gt;HTTP request header&lt;/li&gt;
&lt;li&gt;URL query string&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Conclusion&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Request flow with a proxy server
&lt;/h2&gt;

&lt;p&gt;Let's assume that we have some client side JavaScript running on a web page - it could be a React application, or "vanilla" JavaScript (no framework or library). This client side JavaScript needs to retrieve data from an API which requires an API key to be sent in the request.&lt;/p&gt;

&lt;p&gt;As we don't want our client side JavaScript to contain the API key for security reasons, we're going to create a proxy server in Node.js which can receive a request from the client side JavaScript (made with &lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API"&gt;fetch&lt;/a&gt;, or a request library like &lt;a href="https://github.com/axios/axios"&gt;Axios&lt;/a&gt;). This proxy server will add the required API key to the request and forward it on to the API server.&lt;/p&gt;

&lt;p&gt;The request flow from the client (JavaScript running on a web page in a user's browser) through to the API server will look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Request from client side JavaScript to our proxy server
 ↓
Proxy server receives request, adds the API key, forwards request to API server
 ↓
API server receives request, sends response back to proxy server
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When the proxy server receives a response from the API server it will send it back to the client. At no point will the API key be exposed to the client side JavaScript.&lt;/p&gt;

&lt;p&gt;Instead of making requests to &lt;code&gt;https://some-api.com/some/path&lt;/code&gt; from our client side JavaScript, we'll now make requests to our proxy server: &lt;code&gt;https://my-proxy.com/some/path&lt;/code&gt;. Neat, right?&lt;/p&gt;

&lt;h2&gt;
  
  
  Create a server with Fastify
&lt;/h2&gt;

&lt;p&gt;We're going to use the &lt;a href="https://www.fastify.io/"&gt;Fastify&lt;/a&gt; framework and the &lt;a href="https://github.com/fastify/fastify-http-proxy"&gt;fastify-http-proxy&lt;/a&gt; plugin to create our proxy server in Node.js.&lt;/p&gt;

&lt;p&gt;First let's install the dependencies which our proxy server application will require:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npm &lt;span class="nb"&gt;install &lt;/span&gt;fastify fastify-http-proxy
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We're now going to create and configure a Fastify server instance:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/server.js&lt;/span&gt;

&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;createFastifyServer&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;fastify&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * Create a Fastify server instance with logging enabled.
 * Fastify uses the library `pino` for logging.
 *
 * @see https://www.fastify.io/docs/latest/Logging/
 * @see https://github.com/pinojs/pino/
 */&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;fastify&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;createFastifyServer&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
    &lt;span class="na"&gt;logger&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="cm"&gt;/**
     * Make use of top-level `await` i.e. outside of an `async` function.
     *
     * @see https://nodejs.org/docs/latest-v14.x/api/esm.html#esm_top_level_await
     */&lt;/span&gt;
    &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;fastify&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;listen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3000&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;fastify&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="nx"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;exit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If we run this code (&lt;code&gt;node src/server.js&lt;/code&gt;), we'll have an HTTP server listening on port &lt;code&gt;3000&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Our server doesn't provide any endpoints which you can make a request to, so making a request to &lt;code&gt;http://localhost:3000/&lt;/code&gt; will result in a 404 error response. We need to add and configure the &lt;code&gt;fastify-http-proxy&lt;/code&gt; plugin in order for our server to be able to handle requests.&lt;/p&gt;

&lt;h2&gt;
  
  
  Add and configure the fastify-http-proxy plugin
&lt;/h2&gt;

&lt;p&gt;We want to configure our Fastify server to proxy requests which it receives to &lt;code&gt;https://some-api.com&lt;/code&gt;. In order to do this, let's &lt;code&gt;import&lt;/code&gt; the &lt;a href="https://github.com/fastify/fastify-http-proxy"&gt;fastify-http-proxy&lt;/a&gt; plugin and configure it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/server.js&lt;/span&gt;

&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;fastifyHttpProxy&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;fastify-http-proxy&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * Register and configure the `fastify-http-proxy` plugin.
 *
 * This plugin supports all the options of `fastify-reply-from`,
 * as well as a few additional options e.g. `upstream`.
 *
 * @see https://github.com/fastify/fastify-http-proxy#options
 * @see https://github.com/fastify/fastify-reply-from
 */&lt;/span&gt;
&lt;span class="nx"&gt;fastify&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;register&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;fastifyHttpProxy&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;upstream&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;https://some-api.com&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;undici&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our Fastify server is now configured as a proxy server. It will forward all requests it receives to &lt;code&gt;https://some-api.com&lt;/code&gt; (our "upstream" server).&lt;/p&gt;

&lt;p&gt;Our proxy server will use the HTTP client library &lt;a href="https://github.com/nodejs/undici"&gt;undici&lt;/a&gt; to make requests to the upstream server. The &lt;code&gt;undici&lt;/code&gt; library is a dependency of &lt;a href="https://github.com/fastify/fastify-reply-from"&gt;fastify-reply-from&lt;/a&gt;, which &lt;code&gt;fastify-http-proxy&lt;/code&gt; is using under the hood. &lt;code&gt;undici&lt;/code&gt; is &lt;a href="https://github.com/nodejs/undici#benchmarks"&gt;much faster&lt;/a&gt; than the native &lt;a href="https://nodejs.org/api/http.html"&gt;HTTP client provided by Node.js&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Now that we have our proxy server set up, we need to configure it to add an API key to proxied requests.&lt;/p&gt;

&lt;h2&gt;
  
  
  Add an API key to proxied requests
&lt;/h2&gt;

&lt;p&gt;There are several different ways that APIs can implement authentication. One of the most common methods is for the client to pass an API key in the request. Typically APIs require the API key to be sent in a request header e.g. &lt;code&gt;X-Api-Key: abc123&lt;/code&gt;. Some APIs might require the API key in a query string parameter e.g. &lt;code&gt;?apiKey=abc123&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/fastify/fastify-http-proxy"&gt;fastify-http-proxy&lt;/a&gt; accepts a &lt;code&gt;replyOptions&lt;/code&gt; object which it passes through to &lt;a href="https://github.com/fastify/fastify-reply-from#replyfromsource-opts"&gt;fastify-reply-from&lt;/a&gt;. These options give us full control to modify requests and responses as they pass through our proxy server.&lt;/p&gt;

&lt;p&gt;Let's take a look at how we can modify requests and add an API key before our proxy server forwards it on to the API server (our "upstream").&lt;/p&gt;

&lt;h3&gt;
  
  
  HTTP request header
&lt;/h3&gt;

&lt;p&gt;In order to add an API key to the HTTP request headers, we're going to set a &lt;a href="https://github.com/fastify/fastify-reply-from#rewriterequestheadersoriginalreq-headers"&gt;replyOptions.rewriteRequestHeaders&lt;/a&gt; function. We will access our API key from &lt;a href="https://12factor.net/config"&gt;an environment variable&lt;/a&gt; and set it as the value of an &lt;code&gt;X-Api-Key&lt;/code&gt; request header. This code builds on our initial configuration for the &lt;code&gt;fastify-http-proxy&lt;/code&gt; plugin:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/server.js&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;CONFIG&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;apiKey&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;env&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;API_KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="nx"&gt;fastify&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;register&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;fastifyHttpProxy&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;upstream&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;https://some-api.com&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;undici&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;replyOptions&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="na"&gt;rewriteRequestHeaders&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;originalRequest&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;headers&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="cm"&gt;/**
                 * Preserve the existing request headers.
                 */&lt;/span&gt;
                &lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="nx"&gt;headers&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="cm"&gt;/**
                 * Add the header which the API we're proxying requests
                 * to requires to authenticate the request.
                 */&lt;/span&gt;
                &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;X-Api-Key&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;CONFIG&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;apiKey&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="p"&gt;};&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With a little extra configuration our server is now adding an API key to every request that it is proxying.&lt;/p&gt;

&lt;p&gt;While &lt;code&gt;X-Api-Key&lt;/code&gt; is a commonly used request header name, the API you are making requests to might require a different header e.g. &lt;code&gt;Authorization: Bearer &amp;lt;TOKEN&amp;gt;&lt;/code&gt;. The &lt;code&gt;replyOptions.rewriteRequestHeaders&lt;/code&gt; option allows us to add any request headers that we need.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/simonplend/example-nodejs-api-proxy-server/blob/main/src/server.js"&gt;View the full code for an example proxy server which authenticates using an API key request header&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  URL query string
&lt;/h3&gt;

&lt;p&gt;I do not recommend that you design your own APIs to accept an API key via a URL query string. An API key is a "secret", just like a password is. When you put an API key in a URL it is much easier to accidentally leak it than if you send it via a request header e.g. by an accidental copy and paste, or by logging it in server request logs.&lt;/p&gt;

&lt;p&gt;Unfortunately, some APIs do require you to send an API key in the URL query string. If this is the only way for you to authenticate with the API you are making requests to, you can use the &lt;a href="https://github.com/fastify/fastify-reply-from#querystring"&gt;replyOptions.queryString&lt;/a&gt; option provided by &lt;code&gt;fastify-http-proxy&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this article we've learnt how we can use Fastify and the &lt;code&gt;fastify-http-proxy&lt;/code&gt; plugin to proxy requests and add an API key to them. This allows us to keep our API key secure and away from our client side JavaScript.&lt;/p&gt;

&lt;p&gt;While &lt;code&gt;fastify-http-proxy&lt;/code&gt; is very powerful and allows us to set up a proxy with minimal configuration, there are cases in which you might want to take a different approach e.g.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You need to proxy complex API requests&lt;/li&gt;
&lt;li&gt;You want to create your own abstraction over another API&lt;/li&gt;
&lt;li&gt;You have an existing back end Node.js server application&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In these cases you might want to consider creating your own API endpoints which then make requests to an upstream API. The &lt;a href="https://www.npmjs.com/package/node-fetch"&gt;node-fetch&lt;/a&gt; library is a popular choice for making requests from Node.js. However, if you are interested in the features offered by &lt;a href="https://npmjs.com/package/undici"&gt;undici&lt;/a&gt;, I recommend keeping an eye on the &lt;a href="https://github.com/Ethan-Arrowood/undici-fetch"&gt;undici-fetch&lt;/a&gt; library. It is being developed as a WHATWG Fetch implementation based on &lt;code&gt;undici&lt;/code&gt;.&lt;/p&gt;

&lt;h1&gt;
  
  
  Tired of wasting time reading Node.js blog posts which don't actually help you improve your projects?
&lt;/h1&gt;

&lt;p&gt;&lt;a href="https://simonplend.com/newsletter/"&gt;Sign up to my weekly-ish newsletter&lt;/a&gt; and I'll let you know when I publish a new blog post which helps solve real developer problems ✨&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>security</category>
      <category>tutorial</category>
      <category>node</category>
    </item>
    <item>
      <title>What you need to know about ES modules in Node.js</title>
      <dc:creator>Simon Plenderleith</dc:creator>
      <pubDate>Mon, 18 Jan 2021 12:03:26 +0000</pubDate>
      <link>https://forem.com/simonplend/what-you-need-to-know-about-es-modules-in-node-js-2mh6</link>
      <guid>https://forem.com/simonplend/what-you-need-to-know-about-es-modules-in-node-js-2mh6</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;ECMAScript modules are the official standard format to package JavaScript code for reuse.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;em&gt;— Source: &lt;a href="https://nodejs.org/api/esm.html"&gt;Node.js documentation for ECMAScript modules&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Up until recently I've tended to avoid using ES modules and &lt;code&gt;import/export&lt;/code&gt; syntax in Node.js. I've found it hard to keep track of which versions of Node.js support this syntax out-of-the-box, as well as which ES module features they support. I've put together this short guide in the hope that I can help clear up any confusion that other folks might also have around ES modules in Node.js.&lt;/p&gt;

&lt;p&gt;This blog post isn't going to cover much about what ECMAScript (ES) modules are or how to use them. There are lots of resources out there that already do a great job of this. If you want to learn more about ES modules, check out my top links for learning more at the end of this post.&lt;/p&gt;

&lt;p&gt;As the quote from the Node.js documentation above mentions, ECMAScript modules are the official &lt;a href="https://tc39.github.io/ecma262/#sec-modules"&gt;standard format&lt;/a&gt; for modules in JavaScript. The browser JavaScript ecosystem (tooling and browsers) has had good support for ES modules for quite a while now. Meanwhile, there have been tremendous efforts over the past few years to bring ES module support to Node.js too, which has historically only used the &lt;a href="https://nodejs.org/api/modules.html"&gt;CommonJS module format&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Let's take a look at what you need to know about ES modules in Node.js today.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;I intend to update and expand this blog post as needed. If you spot anything incorrect, out-of-date, or which you feel is missing from this post, please &lt;a href="https://twitter.com/simonplend"&gt;drop me a message on Twitter&lt;/a&gt;. I want to make sure this is a useful and accurate resource!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Jump links
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Several names for the same thing&lt;/li&gt;
&lt;li&gt;Which versions of Node.js have full support for ES modules?&lt;/li&gt;
&lt;li&gt;Why are ECMAScript modules marked as 'Experimental' in the Node.js documentation?&lt;/li&gt;
&lt;li&gt;ES and CommonJS modules play nice together (mostly)&lt;/li&gt;
&lt;li&gt;Use ES modules when you start a new Node.js project&lt;/li&gt;
&lt;li&gt;It's probably not worth migrating your existing Node.js applications to use ES modules&lt;/li&gt;
&lt;li&gt;
Potential pain points

&lt;ul&gt;
&lt;li&gt;Limited test library support for mocking ES modules&lt;/li&gt;
&lt;li&gt;You can't import JSON files without using an experimental flag&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;My top links for learning more&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Several names for the same thing
&lt;/h2&gt;

&lt;p&gt;It took me a while to understand that there are several names which refer to the same thing. In this blog post I'm referring to them as "ES modules", but they are more generally known as "JavaScript modules". This is because they are a language-level module syntax for JavaScript (hence the standard I referenced earlier).&lt;/p&gt;

&lt;p&gt;In the Node.js documentation you will generally see JavaScript modules referred to as "ECMAScript modules". In the wider world, this is often abbreviated to "ES modules", or simply "ESM". These are all a reference to &lt;strong&gt;the same thing&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;JavaScript modules = ECMAScript modules = ES modules = ESM
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Which versions of Node.js have full support for ES modules?
&lt;/h2&gt;

&lt;p&gt;ES module support was &lt;a href="https://github.com/nodejs/node/blob/master/doc/changelogs/CHANGELOG_V8.md#8.5.0"&gt;added to Node.js in v8.5.0&lt;/a&gt; (yes, really!), and released in September 2017. At that stage it was highly experimental and missing a lot of the ES module features which Node.js now supports.&lt;/p&gt;

&lt;p&gt;Node.js now has full support for ES modules and you can happily use them in Node.js 12.x versions and above. I would however recommend that you use newer versions of Node.js 12.x and 14.x as they have have more mature and stable ES module support. Importantly, they also have improved interoperability with older style CommonJS modules, which are still widely used. I explain this in more detail in my article '&lt;a href="https://simonplend.com/node-js-now-supports-named-imports-from-commonjs-modules-but-what-does-that-mean/"&gt;Node.js now supports named imports from CommonJS modules, but what does that mean?&lt;/a&gt;'.&lt;/p&gt;

&lt;p&gt;Here are the versions I recommend using for the &lt;a href="https://nodejs.org/en/about/releases/"&gt;LTS release lines of Node.js&lt;/a&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;14.x — v14.13.0 or higher&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;&lt;em&gt;Why? Support for detection of CommonJS named exports, unflagged &lt;a href="https://nodejs.org/docs/latest-v14.x/api/esm.html#esm_top_level_await"&gt;top-level await&lt;/a&gt;.&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;12.x — v12.20.0 or higher&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;&lt;em&gt;Why? Support for detection of CommonJS named exports, Loading ECMAScript modules no longer requires a command-line flag.&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;10.x — Don't use ES modules in Node.js v10.x releases&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;&lt;em&gt;Why? It's missing some key ES module features. It's also end-of-life on 2021-04-30, meaning this release line  will no longer receive bug fixes after that date.&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It's not a deal breaker - you can use v12.0.0 or v14.0.0 if you like, but using the versions I've mentioned above (or higher) will make your life easier.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why are ECMAScript modules marked as 'Experimental' in the Node.js documentation?
&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;"Hold up, Simon, the Node.js 12.x and 14.x documentation for ECMAScript modules says that this feature is Experimental!"&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;ECMAScript modules are marked as 'Stable' in the &lt;a href="https://nodejs.org/docs/latest-v15.x/api/esm.html"&gt;Node.js 15.x documentation for ECMAScript modules&lt;/a&gt;, however in the &lt;a href="https://nodejs.org/docs/latest-v12.x/api/esm.html"&gt;12.x&lt;/a&gt; and &lt;a href="https://nodejs.org/docs/latest-v14.x/api/esm.html"&gt;14.x&lt;/a&gt; documentation they are marked as 'Experimental'.&lt;/p&gt;

&lt;p&gt;If Node.js 12.x and 14.x releases have full support for ES modules, what gives? I was wondering the same, so I &lt;a href="https://twitter.com/simonplend/status/1348995209884016640"&gt;asked Matteo Collina on Twitter&lt;/a&gt; (he's a member of the &lt;a href="https://github.com/nodejs/TSC"&gt;Node.js TSC&lt;/a&gt;). Myles Borins (also a member of the TSC) chimed in on the thread to explain the rationale behind ES modules being marked as 'Experimental' in the 12.x and 14.x release lines:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;We've explicitly not marked it as stable yet just in case we need to make breaking changes between 15 -&amp;gt; 16 that we may want to backport. I don't think 12 will ever get marked stable due to being maintenance.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;em&gt;(&lt;a href="https://twitter.com/MylesBorins/status/1349016345195786241"&gt;Source tweet&lt;/a&gt;)&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;If we are ready to make the commitment of not breaking anything then yes, it is stable. The 0th hour deprecation of subpath folders does leave me pause though. Also keep in mind that for LTS being experimental makes it easier to make non-breaking changes too.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;em&gt;(&lt;a href="https://twitter.com/MylesBorins/status/1349021538163585025"&gt;Source tweet&lt;/a&gt;)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;My interpretation of this is: you can safely go ahead and use ES modules in Node.js 12.x or 14.x, as the core implementation is highly unlikely to change at this stage. Keeping ES modules marked as 'Experimental' in these Node.js release lines gives the developers working on Node.js some wiggle room to change things if needed. On an open source project of this scale, that makes a lot of sense to me.&lt;/p&gt;

&lt;p&gt;Thanks to &lt;a href="https://twitter.com/matteocollina"&gt;Matteo&lt;/a&gt; and &lt;a href="https://twitter.com/MylesBorins"&gt;Myles&lt;/a&gt; for helping clarify the situation.&lt;/p&gt;

&lt;h2&gt;
  
  
  ES and CommonJS modules play nice together (mostly)
&lt;/h2&gt;

&lt;p&gt;Given that the npm registry lists almost 1.5 million packages, many of which &lt;em&gt;only&lt;/em&gt; expose a CommonJS module, it's safe to say that interoperability between the ES and CommonJS module formats is really important. The good news is that they generally work pretty well together.&lt;/p&gt;

&lt;p&gt;You can reliably &lt;code&gt;import&lt;/code&gt; a CommonJS module in an ES module e.g.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;someModule&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;someModule&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Thanks to some &lt;a href="https://github.com/nodejs/node/pull/35249"&gt;amazing work&lt;/a&gt; by &lt;a href="https://twitter.com/guybedford/"&gt;Guy Bedford&lt;/a&gt;, &lt;a href="https://github.com/GeoffreyBooth"&gt;Geoffrey Booth&lt;/a&gt;, and host of other contributors, you can also import named exports from CommonJS modules (in most cases - I've &lt;a href="https://simonplend.com/node-js-now-supports-named-imports-from-commonjs-modules-but-what-does-that-mean/"&gt;written about this in detail&lt;/a&gt;) e.g.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;someFunction&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;someObject&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;someModule&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What all of this means is that, in general, you can &lt;code&gt;import&lt;/code&gt; CommonJS modules in your ES modules and Node.js will take care of all the module format interoperability for you. I think that's pretty damn impressive.&lt;/p&gt;

&lt;p&gt;The Node.js ECMAScript module documentation has a section which covers all the details about &lt;a href="https://nodejs.org/api/esm.html#esm_interoperability_with_commonjs"&gt;Interoperability with CommonJS&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Use ES modules when you start a new Node.js project
&lt;/h2&gt;

&lt;p&gt;A new Node.js project is a great opportunity to start using ES modules. However, Node.js treats JavaScript code as CommonJS modules by default. This means you must tell it when it should treat JavaScript code as ES modules.&lt;/p&gt;

&lt;p&gt;If all of your project's code will be in ES modules you can add &lt;code&gt;"type": "module"&lt;/code&gt; in the project's &lt;code&gt;package.json&lt;/code&gt; file and you're good to go. Node.js will treat every module in your project as an ES module.&lt;/p&gt;

&lt;p&gt;Note: This doesn't mean the dependencies your project uses must use ES modules. ES and CommonJS modules have good interoperability, as explained above.&lt;/p&gt;

&lt;p&gt;If only specific modules in your project will be ES modules, give the files they're contained in an &lt;code&gt;.mjs&lt;/code&gt; extension (instead of &lt;code&gt;.js&lt;/code&gt;) and Node.js will use the ES module loader for those scripts.&lt;/p&gt;

&lt;p&gt;To learn more about configuring ES modules in Node.js I recommend reading the &lt;a href="https://nodejs.org/api/packages.html#packages_determining_module_system"&gt;Node.js Packages documentation&lt;/a&gt; on this subject.&lt;/p&gt;

&lt;h2&gt;
  
  
  It's probably not worth migrating your existing Node.js applications to use ES modules
&lt;/h2&gt;

&lt;p&gt;There's no single hugely obvious benefit to migrating an existing Node.js application from using CommonJS modules to ES modules. Unless you have a good reason to, migrating to ES modules just for the sake of it is probably not worth it. Given that modules are imported when an application starts, you're not going to see performance improvements when your application is running e.g. handling requests and serving responses.&lt;/p&gt;

&lt;p&gt;If you're working with a small application, by all means go ahead and migrate it to use ES modules for the learning experience. For large applications though, there are almost certainly other things you could better spend your time / money on (and it's likely that your employer or clients will agree).&lt;/p&gt;

&lt;p&gt;Node.js packages &lt;em&gt;should&lt;/em&gt; potentially be updated to use ES modules. They can be changed to only use ES modules, or they can be configured to offer both CommonJS and ES modules (a "dual" package). The Node.js documentation dives into the &lt;a href="https://nodejs.org/api/packages.html#packages_dual_commonjs_es_module_packages"&gt;pros and cons of the "dual" package approach&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Sindre Sorhus, author of over 1,000 Node.js packages, is planning to convert all of their packages to only use ES modules in order to &lt;a href="https://blog.sindresorhus.com/get-ready-for-esm-aa53530b3f77"&gt;"rip off the bandaid and push the ecosystem forward"&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Potential pain points
&lt;/h2&gt;

&lt;p&gt;While Node.js support for ES modules is really good, there are a couple of potential pain points you should be aware of. I expect these potential pain points to go away over time as the wider Node.js ecosystem support for ES modules improves.&lt;/p&gt;

&lt;h3&gt;
  
  
  Limited test library support for mocking ES modules
&lt;/h3&gt;

&lt;p&gt;Jest and Sinon don't yet support mocking ES modules:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Jest has &lt;a href="https://jestjs.io/docs/en/ecmascript-modules"&gt;experimental support for ES modules&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Sinon does not have support for ES modules, but there is a recently re-opened &lt;a href="https://github.com/sinonjs/sinon/issues/1832"&gt;GitHub issue&lt;/a&gt; which offers a workaround.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you need an alternative for mocking, &lt;a href="https://github.com/testdouble/testdouble.js/"&gt;testdouble.js&lt;/a&gt; has full ES module support thanks to &lt;a href="https://dev.to/giltayar/mock-all-you-want-supporting-es-modules-in-the-testdouble-js-mocking-library-3gh1"&gt;some excellent work by Gil Tayar&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;testdouble&lt;/code&gt; library is test-framework agnostic, meaning you can happily use it with any framework you're already using e.g. Mocha, Jest, Jasmine, Tape.&lt;/p&gt;

&lt;h3&gt;
  
  
  You can't import JSON files without using an experimental flag
&lt;/h3&gt;

&lt;p&gt;You can't &lt;code&gt;import&lt;/code&gt; JSON files - e.g. &lt;code&gt;some-file.json&lt;/code&gt; - without using an experimental flag when you run &lt;code&gt;node&lt;/code&gt;. This isn't a big deal for many applications, but if you're currently doing &lt;code&gt;require("some-file.json")&lt;/code&gt; in your application, this is something to be aware of.&lt;/p&gt;

&lt;p&gt;The Node.js documentation details &lt;a href="https://nodejs.org/api/esm.html#esm_no_json_module_loading"&gt;a workaround for loading JSON files in ES modules&lt;/a&gt;. You can also enable the &lt;a href="https://nodejs.org/api/esm.html#esm_json_modules"&gt;experimental JSON module loading&lt;/a&gt; if you really need to.&lt;/p&gt;

&lt;h2&gt;
  
  
  My top links for learning more
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://nodejs.org/api/esm.html"&gt;Node.js documentation for ECMAScript modules&lt;/a&gt; - The latest Node.js documentation for ES modules. It's really good and very thorough.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules"&gt;MDN Guide on JavaScript modules&lt;/a&gt; - This is a fantastic guide which provides some useful background on modules in JavaScript, along with a wealth of practical JavaScript module examples. I ❤️ MDN so much.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.youtube.com/watch?v=mMEKrHmZLpQ"&gt;NodeConf Remote 2020 - Gil Tayar - ES Modules in Node.JS&lt;/a&gt; - An excellent introduction to ES modules in Node.js (&lt;a href="https://github.com/giltayar/ah-theyre-here-esm-nodejs"&gt;companion code + link to slides&lt;/a&gt;, &lt;a href="https://simonplend.com/notes-from-nodeconf-remote-2020/#talk-es-modules-in-nodejs"&gt;my notes from this talk&lt;/a&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://redfin.engineering/node-modules-at-war-why-commonjs-and-es-modules-cant-get-along-9617135eeca1"&gt;Node Modules at War: Why CommonJS and ES Modules Can’t Get Along&lt;/a&gt; - This blog post is now a little bit out of date - e.g. ES modules can now import named CommonJS exports from many packages - but it's still well worth a read. When I read this article last year it really helped me understand the differences between the two module types and made a lot of things click for me.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>node</category>
      <category>esm</category>
      <category>ecmascriptmodules</category>
    </item>
    <item>
      <title>Send awesome structured error responses with Express</title>
      <dc:creator>Simon Plenderleith</dc:creator>
      <pubDate>Wed, 06 Jan 2021 16:05:00 +0000</pubDate>
      <link>https://forem.com/simonplend/send-awesome-structured-error-responses-with-express-3pg6</link>
      <guid>https://forem.com/simonplend/send-awesome-structured-error-responses-with-express-3pg6</guid>
      <description>&lt;p&gt;When you’re creating an Express API it can be difficult to know how to handle error cases and send consistent error responses. It becomes even more complicated if you want to send helpful error responses with extra details about what went wrong.&lt;/p&gt;

&lt;p&gt;You know these extra details are needed because they’ll also be super helpful for debugging requests to your API, but before you know it, you find yourself designing your own error response format. It all feels awkward, and like it’s probably something you shouldn’t be doing, but what alternative is there?&lt;/p&gt;

&lt;p&gt;Thankfully, there’s an awesome alternative, and you can find it in the ‘Problem Details for HTTP APIs’ specification (&lt;a href="https://tools.ietf.org/html/rfc7807" rel="noopener noreferrer"&gt;RFC7807&lt;/a&gt;). Don’t worry though, I don’t expect you to go and read the whole RFC (&lt;a href="https://en.wikipedia.org/wiki/Request_for_Comments" rel="noopener noreferrer"&gt;Request for Comments&lt;/a&gt;) document. I know that RFCs aren’t always the easiest of reads, but I think the ideas in this one are so good that I’ve done the RFC reading for you and pulled out all of the good stuff that can help you with formatting your API error responses.&lt;/p&gt;

&lt;p&gt;In this article we’ll explore the Problem Details specification and how it can help you build better APIs. By learning how to apply this well-defined and structured approach, your struggles with creating API error responses will be a thing of the past.&lt;/p&gt;

&lt;h2&gt;
  
  
  Jump links
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Introducing the ‘Problem Details for HTTP APIs’ specification&lt;/li&gt;
&lt;li&gt;Problem types and Problem details objects&lt;/li&gt;
&lt;li&gt;
Example problem details response

&lt;ul&gt;
&lt;li&gt;More details, clearer problems&lt;/li&gt;
&lt;li&gt;Breakdown of a problem details object&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

How to send problem details responses with Express

&lt;ul&gt;
&lt;li&gt;Define problem types and map them to JavaScript error classes&lt;/li&gt;
&lt;li&gt;Look up the problem details for an error&lt;/li&gt;
&lt;li&gt;Create an error handler to send a problem details response&lt;/li&gt;
&lt;li&gt;Use the problem details response error handler&lt;/li&gt;
&lt;li&gt;Example problem details error responses&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;Next steps&lt;/li&gt;

&lt;/ul&gt;

&lt;h2&gt;
  
  
  Introducing the ‘Problem Details for HTTP APIs’ specification
&lt;/h2&gt;

&lt;p&gt;The aim of the problem details specification is to define a common error format which you can use for the error responses from your API. This avoids having to invent your own error response format or, even worse, attempting to redefine the meaning of existing HTTP status codes. Seriously, don’t do this! The meaning of HTTP status codes are well documented and commonly understood for a reason.&lt;/p&gt;

&lt;p&gt;The status codes defined in the HTTP specification are very useful, and often provide enough context to the client as to what went wrong, but they don’t always convey enough information about an error to be helpful.&lt;/p&gt;

&lt;p&gt;Take for example the status code 422 (Unprocessable Entity) – as defined in the HTTP specification, it tells a client that the server understood the request body and its structure, but was unable to process it. However, that alone doesn’t tell the client specifically &lt;em&gt;what&lt;/em&gt; was wrong with the JSON that was sent in the request body. Problem details can help you solve this problem.&lt;/p&gt;

&lt;p&gt;The specification describes a problem detail as "a way to carry machine-readable details of errors in a HTTP response". Let’s take a look at how the problem details specification defines them.&lt;/p&gt;

&lt;h2&gt;
  
  
  Problem types and Problem details objects
&lt;/h2&gt;

&lt;p&gt;The problem details specification defines what a "problem type" and a "problem details object" are, and their relationship:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem type&lt;/strong&gt; – A problem type definition must include a &lt;code&gt;type&lt;/code&gt; URI (typically a URL), a short &lt;code&gt;title&lt;/code&gt; to describe it and the HTTP status code for it to be used with.&lt;/p&gt;

&lt;p&gt;If required, the definition can also specify additional properties to be included on problem details objects which use this type e.g. &lt;code&gt;balance&lt;/code&gt; and &lt;code&gt;accounts&lt;/code&gt; in the example above. These additional properties are referred to as "extensions" by the specification.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;type&lt;/code&gt; URI is effectively the namespace for the problem type definition. If the definition changes, the type should also change.&lt;/p&gt;

&lt;p&gt;You should avoid defining a new problem type when the response HTTP status code provides enough context by itself. The specification gives the following example: "a ‘write access disallowed’ problem is probably unnecessary, since a 403 Forbidden status code in response to a PUT request is self-explanatory".&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problem details object&lt;/strong&gt; – An object which includes the &lt;code&gt;type&lt;/code&gt;, &lt;code&gt;title&lt;/code&gt; and &lt;code&gt;status&lt;/code&gt; properties for a problem type. This object represents a specific occurrence of that problem type. It can optionally contain a &lt;code&gt;detail&lt;/code&gt; property – a human-readable explanation specific to this occurrence of the problem – and an &lt;code&gt;instance&lt;/code&gt; property – a URI reference that identifies the specific occurrence of the problem.&lt;/p&gt;

&lt;p&gt;A problem details object should include values for any extensions specified by the problem type definition.&lt;/p&gt;

&lt;p&gt;Problem detail objects can be formatted as XML or JSON. For the purpose of this article we’ll be using JSON formatted problem details.&lt;/p&gt;

&lt;h2&gt;
  
  
  Example problem details response
&lt;/h2&gt;

&lt;p&gt;The response body in this example contains a problem details object of the type &lt;code&gt;https://example.com/probs/out-of-credit&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;HTTP/1.1 403 Forbidden
Content-Type: application/problem+json
Content-Language: en

{
    "type": "https://example.com/probs/out-of-credit",
    "title": "You do not have enough credit.",
    "detail": "Your current balance is 30, but that costs 50.",
    "instance": "/account/12345/msgs/abc",
    "balance": 30,
    "accounts": ["/account/12345", "/account/67890"]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;— Source: &lt;a href="https://tools.ietf.org/html/rfc7807" rel="noopener noreferrer"&gt;RFC7807 – Problem Details for HTTP APIs&lt;/a&gt;&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Note how the example response above contains the header &lt;code&gt;Content-Type: application/problem+json&lt;/code&gt;. This is the media type for JSON problem details which is defined by the problem details specification. Clients can use the &lt;code&gt;Content-Type&lt;/code&gt; header in a response to determine what is contained in the response body. This allows them to handle different types of response bodies in different ways.&lt;/p&gt;

&lt;p&gt;Any response containing a problem details object must also contain the &lt;code&gt;Content-Type: application/problem+json&lt;/code&gt; header.&lt;/p&gt;

&lt;h3&gt;
  
  
  More details, clearer problems
&lt;/h3&gt;

&lt;p&gt;Including problem details in the response body allows the client to derive more information about what went wrong, and gives it a better chance of being able to handle the error appropriately. Every problem details object must have a &lt;code&gt;type&lt;/code&gt; property. The client can then use the value of the &lt;code&gt;type&lt;/code&gt; to determine the specific type of problem which occurred.&lt;/p&gt;

&lt;p&gt;In the example problem details object above (&lt;em&gt;Example 3.1&lt;/em&gt;), the problem can be identified as an "out of credit" problem when the client checks the value of the &lt;code&gt;type&lt;/code&gt; field: &lt;code&gt;https://example.com/probs/out-of-credit&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;type&lt;/code&gt; for a problem can be specific to your API, or you can potentially reuse existing ones if you wish.&lt;/p&gt;

&lt;h3&gt;
  
  
  Breakdown of a problem details object
&lt;/h3&gt;

&lt;p&gt;To better understand the properties which make up a problem details object, let’s break it down and look at each property. Let’s start with our example problem details object:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"type"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"https://example.com/probs/out-of-credit"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"title"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"You do not have enough credit."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"detail"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"Your current balance is 30, but that costs 50."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"instance"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"/account/12345/msgs/abc"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"balance"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"accounts"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"/account/12345"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"/account/67890"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let’s go through this line by line:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="nl"&gt;"type"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"https://example.com/probs/out-of-credit"&lt;/span&gt;&lt;span class="err"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;type&lt;/code&gt; URI for the problem type being used by this problem details object. The specification encourages that this is a real URL which provides human-readable documentation in HTML format. The client should use the value of this field as the primary identifier for the problem.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="nl"&gt;"title"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"You do not have enough credit."&lt;/span&gt;&lt;span class="err"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;title&lt;/code&gt; defined by the problem type.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="nl"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;403&lt;/span&gt;&lt;span class="err"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The HTTP &lt;code&gt;status&lt;/code&gt; code defined by the problem type. Should be the same as the status code sent in the response from the API.&lt;/p&gt;

&lt;p&gt;As intermediaries between the client and the server (e.g. a proxy or a cache) might modify the response status code, this value can be used by the client to determine the original status code of the response. Also useful in situations where the response body is the only available part of the response e.g. in logs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="nl"&gt;"detail"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"Your current balance is 30, but that costs 50."&lt;/span&gt;&lt;span class="err"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A human-readable explanation of the problem. It should focus on helping the client correct the problem. Machine-readable information should be added in extensions (see below). Specific to this occurrence of the problem.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="nl"&gt;"instance"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"/account/12345/msgs/abc"&lt;/span&gt;&lt;span class="err"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A URI reference for the specific problem occurrence. Typically a URL, optionally containing more information. Specific to this occurrence of the problem.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="nl"&gt;"balance"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;30&lt;/span&gt;&lt;span class="err"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="nl"&gt;"accounts"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"/account/12345"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"/account/67890"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Extensions specified by the problem type. Specific to this occurrence of the problem.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;type&lt;/code&gt;, &lt;code&gt;title&lt;/code&gt; and &lt;code&gt;status&lt;/code&gt; – as defined by a problem type – should be the same for every occurrence of the problem.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: As with any response you send from your API, you should be careful when creating problem details objects that you don’t expose any of the implementation details of your application, as this can make it potentially vulnerable to attack.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  How to send problem details responses with Express
&lt;/h2&gt;

&lt;p&gt;Now that we’ve covered the concepts and conventions of problem details, we can write some code. This code will allow us to send problem details error responses from our Express API.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: This article uses ECMAScript (ES) module syntax. ES modules are well supported in the v12 and v14 releases of Node.js.&lt;/p&gt;

&lt;p&gt;For Node.js 12.x, I recommend using v12.20.0 or higher. For Node.js 14.x, I recommend using v14.13.0 or higher. These releases of Node.js have stable ES module support, as well as &lt;a href="https://simonplend.com/node-js-now-supports-named-imports-from-commonjs-modules-but-what-does-that-mean/" rel="noopener noreferrer"&gt;improved compatibility with the older style CommonJS modules&lt;/a&gt;, which are still widely used.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Define problem types and map them to JavaScript error classes
&lt;/h3&gt;

&lt;p&gt;In this code we’re going to define two different problem types and map them to JavaScript error classes – in this case, ones that are provided by the &lt;code&gt;http-errors&lt;/code&gt; library. We’ll use these problem types later on when we create an error handler middleware.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/middleware/problem-details-response.js&lt;/span&gt;

&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;createHttpError&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;http-errors&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;defaultProblemDetails&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="cm"&gt;/**
     * This is the only URI reserved as a problem type in the
     * problem details spec. It indicates that the problem has
     * no additional semantics beyond that of the HTTP status code.
     */&lt;/span&gt;
    &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;about:blank&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;status&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;500&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;problemTypes&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="na"&gt;matchErrorClass&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;createHttpError&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;BadRequest&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;details&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;https://example-api.com/problem/invalid-user-id&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="na"&gt;title&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;User ID must be a number&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="na"&gt;status&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;400&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="na"&gt;matchErrorClass&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;createHttpError&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;Forbidden&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="na"&gt;details&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;https://example-api.com/problem/user-locked&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="na"&gt;title&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;User has been locked&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="na"&gt;status&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;403&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="p"&gt;];&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Look up the problem details for an error
&lt;/h3&gt;

&lt;p&gt;Now let’s create a function which, when passed an error object, will look through our array of &lt;code&gt;problemTypes&lt;/code&gt; for one which has been mapped to the type of error it has received:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/middleware/problem-details-response.js&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * Get the problem details which have been defined for an error.
 *
 * @param {Error} error
 * @return {Object} - Problem details (type, title, status)
 */&lt;/span&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;getProblemDetailsForError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;problemType&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;problemTypes&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;find&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;problemType&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="cm"&gt;/**
         * Test if the error object is an instance of the error
         * class specified by the problem type.
         *
         * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof
         */&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt; &lt;span class="k"&gt;instanceof&lt;/span&gt; &lt;span class="nx"&gt;problemType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;matchErrorClass&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;});&lt;/span&gt;

    &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;problemType&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="cm"&gt;/**
         * A problem type hasn't been defined for the type of error 
         * this function has received so return fallback problem details.
         */&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;defaultProblemDetails&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;problemType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;details&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Create an error handler to send a problem details response
&lt;/h3&gt;

&lt;p&gt;This error handler middleware is going to call the &lt;code&gt;getProblemDetailsByError()&lt;/code&gt; function which we just defined, and then send the problem details that it returns as a response body, along with the correct HTTP status code and &lt;code&gt;Content-Type&lt;/code&gt; header:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/middleware/problem-details-response.js&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * Send an error response using the problem details format.
 *
 * @see https://tools.ietf.org/html/rfc7807
 *
 * @param {Error} error
 * @param {Object} request - Express request object
 * @param {Object} response - Express response object
 * @param {Function} next - Express callback function
 */&lt;/span&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;problemDetailsResponseMiddleware&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nx"&gt;next&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="cm"&gt;/**
     * If response headers have already been sent,
     * delegate to the default Express error handler.
     */&lt;/span&gt;
    &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;headersSent&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;problemDetails&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;getProblemDetailsForError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="cm"&gt;/**
     * If the problem details don't contain an HTTP status code,
     * let's check the error object for a status code. If the
     * error object doesn't have one then we'll fall back to a
     * generic 500 (Internal Server Error) status code.
     */&lt;/span&gt;
    &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;problemDetails&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;status&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;problemDetails&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;status&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;statusCode&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="mi"&gt;500&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="cm"&gt;/**
     * Set the correct media type for a response containing a
     * JSON formatted problem details object.
     *
     * @see https://tools.ietf.org/html/rfc7807#section-3
     */&lt;/span&gt;
    &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Content-Type&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;application/problem+json&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="cm"&gt;/**
     * Set the response status code and a JSON formatted body
     * containing the problem details.
     */&lt;/span&gt;
    &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;status&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;problemDetails&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;status&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nf"&gt;json&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;problemDetails&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="cm"&gt;/**
     * Ensure any remaining middleware are run.
     */&lt;/span&gt;
    &lt;span class="nf"&gt;next&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="k"&gt;export&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt; &lt;span class="nx"&gt;problemDetailsResponseMiddleware&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Use the problem details response error handler
&lt;/h3&gt;

&lt;p&gt;Our error handling middlware will be run when an error object is passed to a &lt;code&gt;next()&lt;/code&gt; Express function. When the &lt;code&gt;next()&lt;/code&gt; function is called with with an error object, it automatically stops calling all regular middleware for the current request. It then starts calling any error handler middleware which has been configured.&lt;/p&gt;

&lt;p&gt;It’s time to pull everything together. Here is a complete example Express API application, configured to use our problem details error handler middleware:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/server.js&lt;/span&gt;

&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;express&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;express&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;createHttpError&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;http-errors&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nx"&gt;problemDetailsResponseMiddleware&lt;/span&gt; &lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;./middleware/problem-details-response.js&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * Express configuration and routes
 */&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;PORT&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;3000&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;app&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;express&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * In a real application this would run a query against a
 * database, but for this example it's returning a `Promise`
 * which randomly either resolves with an example user object
 * or rejects with an error.
 */&lt;/span&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;getUserData&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;reject&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;randomlyFail&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;Math&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;random&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mf"&gt;0.5&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;randomlyFail&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nf"&gt;reject&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;An error occurred while attempting to run the database query.&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
            &lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
                &lt;span class="na"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1234&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="na"&gt;first_name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Bobo&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="na"&gt;is_locked&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="p"&gt;});&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;});&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * This route demonstrates:
 *
 * - Creating an error when the user ID in the URL is not numeric.
 * - Creating an error when the (faked) user object from the database
 * is locked.
 * - Catching a (randomly faked) database error (see `getUserData()`
 * function above).
 * - Passing all error objects to the `next()` callback so our problem
 * details response error handler can take care of them.
 */&lt;/span&gt;
&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/user/:user_id&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;userIdIsNumeric&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nf"&gt;isNaN&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;params&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;user_id&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;userIdIsNumeric&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nx"&gt;createHttpError&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;BadRequest&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="nf"&gt;getUserData&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;then&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;user&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;user&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;is_locked&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nx"&gt;createHttpError&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Forbidden&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

                &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;

            &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;json&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;user&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="p"&gt;})&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;catch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;use&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;problemDetailsResponseMiddleware&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;listen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;PORT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;`Example app listening at http://localhost:&lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;PORT&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;`&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Example problem details error responses
&lt;/h3&gt;

&lt;p&gt;Here are the error responses that are produced by the code that we’ve just put together:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt; HTTP/1.1 400 Bad Request
&amp;lt; Content-Type: application/problem+json; charset=utf-8
&amp;lt; Content-Length: 106

{
    "type": "https://example-api.com/problem/invalid-user-id",
    "title": "User ID must be a number",
    "status": 400
}

&amp;lt; HTTP/1.1 403 Forbidden
&amp;lt; Content-Type: application/problem+json; charset=utf-8
&amp;lt; Content-Length: 98

{
    "type": "https://example-api.com/problem/user-locked",
    "title": "User has been locked",
    "status": 403
}

&amp;lt; HTTP/1.1 500 Internal Server Error
&amp;lt; Content-Type: application/problem+json; charset=utf-8
&amp;lt; Content-Length: 35

{
    "type": "about:blank",
    "status": 500
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Just look at those beautiful structured error responses! &lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fs.w.org%2Fimages%2Fcore%2Femoji%2F13.0.0%2F72x72%2F2728.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fs.w.org%2Fimages%2Fcore%2Femoji%2F13.0.0%2F72x72%2F2728.png" alt="✨"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Next steps
&lt;/h2&gt;

&lt;p&gt;Now that you've learnt all about the clarity that problem details can bring to your error responses, I hope you're excited to start using them in your own APIs!&lt;/p&gt;

&lt;p&gt;Want to learn more about how you can build robust APIs with Express? Take a look at some of my other articles:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://simonplend.com/how-to-handle-request-validation-in-your-express-api/" rel="noopener noreferrer"&gt;How to handle request validation in your Express API&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://simonplend.com/how-to-create-an-error-handler-for-your-express-api/" rel="noopener noreferrer"&gt;How to create an error handler for your Express API&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://simonplend.com/how-to-send-consistent-error-responses-from-your-express-api/" rel="noopener noreferrer"&gt;How to send consistent error responses from your Express API&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>express</category>
      <category>node</category>
    </item>
    <item>
      <title>How to create an error handler for your Express API</title>
      <dc:creator>Simon Plenderleith</dc:creator>
      <pubDate>Mon, 07 Dec 2020 09:30:00 +0000</pubDate>
      <link>https://forem.com/simonplend/how-to-create-an-error-handler-for-your-express-api-j26</link>
      <guid>https://forem.com/simonplend/how-to-create-an-error-handler-for-your-express-api-j26</guid>
      <description>&lt;p&gt;Express provides a default error handler, which seems great until you realise that it will only send an HTML formatted error response. This is no good for your API as you want it to always send JSON formatted responses. You start handling errors and sending error responses directly in your Express route handler functions.&lt;/p&gt;

&lt;p&gt;Before you know it, you have error handling code that’s logging errors in development to help you debug, and doing extra handling of the error object in production so you don’t accidentally leak details about your application’s internals. Even with just a few routes, your error handling code is getting messy, and even worse, it’s duplicated in each of your route handler functions. Argh!&lt;/p&gt;

&lt;p&gt;Wouldn’t it be great if you could send JSON error responses from your API &lt;em&gt;and&lt;/em&gt; have your error handling code abstracted into one place, leaving your route handlers nice and tidy? The good news is that you can, by creating your own &lt;a href="https://expressjs.com/en/guide/using-middleware.html#middleware.error-handling"&gt;error handler middleware&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In this article you’ll learn how to create an error handler middleware function which behaves in a similar way to Express’ default error handler, but sends a JSON response. Just the error handler that your API needs!&lt;/p&gt;

&lt;h2&gt;
  
  
  Jump links
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Getting errors to error handler middleware&lt;/li&gt;
&lt;li&gt;
Creating an error handler

&lt;ul&gt;
&lt;li&gt;Error handler concerns&lt;/li&gt;
&lt;li&gt;Error handler middleware function&lt;/li&gt;
&lt;li&gt;Error handler helper functions&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;
Applying the error handler middleware

&lt;ul&gt;
&lt;li&gt;Example error response&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Next steps&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Getting errors to error handler middleware
&lt;/h2&gt;

&lt;p&gt;The Express documentation has examples of an error being thrown e.g. &lt;code&gt;throw new Error('..')&lt;/code&gt;, however this only works well when all of your code is synchronous, which is almost never in Node.js. If you do &lt;code&gt;throw&lt;/code&gt; error objects in your Express application, you will need to be very careful about wrapping things so that &lt;code&gt;next()&lt;/code&gt; is always called and that the error object is passed to it.&lt;/p&gt;

&lt;p&gt;There are workarounds for error handling with asynchronous code in Express – where Promise chains are used, or &lt;code&gt;async/await&lt;/code&gt; – however the fact is that Express does not have proper support built in for asynchronous code.&lt;/p&gt;

&lt;p&gt;Error handling in Express is a broad and complex topic, and I plan to write more about this in the future, but for the purpose of this article we’ll stick with the most reliable way to handle errors in Express: always explicitly call &lt;code&gt;next()&lt;/code&gt; with an error object e.g.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="kd"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/user&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;sort&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;query&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;sort&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;sort&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;'sort' parameter missing from query string.&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="c1"&gt;// ...&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Creating an error handler
&lt;/h2&gt;

&lt;p&gt;You can create and apply multiple error handler middleware in your application e.g. one error handler for validation errors, another error handler for database errors, however we’re going to create a generic error handler for our API. This generic error handler will send a JSON formatted response, and we’ll be applying the best practices that are detailed in the &lt;a href="https://expressjs.com/en/guide/error-handling.html"&gt;official Express Error handling guide&lt;/a&gt;. If you want, you’ll then be able to build on this generic error handler to create more specific error handlers.&lt;/p&gt;

&lt;p&gt;Ok, let’s get stuck in!&lt;/p&gt;

&lt;h3&gt;
  
  
  Error handler concerns
&lt;/h3&gt;

&lt;p&gt;Here are the things we’re going to take care of with our error handler middleware:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Log an error message to &lt;a href="https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)"&gt;standard error (stderr)&lt;/a&gt;&lt;/strong&gt; – in all environments e.g. development, production.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Delegate to the default Express error handler if headers have already been sent&lt;/strong&gt; – The default error handler handles closing the connection and failing the request if you call &lt;code&gt;next()&lt;/code&gt; with an error after you’ve started writing the response, so it’s important to delegate to the default error handler if headers have already been sent (&lt;a href="https://expressjs.com/en/guide/error-handling.html#the-default-error-handler"&gt;source&lt;/a&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Extract an error HTTP status code&lt;/strong&gt; – from an Error object or the Express response object.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Extract an error message&lt;/strong&gt; – from an Error object, in all environments &lt;em&gt;except production&lt;/em&gt; so that we don’t leak details about our application or the servers it runs on. In production the response body will be empty and the HTTP status code will be what clients use to determine the type of error that has occurred.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Send the HTTP status code and the error message as a response&lt;/strong&gt; – the body will be formatted as JSON and we’ll send a &lt;code&gt;Content-Type: application/json&lt;/code&gt; header.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Ensure remaining middleware is run&lt;/strong&gt; – we might end up adding middleware after our error handler middleware in future e.g. to send request timing metrics to another server, so it’s important that our error handler middleware calls &lt;code&gt;next()&lt;/code&gt;, otherwise we could end up in debugging hell in the future.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Error handler middleware function
&lt;/h3&gt;

&lt;p&gt;In Express, error handling middleware are middleware functions that accept four arguments: &lt;code&gt;(error, request, response, next)&lt;/code&gt;. That first &lt;code&gt;error&lt;/code&gt; argument is typically an &lt;code&gt;Error&lt;/code&gt; object which the middleware will then handle.&lt;/p&gt;

&lt;p&gt;As we saw above, there are quite a few concerns that our error handler needs to cover, so let’s first take a look at the error handler middleware function. Afterwards we’ll dig into the helper functions which it calls.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/middleware/error-handler.js&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;NODE_ENVIRONMENT&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;env&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;NODE_ENV&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;development&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * Generic Express error handler middleware.
 *
 * @param {Error} error - An Error object.
 * @param {Object} request - Express request object
 * @param {Object} response - Express response object
 * @param {Function} next - Express `next()` function
 */&lt;/span&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;errorHandlerMiddleware&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;errorMessage&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;getErrorMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="nx"&gt;logErrorMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;errorMessage&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="cm"&gt;/**
     * If response headers have already been sent,
     * delegate to the default Express error handler.
     */&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;headersSent&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;errorResponse&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="na"&gt;statusCode&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;getHttpStatusCode&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt; &lt;span class="p"&gt;}),&lt;/span&gt;
        &lt;span class="na"&gt;body&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;undefined&lt;/span&gt;
    &lt;span class="p"&gt;};&lt;/span&gt;

    &lt;span class="cm"&gt;/**
     * Error messages and error stacks often reveal details
     * about the internals of your application, potentially
     * making it vulnerable to attack, so these parts of an
     * Error object should never be sent in a response when
     * your application is running in production.
     */&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;NODE_ENVIRONMENT&lt;/span&gt; &lt;span class="o"&gt;!==&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;production&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;errorResponse&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;body&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;errorMessage&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="cm"&gt;/**
     * Set the response status code.
     */&lt;/span&gt;
    &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;status&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;errorResponse&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;statusCode&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="cm"&gt;/**
     * Send an appropriately formatted response.
     *
     * The Express `res.format()` method automatically
     * sets `Content-Type` and `Vary: Accept` response headers.
     *
     * @see https://expressjs.com/en/api.html#res.format
     *
     * This method performs content negotation.
     *
     * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation
     */&lt;/span&gt;
    &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;format&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
        &lt;span class="c1"&gt;//&lt;/span&gt;
        &lt;span class="c1"&gt;// Callback to run when `Accept` header contains either&lt;/span&gt;
        &lt;span class="c1"&gt;// `application/json` or `*/*`, or if it isn't set at all.&lt;/span&gt;
        &lt;span class="c1"&gt;//&lt;/span&gt;
        &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;application/json&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="cm"&gt;/**
             * Set a JSON formatted response body.
             * Response header: `Content-Type: `application/json`
             */&lt;/span&gt;
            &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;json&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;message&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;errorResponse&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;body&lt;/span&gt; &lt;span class="p"&gt;});&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="cm"&gt;/**
         * Callback to run when none of the others are matched.
         */&lt;/span&gt;
        &lt;span class="na"&gt;default&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="cm"&gt;/**
             * Set a plain text response body.
             * Response header: `Content-Type: text/plain`
             */&lt;/span&gt;
            &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;type&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;text/plain&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nx"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;errorResponse&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;body&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="p"&gt;});&lt;/span&gt;

    &lt;span class="cm"&gt;/**
     * Ensure any remaining middleware are run.
     */&lt;/span&gt;
    &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nx"&gt;module&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;exports&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;errorHandlerMiddleware&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Error handler helper functions
&lt;/h3&gt;

&lt;p&gt;There are three helper functions which are called by our error handler middleware function above:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;getErrorMessage()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;logErrorMessage()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;getHttpStatusCode()&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The benefit of creating these individual helper functions is that in future if we decide to create more specific error handling middleware e.g. to handle validation errors, we can use these helper functions as the basis for that new middleware.&lt;/p&gt;

&lt;p&gt;Each of these helper functions are quite short, but they contain some important logic:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/middleware/error-handler.js&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * Extract an error stack or error message from an Error object.
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
 *
 * @param {Error} error
 * @return {string} - String representation of the error object.
 */&lt;/span&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;getErrorMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="cm"&gt;/**
     * If it exists, prefer the error stack as it usually
     * contains the most detail about an error:
     * an error message and a function call stack.
     */&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;stack&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;stack&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;typeof&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;toString&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;function&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;toString&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="dl"&gt;""&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * Log an error message to stderr.
 *
 * @see https://nodejs.org/dist/latest-v14.x/docs/api/console.html#console_console_error_data_args
 *
 * @param {string} error
 */&lt;/span&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;logErrorMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * Determines if an HTTP status code falls in the 4xx or 5xx error ranges.
 *
 * @param {number} statusCode - HTTP status code
 * @return {boolean}
 */&lt;/span&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;isErrorStatusCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;statusCode&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;statusCode&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;=&lt;/span&gt; &lt;span class="mi"&gt;400&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="nx"&gt;statusCode&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="mi"&gt;600&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * Look for an error HTTP status code (in order of preference):
 *
 * - Error object (`status` or `statusCode`)
 * - Express response object (`statusCode`)
 *
 * Falls back to a 500 (Internal Server Error) HTTP status code.
 *
 * @param {Object} options
 * @param {Error} options.error
 * @param {Object} options.response - Express response object
 * @return {number} - HTTP status code
 */&lt;/span&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;getHttpStatusCode&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt; &lt;span class="p"&gt;})&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="cm"&gt;/**
     * Check if the error object specifies an HTTP
     * status code which we can use.
     */&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;statusCodeFromError&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;status&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;statusCode&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;isErrorStatusCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;statusCodeFromError&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;statusCodeFromError&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="cm"&gt;/**
     * The existing response `statusCode`. This is 200 (OK)
     * by default in Express, but a route handler or
     * middleware might already have set an error HTTP
     * status code (4xx or 5xx).
     */&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;statusCodeFromResponse&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;statusCode&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;isErrorStatusCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;statusCodeFromResponse&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;statusCodeFromResponse&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="cm"&gt;/**
     * Fall back to a generic error HTTP status code.
     * 500 (Internal Server Error).
     *
     * @see https://httpstatuses.com/500
     */&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="mi"&gt;500&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now that we've created our error handler middleware, it's time to apply it in our application.&lt;/p&gt;

&lt;h2&gt;
  
  
  Applying the error handler middleware
&lt;/h2&gt;

&lt;p&gt;Here is a complete example Express API application. It uses the &lt;a href="https://www.npmjs.com/package/http-errors"&gt;http-errors&lt;/a&gt; library to add an HTTP status code to an error object and then passes it to the &lt;code&gt;next()&lt;/code&gt; callback function. Express will then call our error handler middleware with the error object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// src/server.js&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;express&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;require&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;express&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;createHttpError&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;require&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;http-errors&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;errorHandlerMiddleware&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;require&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;./middleware/error-handler.js&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * In a real application this would run a query against a
 * database, but for this example it's always returning a
 * rejected `Promise` with an error message.
 */&lt;/span&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;getUserData&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;reject&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;An error occurred while attempting to run the database query.&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
    &lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * Express configuration and routes
 */&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;PORT&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;3000&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;app&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;express&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * This route demonstrates:
 *
 * - Catching a (faked) database error (see `getUserData()` function above).
 * - Using the `http-errors` library to extend the error object with
 * an HTTP status code.
 * - Passing the error object to the `next()` callback so our generic
 * error handler can take care of it.
 */&lt;/span&gt;
&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="kd"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/user&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;getUserData&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;userData&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;json&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;userData&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;catch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="cm"&gt;/**
             * 500 (Internal Server Error) - Something has gone wrong in your application.
             */&lt;/span&gt;
            &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;httpError&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;createHttpError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;500&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

            &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;httpError&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="p"&gt;});&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * Any error handler middleware must be added AFTER you define your routes.
 */&lt;/span&gt;
&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;use&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;errorHandlerMiddleware&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;listen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;PORT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;`Example app listening at http://localhost:&lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;PORT&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;`&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;You can learn how to use the &lt;code&gt;http-errors&lt;/code&gt; library in my article on '&lt;a href="https://simonplend.com/how-to-send-consistent-error-responses-from-your-express-api/"&gt;How to send consistent error responses from your Express API&lt;/a&gt;'.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Example error response
&lt;/h3&gt;

&lt;p&gt;Here's an example GET request with cURL to our &lt;code&gt;/user&lt;/code&gt; endpoint, with the corresponding error response generated by our error handler middleware (in development):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ curl -v http://localhost:3000/user

&amp;gt; GET /user HTTP/1.1
&amp;gt; Host: localhost:3000
&amp;gt; User-Agent: curl/7.68.0
&amp;gt; Accept: */*
&amp;gt; 
&amp;lt; HTTP/1.1 500 Internal Server Error
&amp;lt; X-Powered-By: Express
&amp;lt; Vary: Accept
&amp;lt; Content-Type: application/json; charset=utf-8
&amp;lt; Content-Length: 279
&amp;lt; Connection: keep-alive
&amp;lt; 

{"message":"InternalServerError: An error occurred while attempting to run the database query.\n at /dev/example/src/server.js:262:22\n at processTicksAndRejections (internal/process/task_queues.js:97:5)"}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Next steps
&lt;/h2&gt;

&lt;p&gt;You might have noticed that we're not sending a response body in production. This is due to the fact that sending the error object's message or call stack would leak details about our application, making it vulnerable to potential attackers. As we've created a generic error handler middleware here, the best that we can do is send back a suitable error HTTP status code in production.&lt;/p&gt;

&lt;p&gt;If you know the types of the errors that your error handler middleware will be receiving (which you can check for example with &lt;code&gt;error instanceof ErrorClass&lt;/code&gt;), you could define some production safe error messages which correspond with those error types. These production safe error messages could then be sent in the response body, providing more useful context about the error which has occurred. Give it a try!&lt;/p&gt;

</description>
      <category>express</category>
      <category>node</category>
      <category>middleware</category>
    </item>
    <item>
      <title>How to handle request validation in your Express API</title>
      <dc:creator>Simon Plenderleith</dc:creator>
      <pubDate>Fri, 20 Nov 2020 10:15:00 +0000</pubDate>
      <link>https://forem.com/simonplend/how-can-you-handle-request-validation-in-your-express-based-api-4a2i</link>
      <guid>https://forem.com/simonplend/how-can-you-handle-request-validation-in-your-express-based-api-4a2i</guid>
      <description>&lt;p&gt;Let’s be real, adding request validation to your Express based API isn’t particularly exciting, but you know that it is an important foundational part of building an API, so you sit down to figure out what you’re going to do.&lt;/p&gt;

&lt;p&gt;You try and pick a validation library, but it’s more difficult than you expect because they’re all quite different from each other, and it’s not clear what benefits one has over another. Perhaps you start to build your own custom validation, but it quickly starts to feel very messy. You just want to be able to put something reliable in place for validation and move on to building the interesting stuff in your API. You wonder to yourself, is adding request validation to an Express API really this difficult?!&lt;/p&gt;

&lt;p&gt;In this article I’ll introduce you to &lt;a href="https://json-schema.org/"&gt;JSON Schema&lt;/a&gt;, which allows you to describe the format that you expect data to be in and then validate data against it. I’ll then show you how to use JSON Schema to validate requests to your Express based API and send validation errors back in the response. By the time we’re done you won’t have to waste time figuring out how to handle request validation ever again.&lt;/p&gt;

&lt;h2&gt;
  
  
  Jump links
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Getting to grips with JSON Schema&lt;/li&gt;
&lt;li&gt;Why should I use JSON Schema and not validation library X?&lt;/li&gt;
&lt;li&gt;How to integrate validation with JSON schemas into your application&lt;/li&gt;
&lt;li&gt;Pulling it all together&lt;/li&gt;
&lt;li&gt;Wrapping things up&lt;/li&gt;
&lt;li&gt;Handy JSON Schema links&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Getting to grips with JSON Schema
&lt;/h2&gt;

&lt;p&gt;JSON Schema is very powerful, but for now we’ll only use a few of its features so that we can get comfortable with how it works.&lt;/p&gt;

&lt;p&gt;Here’s an example JSON schema showing some of the types and keywords which you can use to describe how an object should be structured:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight json"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"type"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"object"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"required"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"name"&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="nl"&gt;"properties"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="nl"&gt;"name"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
            &lt;/span&gt;&lt;span class="nl"&gt;"type"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"string"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
            &lt;/span&gt;&lt;span class="nl"&gt;"minLength"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="p"&gt;},&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="nl"&gt;"age"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="w"&gt;
            &lt;/span&gt;&lt;span class="nl"&gt;"type"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="s2"&gt;"integer"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="w"&gt;
            &lt;/span&gt;&lt;span class="nl"&gt;"minimum"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="w"&gt; &lt;/span&gt;&lt;span class="mi"&gt;18&lt;/span&gt;&lt;span class="w"&gt;
        &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
    &lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="w"&gt;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The nice thing about JSON Schema is that it tends to be self-documenting, which is great for us humans who want to quickly understand what’s going on. At the same time, JSON schemas are also machine readable, meaning that we can use a JSON Schema validator library to validate the data which our application receives against a schema.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;I recommend you finish reading this article before diving deeper into all of the features of JSON Schema, but if you’re keen to learn more about them right now you can jump to the handy links I’ve collected at the end.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Why should I use JSON Schema and not validation library X?
&lt;/h2&gt;

&lt;p&gt;Here are the things which I think make JSON Schema a uniquely ideal tool for data validation in your Node.js application.&lt;/p&gt;

&lt;h3&gt;
  
  
  No library, framework or language lock-in
&lt;/h3&gt;

&lt;p&gt;There are &lt;a href="https://json-schema.org/implementations.html"&gt;JSON Schema validation libraries&lt;/a&gt; available for every popular programming language.&lt;/p&gt;

&lt;p&gt;JSON Schema doesn’t tie you to a library or a framework e.g. &lt;a href="https://www.npmjs.com/package/joi"&gt;Joi&lt;/a&gt;, &lt;a href="https://www.npmjs.com/package/yup"&gt;Yup&lt;/a&gt;, &lt;a href="https://www.npmjs.com/package/validate.js"&gt;validate.js&lt;/a&gt;. These Node.js libraries all take their own approach to defining validation rules and error messages, so the things you need to learn to use them will become obsolete if they stop being developed or become deprecated.&lt;/p&gt;

&lt;p&gt;This almost happened with the Joi validation library earlier this year, when the lead maintainer of the Hapi.js framework which it was a part of announced plans to deprecate all modules. Fortunately Joi itself seems to have been adopted by &lt;a href="https://twitter.com/sidewaytech/status/1284237116705136640"&gt;some kind souls&lt;/a&gt;, but it should make you think twice about committing to a specific library when more widely supported tooling is available.&lt;/p&gt;

&lt;h3&gt;
  
  
  Move between Node.js frameworks, or even languages, and take your schemas with you
&lt;/h3&gt;

&lt;p&gt;Because JSON schemas aren’t tied to a framework, it’s one less thing to worry about if you decide to migrate away from Express to something else e.g. Fastify, which has built in support for &lt;a href="https://www.fastify.io/docs/latest/Validation-and-Serialization/"&gt;request validation and response serialization&lt;/a&gt; with JSON Schema.&lt;/p&gt;

&lt;p&gt;Because JSON Schema itself is language agnostic and widely supported, if you ever decide to rewrite your Node.js applications in a completely different language e.g. Go or Rust, you won’t need to rewrite all of the validation – you can take your JSON schemas with you!&lt;/p&gt;

&lt;h3&gt;
  
  
  Active and supportive community
&lt;/h3&gt;

&lt;p&gt;There is an active community of folks on Slack who are very willing to help you out. The official &lt;a href="https://json-schema.org/"&gt;JSON Schema website&lt;/a&gt; has a link which you can use to join.&lt;/p&gt;

&lt;h3&gt;
  
  
  JSON Schema is on a path to becoming a standard
&lt;/h3&gt;

&lt;p&gt;JSON Schema is &lt;a href="https://json-schema.org/#project-status"&gt;on its way&lt;/a&gt; to becoming a standard. It’s currently &lt;a href="https://json-schema.org/specification-links.html"&gt;defined in a collection of IETF Internet-Draft documents&lt;/a&gt;, with the intention that they will be adopted by an IETF Working Group and shepherded through to RFC status, making them eligible to become an &lt;a href="https://en.wikipedia.org/wiki/Internet_Standard"&gt;Internet Standard&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to integrate validation with JSON schemas into your application
&lt;/h2&gt;

&lt;h3&gt;
  
  
  First things first, parse that JSON request body
&lt;/h3&gt;

&lt;p&gt;Your application will need to be able to handle POST requests with a JSON body, where the &lt;code&gt;Content-Type&lt;/code&gt; header is &lt;code&gt;application/json&lt;/code&gt;. Here’s an example of how you can make a request like this on the command line with &lt;a href="https://curl.se/"&gt;cURL&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;curl --request POST \
  --url http://localhost:3000/user \
  --header 'Content-Type: application/json' \
  --data '{
    "first_name": "Test",
    "last_name": "Person",
    "age": true
}'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The package most commonly used for handling the JSON body of a POST request in Express based applications is &lt;code&gt;body-parser&lt;/code&gt;. If you already have it installed and configured in your application, that’s great, and you can skip on to the next section, otherwise let’s get it set up:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npm &lt;span class="nb"&gt;install &lt;/span&gt;body-parser
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And then add it into your application:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;bodyParserMiddleware&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;require&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;body-parser&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * You can add the `body-parser` middleware anywhere after
 * you've created your Express application, but you must do
 * it before you define your routes.
 *
 * By using the `json()` method, if a request comes into your
 * application with a `Content-Type: application/json` header,
 * this middleware will treat the request body as a JSON string.
 * It will attempt to parse it with `JSON.parse()` and set the
 * resulting object (or array) on a `body` property of the request
 * object, which you can access in your route handlers, or other
 * general middleware.
 */&lt;/span&gt;
&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;use&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;bodyParserMiddleware&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;json&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Integrate Ajv (Another JSON Schema Validator) into your application
&lt;/h3&gt;

&lt;p&gt;The &lt;a href="https://ajv.js.org/"&gt;Ajv (Another JSON Schema Validator)&lt;/a&gt; library is the most popular JSON Schema validator written for JavaScript (Node.js and browser). You can use Ajv directly, however for an Express based API it’s nice to be able to use middleware to validate request data which has been sent to an endpoint before that endpoint’s route handler is run. This allows you to prevent things like accidentally storing invalid data in your database. It also means that you can handle validation errors and send a useful error response back to the client. The &lt;a href="https://github.com/vacekj/express-json-validator-middleware"&gt;express-json-validator-middleware&lt;/a&gt; package can help you with all of this.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;express-json-validator-middleware&lt;/code&gt; package uses Ajv and allows you to pass configuration options to it. This is great as it means you have full control to configure Ajv as if you were using it directly.&lt;/p&gt;

&lt;p&gt;Before we integrate this middleware into our application, let’s get it installed:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npm &lt;span class="nb"&gt;install &lt;/span&gt;express-json-validator-middleware
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once you have it installed you need to require it in your application and configure it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;Validator&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;require&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;express-json-validator-middleware&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * Create a new instance of the `express-json-validator-middleware`
 * `Validator` class and pass in Ajv options.
 *
 * `allErrors` = Check all schema rules and collect all errors.
 * The Ajv default is for it to return after the first error.
 *
 * @see https://github.com/ajv-validator/ajv/blob/master/docs/api.md#options
 */&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;validate&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nx"&gt;Validator&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;allErrors&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt; &lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Using a JSON schema to validate a response
&lt;/h3&gt;

&lt;p&gt;In this next code snippet we’re going to do two things:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Define a JSON schema which describes the data which we expect to receive when a client calls our API endpoint to create a new user. We want the data to be an object which always has a &lt;code&gt;first_name&lt;/code&gt; and a &lt;code&gt;last_name&lt;/code&gt; property. This object can optionally include an &lt;code&gt;age&lt;/code&gt; property, and if it does, the value of that property must be an integer which is greater than or equal to 18.&lt;/li&gt;
&lt;li&gt;We’re going to use the user schema which we’ve defined to validate requests to our &lt;code&gt;POST /user&lt;/code&gt; API endpoint.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;userSchema&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;object&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;required&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;first_name&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;last_name&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
    &lt;span class="na"&gt;properties&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="na"&gt;first_name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;string&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="na"&gt;minLength&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="na"&gt;last_name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;string&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="na"&gt;minLength&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="na"&gt;age&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;integer&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="na"&gt;minimum&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;18&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * Here we're using the `validate()` method from our `Validator`
 * instance. We pass it an object telling it which request properties
 * we want to validate, and what JSON schema we want to validate the
 * value of each property against. In this example we are going to
 * validate the `body` property of any requests to the POST /user
 * endpoint against our `userSchema` JSON schema.
 *
 * The `validate()` method compiles the JSON schema with Ajv, and
 * then returns a middleware function which will be run every time a
 * request is made to this endpoint. This middleware function will
 * take care of running the validation which we've configured.
 *
 * If the request `body` validates against our `userSchema`, the
 * middleware function will call the `next()` Express function which
 * was passed to it and our route handler function will be run. If Ajv
 * returns validation errors, the middleware will call the `next()`
 * Express function with an error object which has a `validationErrors`
 * property containing an array of validation errors, and our route handler
 * function will NOT be run. We'll look at where that error object gets
 * passed to and how we can handle it in the next step.
 */&lt;/span&gt;
&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;post&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/user&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nx"&gt;validate&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;body&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;userSchema&lt;/span&gt; &lt;span class="p"&gt;}),&lt;/span&gt;
    &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;createUserRouteHandler&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="cm"&gt;/**
         * Normally you'd save the data you've received to a database,
         * but for this example we'll just send it back in the response.
         */&lt;/span&gt;
        &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;json&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;body&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

        &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Sending validation errors in a response
&lt;/h3&gt;

&lt;p&gt;In the previous code snippet we learnt how to integrate the &lt;code&gt;express-json-validator-middleware&lt;/code&gt; so that it will validate a request body against our user schema. If there are validation errors, the middleware will call the &lt;code&gt;next()&lt;/code&gt; Express function with an error object. This error object has a &lt;code&gt;validationErrors&lt;/code&gt; property containing an array of validation errors. When an error object is passed to a &lt;code&gt;next()&lt;/code&gt; Express function, it automatically stops calling all regular middleware for the current request, and starts calling any error handler middleware which has been configured.&lt;/p&gt;

&lt;p&gt;The difference between error handler middleware and regular middleware is that error handler middleware functions specify four parameters instead of three i.e. &lt;code&gt;(error, request, response, next)&lt;/code&gt;. To be able to handle the error created by &lt;code&gt;express-json-validator-middleware&lt;/code&gt; and send a useful error response back to the client we need to create our own error handler middleware and configure our Express application to use.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="cm"&gt;/**
 * Error handler middleware for handling errors of the
 * `ValidationError` type which are created by
 * `express-json-validator-middleware`. Will pass on
 * any other type of error to be handled by subsequent
 * error handling middleware.
 *
 * @see https://expressjs.com/en/guide/error-handling.html
 *
 * @param {Error} error - Error object
 * @param {Object} request - Express request object
 * @param {Object} response - Express response object
 * @param {Function} next - Express next function
 */&lt;/span&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;validationErrorMiddleware&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="cm"&gt;/**
     * If the `error` object is not a `ValidationError` created
     * by `express-json-validator-middleware`, we'll pass it in
     * to the `next()` Express function and let any other error
     * handler middleware take care of it. In our case this is
     * the only error handler middleware, so any errors which
     * aren't of the `ValidationError` type will be handled by
     * the default Express error handler.
     *
     * @see https://expressjs.com/en/guide/error-handling.html#the-default-error-handler
     */&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;isValidationError&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt; &lt;span class="k"&gt;instanceof&lt;/span&gt; &lt;span class="nx"&gt;ValidationError&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;isValidationError&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="cm"&gt;/**
     * We'll send a 400 (Bad Request) HTTP status code in the response.
     * This let's the client know that there was a problem with the
     * request they sent. They will normally implement some error handling
     * for this situation.
     *
     * We'll also grab the `validationErrors` array from the error object
     * which `express-json-validator-middleware` created for us and send
     * it as a JSON formatted response body.
     *
     * @see https://httpstatuses.com/400
     */&lt;/span&gt;
    &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;status&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;400&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nx"&gt;json&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
        &lt;span class="na"&gt;errors&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;validationErrors&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;});&lt;/span&gt;

    &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This allows us to send back error responses like this when there is an error validating the request body against our user schema:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt; HTTP/1.1 400 Bad Request
&amp;lt; Content-Type: application/json; charset=utf-8
&amp;lt; Content-Length: 187

{
    "errors": {
        "body": [
            {
                "keyword": "minimum",
                "dataPath": ".age",
                "schemaPath": "#/properties/age/minimum",
                "params": {
                    "comparison": "&amp;gt;=",
                    "limit": 18,
                    "exclusive": false
                },
                "message": "should be &amp;gt;= 18"
            }
        ]
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Pulling it all together
&lt;/h2&gt;

&lt;p&gt;Here are all of the code snippets in this article combined into a complete Express API application:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;express&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;require&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;express&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;bodyParserMiddleware&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;require&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;body-parser&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;Validator&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nx"&gt;ValidationError&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;require&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;express-json-validator-middleware&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nx"&gt;validate&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nx"&gt;Validator&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;allErrors&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt; &lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;validationErrorMiddleware&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;isValidationError&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt; &lt;span class="k"&gt;instanceof&lt;/span&gt; &lt;span class="nx"&gt;ValidationError&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;isValidationError&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;status&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;400&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nx"&gt;json&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt;
        &lt;span class="na"&gt;errors&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;validationErrors&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;});&lt;/span&gt;

    &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;userSchema&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;object&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="na"&gt;required&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;first_name&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;last_name&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;],&lt;/span&gt;
    &lt;span class="na"&gt;properties&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="na"&gt;first_name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;string&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="na"&gt;minLength&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="na"&gt;last_name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;string&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="na"&gt;minLength&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
        &lt;span class="na"&gt;age&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;integer&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="na"&gt;minimum&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;18&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;},&lt;/span&gt;
    &lt;span class="p"&gt;},&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;app&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;express&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;use&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;bodyParserMiddleware&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;json&lt;/span&gt;&lt;span class="p"&gt;());&lt;/span&gt;

&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;post&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/user&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nx"&gt;validate&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;body&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nx"&gt;userSchema&lt;/span&gt; &lt;span class="p"&gt;}),&lt;/span&gt;
    &lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;createUserRouteHandler&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;json&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;body&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

        &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;use&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;validationErrorMiddleware&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;PORT&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;process&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;env&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;PORT&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="mi"&gt;3000&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;listen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;PORT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;`Example app listening at http://localhost:&lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;PORT&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;`&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Note: For the purpose of this article I’ve combined everything into one block of code, but in a real application I would recommend separating the concerns into separate files.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Wrapping things up
&lt;/h2&gt;

&lt;p&gt;You might have guessed from this article that I’m a big fan of JSON Schema. I think that it’s an excellent way to approach request validation, and I hope that you’re now ready to give it a try in your Express based applications.&lt;/p&gt;

&lt;p&gt;In my next article I’ll be showing you how you to transform that raw errors array from Ajv into an even more helpful error response by applying the &lt;a href="https://tools.ietf.org/html/rfc7807"&gt;"problem detail" specification&lt;/a&gt;. If you want to know when I publish this new article hit the 'Follow' button at the top of this page!&lt;/p&gt;

&lt;h2&gt;
  
  
  Handy JSON Schema links
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://json-schema.org/understanding-json-schema/"&gt;Understanding JSON Schema book&lt;/a&gt; – An excellent free online book which will teach you the fundamentals and help you make the most of JSON Schema (also available in &lt;a href="https://json-schema.org/understanding-json-schema/UnderstandingJSONSchema.pdf"&gt;PDF format&lt;/a&gt;).&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://json-schema.org/specification-links.html"&gt;JSON Schema Specification Links&lt;/a&gt; – The latest specifications for JSON Schema.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/ajv-validator/ajv-errors"&gt;ajv-errors&lt;/a&gt; – An Ajv plugin for defining custom error messages in your schemas.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/fastify/fluent-schema"&gt;fluent-schema&lt;/a&gt; – Writing large JSON schemas is sometimes overwhelming, but this powerful little library allows you to write JavaScript to generate them.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>express</category>
      <category>node</category>
      <category>jsonschema</category>
    </item>
    <item>
      <title>How to restore changes which you’ve reverted from your main git branch</title>
      <dc:creator>Simon Plenderleith</dc:creator>
      <pubDate>Thu, 12 Nov 2020 17:59:56 +0000</pubDate>
      <link>https://forem.com/simonplend/how-to-restore-changes-which-you-ve-reverted-from-your-main-git-branch-16d</link>
      <guid>https://forem.com/simonplend/how-to-restore-changes-which-you-ve-reverted-from-your-main-git-branch-16d</guid>
      <description>&lt;p&gt;Reverting code changes and restoring them with git is one of those things that feels like it’s going to be straightforward, but often ends up turning your git history into a hot mess. A messy history is one thing, but not even being able to restore the code changes you reverted? That’s a nightmare!&lt;/p&gt;

&lt;p&gt;When you start looking at the documentation for git you’ll probably end up despairing at how complicated it seems to do something which you know &lt;em&gt;should&lt;/em&gt; be simple. Wouldn’t it be great if you could revert and restore changes whenever you need to with git? The good news is that it’s not difficult to do when you know how, but first we need to understand why your code changes aren’t being restored in the way that you expect them to be.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why aren’t my code changes being restored?!
&lt;/h2&gt;

&lt;p&gt;If you’ve ever reverted code changes from your &lt;code&gt;main&lt;/code&gt; branch and then later tried to restore them, this git workflow is probably familiar to you:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--o1Z4NfvS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://simonplend.com/wp-content/uploads/2020/11/diagram.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--o1Z4NfvS--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://simonplend.com/wp-content/uploads/2020/11/diagram.png" alt="Diagram showing the git workflow of merging a feature branch into the main branch, finding a bug, reverting the changes which were merged in, then adding a bug fix to the feature branch, merging it into the main branch again and finding that the code changes made in the feature branch before the bug fix are not showing in the main branch."&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The reason that the code changes made before the bug fix are "missing" from &lt;code&gt;main&lt;/code&gt; when you try to merge &lt;code&gt;feature-branch&lt;/code&gt; in again is because the commits containing those changes were already merged in to &lt;code&gt;main&lt;/code&gt; earlier.&lt;/p&gt;

&lt;p&gt;To bring the changes back in to &lt;code&gt;main&lt;/code&gt; which you reverted, as well as any bug fix, you need to create a fresh branch and revert the commit which reverted the changes. Huh?! Let’s head to the command line and see what that looks like.&lt;/p&gt;

&lt;h2&gt;
  
  
  Put ya revert down flip it and revert it
&lt;/h2&gt;

&lt;p&gt;Ok, now for the good stuff: the git commands which will restore order to the universe and let you get on with your life. The following commands assume you’re in a situation where your &lt;code&gt;main&lt;/code&gt; branch has had &lt;code&gt;feature-branch&lt;/code&gt; merged in, and that the code changes introduced by that merge have then been reverted.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Make sure your local main branch is up-to-date.&lt;/span&gt;
git checkout main
git pull

&lt;span class="c"&gt;# Create a new branch off of main.&lt;/span&gt;
&lt;span class="c"&gt;# This is where you're going to bring back the changes which were reverted.&lt;/span&gt;
git checkout &lt;span class="nt"&gt;-b&lt;/span&gt; restore-feature-x

&lt;span class="c"&gt;# You need to look at your git log and copy the SHA hash for the commit that&lt;/span&gt;
&lt;span class="c"&gt;# you created when you reverted the changes e.g. c4780a2bf0e22a93ece0b42cf5e42a9a21cfcbca&lt;/span&gt;
&lt;span class="c"&gt;# You'll use this commit SHA hash which you've copied in the next command.&lt;/span&gt;
git log

&lt;span class="c"&gt;# Revert the commit where you reverted the changes.&lt;/span&gt;
git revert COMMIT_SHA_HASH_YOU_JUST_COPIED

&lt;span class="c"&gt;# This branch will now contain the changes which you originally reverted,&lt;/span&gt;
&lt;span class="c"&gt;# and you can proceed to make any bug fixes or further changes that are required.&lt;/span&gt;
&lt;span class="c"&gt;#&lt;/span&gt;
&lt;span class="c"&gt;# You can diff this branch against the main branch to confirm that when you merge&lt;/span&gt;
&lt;span class="c"&gt;# this branch in, main will contain all the changes that you want it to.&lt;/span&gt;
git diff main..
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I recommend that you follow this one simple rule for restoring changes that you’ve reverted with git: revert the revert, every time. If you don’t, you’re very likely to end up fighting git, which nobody wants to do, not even on a good day.&lt;/p&gt;

</description>
      <category>git</category>
    </item>
    <item>
      <title>Notes from NodeConf Remote 2020</title>
      <dc:creator>Simon Plenderleith</dc:creator>
      <pubDate>Mon, 09 Nov 2020 11:36:38 +0000</pubDate>
      <link>https://forem.com/simonplend/notes-from-nodeconf-remote-2020-npg</link>
      <guid>https://forem.com/simonplend/notes-from-nodeconf-remote-2020-npg</guid>
      <description>&lt;p&gt;&lt;a href="https://www.nodeconfremote.com/"&gt;NodeConf Remote 2020&lt;/a&gt; was held on November 2nd – 6th as a free online event, standing in for the annual NodeConf EU conference, which for obvious reasons couldn’t be held in person due to the pandemic. I tuned in when I could during the two days of excellent talks and I wrote up notes during the talks I watched.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Fair warning: The talk notes I’m sharing here are in a fairly raw state and provided with no warranty – I tried to make sure I noted down all the details accurately, but I can’t guarantee that it’s all 100% correct!&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;You can watch all of the talks from NodeConf Remote 2020 on the &lt;a href="https://www.youtube.com/playlist?list=PL0CdgOSSGlBalMPxFFycq7OIqQF8cJS28"&gt;NearForm YouTube channel&lt;/a&gt;.&lt;/p&gt;




&lt;h2&gt;
  
  
  Jump links
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Talk: Aaaaaaaaaaaaaah, They’re Here! ES Modules in Node.JS&lt;/li&gt;
&lt;li&gt;Talk: Can we double HTTP client throughput?&lt;/li&gt;
&lt;li&gt;Talk: AsyncLocalStorage: usage and best practices&lt;/li&gt;
&lt;li&gt;Talk: Examining Observability in Node.js&lt;/li&gt;
&lt;li&gt;Talk: Node.js startup performance&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Talk: Aaaaaaaaaaaaaah, They’re Here! ES Modules in Node.JS
&lt;/h2&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Speaker&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Gil Tayar (&lt;a href="https://twitter.com/giltayar"&gt;@giltayar&lt;/a&gt;)&lt;/p&gt;

&lt;h3&gt;
  
  
  One big takeaway
&lt;/h3&gt;

&lt;p&gt;The ECMAScript modules (ESM) implementation in Node.js is in a very mature state, so it’s a great time to start gradually migrating your packages and applications from CommonJS modules. You might also potentially be able to ditch Babel too if you’re only using it for import/export support.&lt;/p&gt;

&lt;h3&gt;
  
  
  Talk abstract
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;Yes, they’re here. Node v13.2.0 marked the first version of Node.JS where ESM support is unflagged, meaning you can start using ES Modules. It’s been a long, four year journey from defining them in the spec (June 2015!) till they could be used in Node.JS (November 2019).&lt;/p&gt;

&lt;p&gt;Why did it take so long? What were the major hurdles? Should we migrate? How does the migration path look like? Are they really better than CommonJS Modules? What is in store for the future?&lt;/p&gt;

&lt;p&gt;Gil Tayar, a former member of the Node.JS Modules Working Group, and now just a passionate observer of it, will try and navigate these confusing waters, and hopefully make you understand why, when, and how to migrate your Node.JS code to use ES Modules.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  My notes
&lt;/h3&gt;

&lt;p&gt;Unfortunately I missed a big chunk of this talk, but my main takeaway was the reasons why ECMAScript modules (ESM) are better than CommonJS (CJS) modules or Babel transforms. It’s because they’re:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Strict&lt;/li&gt;
&lt;li&gt;Browser compatible – whoop, standards!&lt;/li&gt;
&lt;li&gt;Statically parsed&lt;/li&gt;
&lt;li&gt;Async + supports top-level await&lt;/li&gt;
&lt;li&gt;Native 🎉&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Related links&lt;/strong&gt;
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.youtube.com/watch?v=mMEKrHmZLpQ"&gt;Talk video&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.google.com/presentation/d/1k45i4nq3cNHsTq-84V19fv4-9M6Jhw4jE0nLsQie6GQ/edit#slide=id.g7036a1e984_0_9"&gt;Talk slides&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/giltayar/ah-theyre-here-esm-nodejs"&gt;Code from the talk&lt;/a&gt; – really great code examples to help you understand ECMAScript modules.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Talk: Can we double HTTP client throughput?
&lt;/h2&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Speaker&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Matteo Collina (&lt;a href="https://twitter.com/matteocollina"&gt;@matteocollina&lt;/a&gt;)&lt;/p&gt;

&lt;h3&gt;
  
  
  One big takeaway
&lt;/h3&gt;

&lt;p&gt;If you’re running Node.js microservices which make HTTP requests to each other, to keep things fast, you should 1. always create an HTTP agent with keepAlive, 2. use HTTP pipelining. &lt;a href="https://github.com/nodejs/undici"&gt;Undici&lt;/a&gt; can take care of both of these things for you, and is capable of a much higher throughput than the Node.js core http module.&lt;/p&gt;

&lt;h3&gt;
  
  
  Talk abstract
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;The Node.js HTTP client is a fundamental part of any application, yet many think it cannot be improved. I took this as a challenge and I’m now ready to present a new HTTP client for Node.js, undici, that doubles the throughput of your application.&lt;/p&gt;

&lt;p&gt;The story behind this improvement begins with the birth of TCP/IP and it is rooted in one of the fundamental limitations of networking: head-of-line blocking (HOL blocking). HOL blocking is one of those topics that developers blissfully ignore and yet it deeply impacts the runtime experience of the distributed applications that they build every day. Undici is a HTTP/1.1 client that avoids HOL blocking by using keep-alive and pipelining, resulting in a doubling of your application throughput.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  My notes
&lt;/h3&gt;

&lt;p&gt;I missed a bunch of this talk too 🙈 I’m planning to watch the full talk video (link below) to learn more about the TCP fundamentals which affect HTTP request performance in Node.js, but here’s what I noted live on the day:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Microservices typically communicate with each other over HTTP/1.1 – without any tuning, requests can get slow ← I’ve personally experienced this in projects I’ve worked on in the past.&lt;/li&gt;
&lt;li&gt;To have decent request throughput you should always create an HTTP agent with keep alive enabled – this allows for connection reuse between requests.&lt;/li&gt;
&lt;li&gt;You should also use &lt;a href="https://en.wikipedia.org/wiki/HTTP_pipelining"&gt;HTTP pipelining&lt;/a&gt; so you can send concurrent HTTP requests over a single connection.&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/nodejs/undici"&gt;Undici&lt;/a&gt; HTTP/1.1 client allows you to create a "pool" which you can then make requests through. Using Undici with pool + pipelining is FAST – over three times throughput of node http agent with keep alive 🚀&lt;/li&gt;
&lt;li&gt;Main takeaways:

&lt;ul&gt;
&lt;li&gt;Always use an http(s).Agent&lt;/li&gt;
&lt;li&gt;Undici can drastically reduce the overhead of your distributed system&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Related links
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.youtube.com/watch?v=D9xblqBAHO8"&gt;Talk video&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/nodejs/undici"&gt;Undici client library on GitHub&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Talk: AsyncLocalStorage: usage and best practices
&lt;/h2&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Speaker&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Vladimir de Turckheim (&lt;a href="https://twitter.com/poledesfetes"&gt;@poledesfetes&lt;/a&gt;)&lt;/p&gt;

&lt;h3&gt;
  
  
  One big takeaway
&lt;/h3&gt;

&lt;p&gt;Node.js is constantly evolving and there are some powerful new APIs being implemented that don’t always make headlines. The &lt;code&gt;AsyncLocalStorage&lt;/code&gt; API is one of those, and I’m hoping I’ll have an opportunity soon to give it a try.&lt;/p&gt;

&lt;h3&gt;
  
  
  Talk abstract
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;During Spring, a curious API was added to Node.js core: AsyncLocalStorage. Most Node.js users are not familiar with the power of such tool.&lt;/p&gt;

&lt;p&gt;That’s too bad: it can be used to drastically improve an application’s code and allow building powerful tooling around Node.js applications.&lt;/p&gt;

&lt;p&gt;So, let’s discover what this API is and how to use it to leverage the unlimited powers of AsyncLocalStorage (ok, I might have exagerated it a bit here).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  My notes
&lt;/h3&gt;

&lt;p&gt;&lt;em&gt;Given that efforts are being made to align Node.js more closely with browser standards, it seems odd that the &lt;code&gt;AsyncLocalStorage&lt;/code&gt; API is named as it is: it has nothing to do with the browser Local Storage API&lt;/em&gt; 🤔&lt;/p&gt;

&lt;p&gt;In threaded languages e.g. PHP&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A request enters the process → a thread is created&lt;/li&gt;
&lt;li&gt;The request has its own thread – it’s basically a thread-singleton&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In single-threaded world e.g. Node.js, a single thread handles multiple requests.&lt;/p&gt;

&lt;p&gt;Exception handling is weird in Node.js, nextTick async operations will lose the call stack.&lt;/p&gt;

&lt;p&gt;Let’s create contexts for asynchronous environments: &lt;code&gt;AsyncLocalStorage&lt;/code&gt; – asynchronous-proof store, can create async contexts for you to use.&lt;/p&gt;

&lt;p&gt;Basic example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { AsyncLocalStorage } = require("async_hooks");

const context = new AsyncLocalStorage();

context.run(new Map(), () =&amp;gt; {
    // Do stuff
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can always know what the current request context is. Using &lt;code&gt;process.on('uncaughtException')&lt;/code&gt;, which is normally advised against, however &lt;code&gt;AsyncLocalStorage&lt;/code&gt; allows us to create an application state. Allows for unified error handling.&lt;/p&gt;

&lt;p&gt;Other use cases:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;User management – store current user and use in DB abstraction&lt;/li&gt;
&lt;li&gt;Monitoring – build your own monitoring tool to log/track/monitor what your apps&lt;/li&gt;
&lt;li&gt;Single DB transaction for HTTP request&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Key points:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Memory safe and pretty fast.&lt;/li&gt;
&lt;li&gt;It’s experimental, but production ready.&lt;/li&gt;
&lt;li&gt;It won’t work with queues.&lt;/li&gt;
&lt;li&gt;Don’t share &lt;code&gt;AsyncLocalStorage&lt;/code&gt; instances.&lt;/li&gt;
&lt;li&gt;Don’t create too many &lt;code&gt;AsyncLocalStorage&lt;/code&gt; instances.&lt;/li&gt;
&lt;li&gt;Consider the store as immutable if using basic types&lt;/li&gt;
&lt;li&gt;Use a &lt;code&gt;Map&lt;/code&gt; for everything else&lt;/li&gt;
&lt;li&gt;Use the &lt;code&gt;run&lt;/code&gt; method, but &lt;code&gt;enterWith&lt;/code&gt; only if you need to&lt;/li&gt;
&lt;li&gt;Call &lt;code&gt;exit()&lt;/code&gt; if you are not sure if it will be GCed&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Related links
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.youtube.com/watch?v=c7ic3TtBtb0"&gt;Talk video&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.icloud.com/keynote/0OnPGmSwaRaRvISsCqQu44mGA#AsyncLocalStorage-NODECONF"&gt;Talk slides&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Talk: Examining Observability in Node.js
&lt;/h2&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Speaker&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Liz Parody (&lt;a href="https://twitter.com/lizparody23"&gt;@lizparody23&lt;/a&gt;)&lt;/p&gt;

&lt;h3&gt;
  
  
  One big takeaway
&lt;/h3&gt;

&lt;p&gt;Observing = Exposing internal state of an application so it can be viewed externally and continuously analysed.&lt;/p&gt;

&lt;p&gt;Monitoring = Waiting for problems to happen.&lt;/p&gt;

&lt;h3&gt;
  
  
  Talk abstract
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;Imagine your productivity and confidence developing web apps without chrome dev tools. Many do exactly that with Node.js.&lt;/p&gt;

&lt;p&gt;It is important to observe and learn what’s happening in your app to stay competitive and create the most performant and efficient Node.js applications, following the best practices.&lt;/p&gt;

&lt;p&gt;In this talk, we will explore useful tools to examine your Node.js applications and how observability will speed up development, produce better code while improving reliability and uptime.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  My notes
&lt;/h3&gt;

&lt;p&gt;What is observability? It’s a measure of how well the internal state of a system can be determined from the outside.&lt;/p&gt;

&lt;p&gt;Observing or asking questions from outside the system – no new code should be needed.&lt;/p&gt;

&lt;p&gt;Tools to the rescue!&lt;/p&gt;

&lt;p&gt;Software becoming exponentially more complex: microservices, Docker, Kubernetes etc. Great for products, hard for humans.&lt;/p&gt;

&lt;p&gt;Big growth in observability tools, but hard to choose one.&lt;/p&gt;

&lt;p&gt;Why is observability important? Just monitoring for problems not enough – new issues could be "unknown unknowns".&lt;/p&gt;

&lt;p&gt;A good observability tool:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Helps you find where problem is&lt;/li&gt;
&lt;li&gt;Doesn’t add overhead to app&lt;/li&gt;
&lt;li&gt;Has great security&lt;/li&gt;
&lt;li&gt;Flexible integrations&lt;/li&gt;
&lt;li&gt;Doesn’t require code changes&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Observing = Exposing internal state to be externally accessed.&lt;/p&gt;

&lt;p&gt;Monitoring = Waiting for problems to happen.&lt;/p&gt;

&lt;p&gt;Layers of observability:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Cloud/Network&lt;/li&gt;
&lt;li&gt;Service/Host&lt;/li&gt;
&lt;li&gt;Node.js&lt;/li&gt;
&lt;li&gt;Internals&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Node.js + Internals tools&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;A. Node.js Performance Hooks&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Performance monitoring should be part of development process, not an afterthought when problems arise.&lt;/p&gt;

&lt;p&gt;Using &lt;code&gt;perf_hooks&lt;/code&gt; module allow you to collect performance metrics from the running Node.js application.&lt;/p&gt;

&lt;p&gt;Requires code to implement in your application.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;B. Profiling&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Flame graphs can be very useful, but they’re very intensive to collect so cannot be captured in production.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;C. Trace Events&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Enable with —trace-event—categories trace_events&lt;/p&gt;

&lt;p&gt;node, node.async_hooks, v8 – enabled by default&lt;/p&gt;

&lt;p&gt;To get the output of several events —trace-event-enabled&lt;/p&gt;

&lt;p&gt;Connect to the locally running application: chrome://tracing&lt;/p&gt;

&lt;p&gt;Tracing has less overhead, but it can become tricky to work with as it exposes a lot of Node.js internals.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;D. Heap Snapshot&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Is a static snapshot of memory usage details at point in time, glimpse into V8 heap usage&lt;/p&gt;

&lt;p&gt;Useful for finding and fixing memory + performance issues in Node.js applications.&lt;/p&gt;

&lt;p&gt;Built in heap snapshots signal flag &lt;code&gt;--heapshot-signal&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Chrome DevTools allow you to compare snapshots.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;E. The V8 Inspector&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Chrome DevTools was integrated directly into Node.js a few years ago.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;--inspect&lt;/code&gt; flag, listens by default on &lt;code&gt;127.0.0.1:9229&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;--inspect-brk&lt;/code&gt; for using the inspector with breakpoints&lt;/p&gt;

&lt;p&gt;Go to &lt;code&gt;chrome://inspect&lt;/code&gt; so you can connect DevTools to your Node.js application&lt;/p&gt;

&lt;p&gt;Allows you to… edit code on-the-fly, diagnose problems quickly, access sourcemaps for transpiled code, LiveEdit, console evaluation, sampling JavaScript profiler with flame graph, heap snapshot inspection, async stacks for native promises.&lt;/p&gt;

&lt;p&gt;Only suitable for development, not for production.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Problems with Node.js internals tools&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Tells you there’s a problem, but not where.&lt;/p&gt;

&lt;p&gt;Not easy to implement, not enough information.&lt;/p&gt;

&lt;p&gt;Not presented in user-friendly way, data overload.&lt;/p&gt;

&lt;p&gt;Significant overhead, not viable in production.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;External Tools for Node.js Observability&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;A. Blocked Library&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Available in Node.js 8+. Helps you checked if event loop is blocked, provides stacktrace pointing to blocking function. &lt;code&gt;blocked()&lt;/code&gt; function reports every value over configured threshold.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;B. New Relic (hosted service)&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Offers application performance monitoring (APM).&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;C. DataDog (hosted service)&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Similar service to New Relic.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;D. Instana (hosted service)&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;APM for microservices – trace every distributed request, map all service dependencies, profile every production process.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;E. Dynatrace (hosted service)&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Another APM, with a focus on "advanced observability".&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;F. Google Cloud Stackdriver&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Another APM, for Google Cloud and Amazon Web Services.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Problems with APMs&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;They have to be integrated into your applications and can cause a significant amount of overhead.&lt;/p&gt;

&lt;p&gt;Accuracy might be questionable as the APM modules themselves can have&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;N|Solid&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Native C++ agent which runs alongside your application, doesn’t require integration with your application code, resulting in minimal overhead on application performance. [N|Solid is a product of NodeSource, the speaker’s employer]&lt;/p&gt;

&lt;h3&gt;
  
  
  Related links
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.youtube.com/watch?v=uoblRbnkLQI"&gt;Talk Video&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.google.com/presentation/d/1sPtnr8OJiMDsAeUl91lOoC4o0eGjLUXepx35OKNtZfQ/edit"&gt;Talk Slides&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Talk: Node.js startup performance
&lt;/h2&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Speaker&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Joyee Cheung (&lt;a href="https://twitter.com/JoyeeCheung"&gt;@JoyeeCheung&lt;/a&gt;)&lt;/p&gt;

&lt;h3&gt;
  
  
  One big takeaway
&lt;/h3&gt;

&lt;p&gt;There is a tremendous amount of important work being done in the background by developers like Joyee who are working on the Node.js core. If you want to get a deeper understanding of what Node.js is doing under the hood, and why improvements to the Node.js core are so important, I thoroughly recommend that you &lt;a href="https://www.youtube.com/watch?v=G36lrPrF09c&amp;amp;list=PL0CdgOSSGlBalMPxFFycq7OIqQF8cJS28"&gt;watch Joyee’s talk&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Talk abstract
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;In this talk, we will break down how Node.js spends its time starting up from scratch, and look into recent changes in the Node.js code base that have improved the startup performance by using different tricks and various V8 APIs.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  My notes
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;The journey of Node.js startup performance&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Refactoring to avoid unnecessary work&lt;/li&gt;
&lt;li&gt;Implement code caching&lt;/li&gt;
&lt;li&gt;Integrating V8 startup snapshot&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Used to take ~60ms on a modern server.&lt;/p&gt;

&lt;p&gt;After optimisations ended, startup time on same server dropped to 21ms.&lt;/p&gt;

&lt;p&gt;Between Node.js v10 – v15 – startup time time reduced by 40 – 50%&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Overview of the Node.js bootstrap process&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Around half of the Node.js core is written in JavaScript, the rest in C++.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Initialize the process e.g. processing command line flags, setting up signal handlers, creating default event loop etc. (C++)&lt;/li&gt;
&lt;li&gt;Initialize V8 isolate (C++)

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;v8::Isolate&lt;/code&gt; is instance of the v8 JavaScript engine&lt;/li&gt;
&lt;li&gt;Encapsulates the JS heap, microtask queue, pending exceptions…&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Initialize V8 context (JavaScript)

&lt;ul&gt;
&lt;li&gt;Sandboxed execution context&lt;/li&gt;
&lt;li&gt;Encapsulates JavaScript builtins (primordials) e.g. globalThis, Array, Object&lt;/li&gt;
&lt;li&gt;Node.js copies original JS built-ins at beginning of bootstrap for built-in modules to use.&lt;/li&gt;
&lt;li&gt;In Node.js userland JS executed in main V8 context by default, shares same context as one used by built-ins of Node.js&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Initialize Node.js environment (JavaScript and C++)

&lt;ul&gt;
&lt;li&gt;Initialize runtime-independent states (JavaScript)&lt;/li&gt;
&lt;li&gt;Initialize event loop (C++)&lt;/li&gt;
&lt;li&gt;Initialize V8 inspector (C++) – can only debug JavaScript once the inspector is initialized&lt;/li&gt;
&lt;li&gt;Initialize runtime dependent states (JavaScript)&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Load main script (JavaScript)

&lt;ul&gt;
&lt;li&gt;Execution from CLI (&lt;code&gt;node index.js&lt;/code&gt;) – Create + initialize environment, select a main script → Load &lt;code&gt;run_main_module.js&lt;/code&gt;, detect module type → Read and compile &lt;code&gt;${cwd}/index.js&lt;/code&gt; with CommonJS or ECMAScript module loader → Start event loop&lt;/li&gt;
&lt;li&gt;Execution for worker intialiized by code in main thread – Create + initialize environment, select a main script → Load &lt;code&gt;worker_thread.js&lt;/code&gt;, setup message port and start listening → Start event loop → Compile and run the script sent from the port&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Start the event loop – will be kept running until nothing is keeping it open.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Refactoring&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Lazy-load builtins that are not always used

&lt;ul&gt;
&lt;li&gt;Lots of builtin modules depend on each other&lt;/li&gt;
&lt;li&gt;Caveat: more time would be spent loading them on demand later&lt;/li&gt;
&lt;li&gt;Can be reverted when startup snapshot covers these modules&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Initializing runtime states were cleanly separated as part of the refactoring work.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Code caching&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;This speeds up JS compilation.&lt;/li&gt;
&lt;li&gt;Previously: parse and compile source code of JS native modules at Node.js run time and execute them to make them available as built-in modules.&lt;/li&gt;
&lt;li&gt;Now: parse and compile source code of JS native modules at Node.js executable build time, then deserialize them from the Node.js executable in the Node.js process (run time), and execute them to make them available as built-in modules.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Refactoring for snapshot integration&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;This was enabled by splitting runtime initialization into two separate phases (as mentioned earlier).&lt;/li&gt;
&lt;li&gt;Before: At Node.js process run time: Array, Object, String etc. → Runs through initialization scripts → Initialize Primordials: process, URL, Buffer etc. → Node.js process&lt;/li&gt;
&lt;li&gt;After: At Node.js executable build time: Array, Object, String etc. → Runs through initialization scripts → Initialize Primordials: process, URL, Buffer etc. → Serialize and compile into snapshot blob. At Node.js process run time, deserialize snapshot blob from executable.&lt;/li&gt;
&lt;li&gt;Saves quite a lot of time at startup.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ongoing work&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;During this refactoring work for Node.js, contributions were made to V8&lt;/li&gt;
&lt;li&gt;Supporting more language features in the V8 snapshot

&lt;ul&gt;
&lt;li&gt;JSMap and JSSet rehashing (previously disabled in Node.js v8)&lt;/li&gt;
&lt;li&gt;Class field initializers&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Future work&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Userland snapshotting&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Take a snapshot of an application and write it to disk&lt;/li&gt;
&lt;li&gt;Load from file system or build into an executable&lt;/li&gt;
&lt;li&gt;Tracking issue: &lt;a href="https://github.com/nodejs/node/issues/35711"&gt;https://github.com/nodejs/node/issues/35711&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Questions &amp;amp; Answers&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;What’s inside the startup snapshots?&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Two types:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Isolate snapshots – e.g. V8 strings, numbers&lt;/li&gt;
&lt;li&gt;Context snapshots – e.g. objects you create&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;What are runtime dependent states?&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Runtime dependent states = things configured with command line flags or environment variables&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Related links
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.youtube.com/watch?v=G36lrPrF09c&amp;amp;list=PL0CdgOSSGlBalMPxFFycq7OIqQF8cJS28"&gt;Talk Video&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>node</category>
      <category>nodeconf</category>
      <category>notes</category>
    </item>
    <item>
      <title>How to send consistent error responses from your Express API</title>
      <dc:creator>Simon Plenderleith</dc:creator>
      <pubDate>Thu, 29 Oct 2020 11:12:46 +0000</pubDate>
      <link>https://forem.com/simonplend/how-to-send-consistent-error-responses-from-your-express-api-44k7</link>
      <guid>https://forem.com/simonplend/how-to-send-consistent-error-responses-from-your-express-api-44k7</guid>
      <description>&lt;p&gt;When you’re building an API with Express it can be difficult to know how to send consistent error responses. The framework doesn’t seem to provide any special features for this, so you’re left to figure it out on your own. At some point you’ll probably find yourself wondering if you’re doing it "the right way".&lt;/p&gt;

&lt;p&gt;As I mentioned in my ‘&lt;a href="https://simonplend.com/5-best-practices-for-building-a-modern-api-with-express/"&gt;5 best practices for building a modern API with Express&lt;/a&gt;‘ blog post:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;It’s very tempting when building an API to invent your own format for error responses, but HTTP response status codes are a great starting point as they can communicate a specific error state.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If you invent your own format you’ll have to build a bunch of extra logic into your API, and you’ll probably want to make sure it’s thoroughly tested too. Nobody wants errors in their error response code, right?! On top of that, it will also require clients – e.g. front end JavaScript – to implement additional code for handling the special format of your API’s error responses.&lt;/p&gt;

&lt;p&gt;Wouldn’t it be nice if there was a simpler way, a tried and tested &lt;em&gt;standard&lt;/em&gt; way, of sending error responses? As luck would have it, there is! The HTTP standard &lt;a href="https://tools.ietf.org/html/rfc7231#section-6"&gt;defines status codes&lt;/a&gt; which you can use in the responses from your API to indicate whether the request was successful, or whether an error occurred.&lt;/p&gt;

&lt;p&gt;Here’s an example HTTP error response with the 400 status code, which indicates a ‘Bad Request’ from the client:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt; HTTP/1.1 400 Bad Request
&amp;lt; Content-Type: text/html; charset=utf-8
&amp;lt; Content-Length: 138
&amp;lt; Date: Wed, 28 Oct 2020 20:11:07 GMT
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you want to send an error response like this, you could use Express' res.status() method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nx"&gt;res&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;status&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;400&lt;/span&gt;&lt;span class="p"&gt;).&lt;/span&gt;&lt;span class="nx"&gt;end&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Follow the &lt;del&gt;yellow brick road&lt;/del&gt; HTTP standard
&lt;/h2&gt;

&lt;p&gt;By default the HTTP status code sent in a response from an Express application is 200 (OK). This tells the client that the request was successful and that they can proceed to parse and extract whatever data they require from the response. To indicate an error when sending a response, you should use an HTTP status code from one of the two error ranges defined by the HTTP standard:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Client error 4xx&lt;/strong&gt; - The client has done something wrong.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Server error 5xx&lt;/strong&gt; - Something has gone wrong in your application.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;The MDN web docs have &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status"&gt;a great reference with all of the HTTP response status codes&lt;/a&gt; that are defined by the HTTP standard, along with explanations of what they mean.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Once you've figured out what error status codes your API should send in different situations, you need a way of getting those status codes into an error - this is where the &lt;code&gt;http-errors&lt;/code&gt; library comes in.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to create errors with the http-errors library
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Setting it up
&lt;/h3&gt;

&lt;p&gt;First of all you will need to install the &lt;code&gt;http-errors&lt;/code&gt; library:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;npm &lt;span class="nb"&gt;install &lt;/span&gt;http-errors
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And then you'll want to &lt;code&gt;require()&lt;/code&gt; it in your application (after you require &lt;code&gt;express&lt;/code&gt; is fine):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;createHttpError&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;require&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;http-errors&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;http-errors&lt;/code&gt; library offers two different ways to create an error object.&lt;/p&gt;

&lt;h3&gt;
  
  
  Way #1: Specify a numeric HTTP status code
&lt;/h3&gt;

&lt;p&gt;The first way is to &lt;a href="https://www.npmjs.com/package/http-errors#createerrorstatus-message-properties"&gt;specify a numeric HTTP status code&lt;/a&gt; e.g.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;createHttpError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;400&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Invalid filter&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you want, instead of passing an error message string, you can &lt;a href="https://www.npmjs.com/package/http-errors#createerrorstatus-error-properties"&gt;pass an existing error object to be extended&lt;/a&gt; e.g.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nb"&gt;Error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Invalid filter&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;httpError&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;createHttpError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;400&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;&lt;strong&gt;Warning!&lt;/strong&gt; Be careful whenever you pass an existing error as you could potentially expose sensitive details about your application if it gets sent through in an error response. As you'll see in the next section, the default error handler in Express has safeguards built in to help you avoid this, but it's important to be careful about what details you expose in your API responses.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If you want to specify extra headers to be added when the error is sent in a response, &lt;code&gt;http-errors&lt;/code&gt; allows you to do this by passing in a &lt;a href="https://www.npmjs.com/package/http-errors#api"&gt;properties object&lt;/a&gt; e.g.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;createHttpError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;400&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Invalid filter&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="na"&gt;headers&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;X-Custom-Header&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Value&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Way #2: Use a named HTTP error constructor
&lt;/h3&gt;

&lt;p&gt;The second way of creating an error object is to use one of the &lt;a href="https://www.npmjs.com/package/http-errors#new-createerrorcode--namemsg"&gt;named HTTP error constructors&lt;/a&gt; which &lt;code&gt;http-errors&lt;/code&gt; provides e.g.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nx"&gt;createHttpError&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;BadRequest&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Invalid filter&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The difference with this second approach is that you can only pass in an error message string - it doesn't allow you to pass in an existing error object or a properties object. For situations where you don't need them, I think this second approach is easier to maintain. It means don't need to keep looking up HTTP status codes to find out what they mean every time you revisit the code.&lt;/p&gt;

&lt;h3&gt;
  
  
  What's in these error objects?
&lt;/h3&gt;

&lt;p&gt;Here are the properties which will always exist on an error object created with &lt;code&gt;http-errors&lt;/code&gt;, along with example values:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nl"&gt;message&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Invalid filter&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="c1"&gt;// This statusCode property is going to come in very handy!&lt;/span&gt;
    &lt;span class="nx"&gt;statusCode&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;400&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nx"&gt;stack&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;`BadRequestError: Invalid filter
        at /home/simonplend/dev/express-error-responses/app.js:33:17
        at Layer.handle [as handle_request] (/home/simonplend/dev/express-error-responses/node_modules/express/lib/router/layer.js:95:5)
        at next (/home/simonplend/dev/express-error-responses/node_modules/express/lib/router/route.js:137:13)`&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let's take a look at what you can do with an error object once you've created it.&lt;/p&gt;

&lt;h2&gt;
  
  
  The default error handler in Express
&lt;/h2&gt;

&lt;p&gt;Express provides a &lt;a href="https://expressjs.com/en/guide/error-handling.html#the-default-error-handler"&gt;default error handler&lt;/a&gt;. This error handler is called when you call the &lt;code&gt;next()&lt;/code&gt; callback function from a middleware or route handler and you pass an error object to it e.g. &lt;code&gt;next(error)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;There are two important things to know about the behaviour of the default error handler in Express:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;It will look for for a &lt;code&gt;statusCode&lt;/code&gt; property on the error object (&lt;code&gt;error.statusCode&lt;/code&gt;) - that's right, just like the one which exists on errors created with &lt;code&gt;http-error&lt;/code&gt;. If &lt;code&gt;statusCode&lt;/code&gt; is within the 4xx or 5xx range, it will set that as the status code of the response, otherwise it will set the status code to 500 (Internal Server Error).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In development it will send the full stack trace of the error that it receives (&lt;code&gt;error.stack&lt;/code&gt;) in the response e.g.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;BadRequestError: Invalid sort parameter, must be either: first_name, last_name
    at /home/simonplend/dev/express-error-responses/app.js:17:17
    at Layer.handle [as handle_request] (/home/simonplend/dev/express-error-responses/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/simonplend/dev/express-error-responses/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/home/simonplend/dev/express-error-responses/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/simonplend/dev/express-error-responses/node_modules/express/lib/router/layer.js:95:5)
    at /home/simonplend/dev/express-error-responses/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/home/simonplend/dev/express-error-responses/node_modules/express/lib/router/index.js:335:12)
    at next (/home/simonplend/dev/express-error-responses/node_modules/express/lib/router/index.js:275:10)
    at expressInit (/home/simonplend/dev/express-error-responses/node_modules/express/lib/middleware/init.js:40:5)
    at Layer.handle [as handle_request] (/home/simonplend/dev/express-error-responses/node_modules/express/lib/router/layer.js:95:5)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In production i.e. when the environment variable &lt;code&gt;NODE_ENV&lt;/code&gt; is set to &lt;code&gt;production&lt;/code&gt;, it will omit the stack trace and only send the name which corresponds with the HTTP status code e.g. &lt;code&gt;Bad Request&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Displaying a stack trace in production is &lt;em&gt;a bad thing to do&lt;/em&gt;: it creates a security risk as it reveals internal details about your application, which makes it more vulnerable to a potential attacker, as they will have details about how your application is structured and what libraries you are using.&lt;/p&gt;

&lt;h2&gt;
  
  
  Putting it all together
&lt;/h2&gt;

&lt;p&gt;Ok, so we know about HTTP status codes, how to create JavaScript error objects which contain a status code, and how the default error handler in Express can use them. Let's put it all together!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;express&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;require&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;express&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * We'll be using this library to help us create errors with
 * HTTP status codes.
 */&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;createHttpError&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;require&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;http-errors&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * In a real application this would run a query against a
 * database, but for this example it's always returning a
 * rejected `Promise` with an error message.
 */&lt;/span&gt;
&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nx"&gt;getUserData&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;Promise&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;reject&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;An error occurred while attempting to run the database query.&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;
    &lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * Express configuration and routes
 */&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;PORT&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;3000&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;app&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;express&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;

&lt;span class="cm"&gt;/**
 * This example route will potentially respond with two
 * different types of error:
 * 
 * - 400 (Bad Request) - The client has done something wrong.
 * - 500 (Internal Server Error) - Something has gone wrong in your application.
 */&lt;/span&gt;
&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="kd"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;/user&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;validSort&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;first_name&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;last_name&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;];&lt;/span&gt;

    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;sort&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;request&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;query&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;sort&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;sortIsValid&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;sort&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="nx"&gt;validSort&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;includes&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;sort&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="nx"&gt;sortIsValid&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="cm"&gt;/**
         * This error is created by specifying a numeric HTTP status code.
         * 
         * 400 (Bad Request) - The client has done something wrong.
         */&lt;/span&gt;
        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nx"&gt;createHttpError&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;BadRequest&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="s2"&gt;`Invalid sort parameter, must be either: &lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;validSort&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;join&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;, &lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;)}&lt;/span&gt;&lt;span class="s2"&gt;`&lt;/span&gt;
        &lt;span class="p"&gt;);&lt;/span&gt;

        &lt;span class="cm"&gt;/**
         * Because we're passing an error object into the `next()` function,
         * the default error handler in Express will kick in and take
         * care of sending an error response for us.
         * 
         * It's important that we return here so that none of the
         * other code in this route handler function is run.
         */&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="nx"&gt;getUserData&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;then&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;userData&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;json&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;userData&lt;/span&gt;&lt;span class="p"&gt;))&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;catch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="cm"&gt;/**
             * This error is created by using a named HTTP error constructor.
             *
             * An existing error is being passsed in and extra headers are
             * being specified that will be sent with the response.
             *
             * 500 (Internal Server Error) - Something has gone wrong in your application.
             */&lt;/span&gt;
            &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;httpError&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;createHttpError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;500&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="na"&gt;headers&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                    &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;X-Custom-Header&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="s2"&gt;Value&lt;/span&gt;&lt;span class="dl"&gt;"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="p"&gt;});&lt;/span&gt;

            &lt;span class="cm"&gt;/**
             * Once again, the default error handler in Express will kick
             * in and take care of sending an error response for us when
             * we pass our error object to `next()`.
             * 
             * We don't technically need to return here, but it's
             * good to get into the habit of doing this when calling
             * `next()` so you don't end up with weird bugs where
             * an error response has been sent but your handler function
             * is continuing to run as if everything is ok.
             */&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;httpError&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="p"&gt;});&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="nx"&gt;app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;listen&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;PORT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;`Example app listening at http://localhost:&lt;/span&gt;&lt;span class="p"&gt;${&lt;/span&gt;&lt;span class="nx"&gt;PORT&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="s2"&gt;`&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Note: The default error handler in Express sends an HTML response body. If you want to send a JSON response body, you will need to &lt;a href="https://expressjs.com/en/guide/error-handling.html#writing-error-handlers"&gt;write your own error handler&lt;/a&gt;. I'll be covering this in a future blog post!&lt;/em&gt;&lt;/p&gt;

</description>
      <category>express</category>
      <category>node</category>
      <category>errors</category>
      <category>http</category>
    </item>
  </channel>
</rss>
