express-except-middleware
TypeScript icon, indicating that this package has built-in type declarations

0.0.2 • Public • Published

README

This library is a middleware you can use to conditionally use other middleware on Express servers.

Usage

Pass a string to do a simple path match. Eg. Calls authMiddleware unless the request path matches /public:

except(option: string, ...)

import { except } from 'express-except-middleware'

app.use(except('/public', authMiddleware))

You can pass a string with path parameters. Calls authMiddleware unless the request path matches /public/:id:

app.use(except('/public/:id', authMiddleware))

except(option: MatchObject, ...)

You can pass an object that will match both the method and path. Method is case insensitive. Eg. Calls authMiddleware unless a GET request was made to the path /public.

app.use(except({method: 'GET', path: '/public'}), authMiddleware))

except(option: MatchFunction, ...)

Match using a function. Your function will be called with the request and response objects. You must return a boolean from your function. Eg. Calls authMiddleware unless the Authorization header is defined on the request.

const checkHeader = (req, res) => {
    return req.headers['Authorization'] === undefined
}

app.use(except(checkHeader, authMiddleware))

except(option: AsyncMatchFunction, ...)

Match using a Promise based function that resolves to a boolean. Your function will be called the request and response objects. You must resolve to a boolean from your async function. Eg. Calls authMiddleware unless asyncShouldAuthenticate

function asyncCheck(req, res) {
    // Do some async operation here
    return asyncShouldAuthenticate()
}
app.use(except(asyncCheck, authMiddleware))

except(option: Array<string | MatchObject | MatchFunction>, ...)

Match using an array of options. This is an OR operation. If at least one option matches the request, then next() is called and the supplied middleware is not executed. Eg. Calls authMiddleware unless:

  • the request path matches /public
  • OR the request method is GET and path matches /foo
  • OR the request header Foobar is undefined
  • OR the checkAsync() function resolves to true
const options = [
    '/public',
    { method: 'GET', path: '/foo' },
    function(req, res) {
        return req.headers['Foobar'] === undefined
    },
    function(req, res) {
        return checkAsync()
    },
]
app.use(except([], authMiddleware)

Readme

Keywords

none

Package Sidebar

Install

npm i express-except-middleware

Weekly Downloads

0

Version

0.0.2

License

MIT

Unpacked Size

9.01 kB

Total Files

4

Last publish

Collaborators

  • andrewsinner