require-header
TypeScript icon, indicating that this package has built-in type declarations

5.1.0 • Public • Published

Require-Header

Express middleware to handle errors where an expected header is missing.

Table of Contents

Requirements

This library requires the following to run:

Usage

Install with npm:

npm install allow-methods

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'));

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

Package Sidebar

Install

npm i require-header

Weekly Downloads

65

Version

5.1.0

License

MIT

Unpacked Size

6.84 kB

Total Files

7

Last publish

Collaborators

  • rowanmanning