require-header v6.0.0
Require-Header
Express middleware to handle errors where an expected header is missing.
Requirements
This library requires the following to run:
- Node.js 20+
Usage
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');
Route-level
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
});
});
Application-level
const express = require('express');
const app = express();
// Require a User-Agent header across the entire application
app.use(requireHeader('User-Agent'));
Migration
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.
Contributing
The contributing guide is available here. All contributors must follow this library's code of conduct.
License
Licensed under the MIT license. Copyright © 2015, Rowan Manning
4 months ago
12 months ago
1 year ago
1 year ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
9 years ago
9 years ago
10 years ago
10 years ago
11 years ago