1.0.1 • Published 3 years ago

with-allow v1.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

withAllow

A route handler wrapper for Express to check if the requested HTTP method are allowed for the route.

Downloads install size

Install

$ npm install with-allow --save

Usage

import express from 'express'
import withAllow from 'with-allow'

const app = express()

const routeHandler =
  (req, res) => {
    res.send(`${req.method} works!`)
  }

// other HTTP method requests such as POST, PUT etc., will throw 405 HTTP error
app.get('/', withAllow(routeHandler, ['GET']))

app.listen(3000, () => {
  console.log('Express server is running on port: 3000')
})

// http://localhost:3000 -> will print out "GET works!"

Next.js

It is also possible to use withAllow in Next.js API routes. There is an example following.

// Next.js API route example
function handler(req, res) {
  // API route handler
}

export default withAllow(handler, ['POST'])

Options

NameTypeDefaultDescription
handlerfunction-The original Express.js route handler
allowedMethodsstring[] or *[]Allowed HTTP method list for the route handler. Left blank to disallow all the HTTP methods. Pass asterisk (*) to allow all the HTTP methods.