Express middleware to handle errors where an expected header is missing.
This library requires the following to run:
- Node.js 20+
Install with npm:
npm install require-header
Load the library into your code with a require
call:
const { requireHeader } = require('require-header');
requireHeader
will return a middleware function that will error if the request does not set the given header. The error will have message
and status
properties which you can use.
It accepts two arguments. Firstly, the name of a header which is required:
requireHeader('User-Agent');
Secondly (optionally) a message which will be used in the error if the request message does not match:
requireHeader('User-Agent', 'User-Agent header is required');
const express = require('express');
const app = express();
// Only requests with a User-Agent header will continue
app.get(requireHeader('User-Agent'), () => { ... });
If you want to do something useful with the error, for example output a sensible JSON response, you will need to define an error handler for your application (after the route definition):
app.use((error, request, response, next) => {
response.status(error.status || 500).send({
message: error.message
});
});
const express = require('express');
const app = express();
// Require a User-Agent header across the entire application
app.use(requireHeader('User-Agent'));
A new major version of this project is released if breaking changes are introduced. We maintain a migration guide to help users migrate between these versions.
The contributing guide is available here. All contributors must follow this library's code of conduct.
Licensed under the MIT license.
Copyright © 2015, Rowan Manning