|
| 1 | +# Fastify Allow Plugin |
| 2 | +The HTTP 1.1 specification has an [`Allow` header](https://datatracker.ietf.org/doc/html/rfc7231#section-7.4.1) for resources to include in client responses, indicating all the methods the resource supports. All resource requests return the `Allow` header so client develpers can discover all of the allowable methods on the resource. If a resource does not support a method, for instance, `DELETE`, then the response status will be `405 Not Allowed` along with the `Allow` header. |
| 3 | + |
| 4 | +This plugin adds an `Allow` header to all responses with routes that have registered handlers, regardless of the method they handle. It returns a `405 Not Allowed` response when a route has no supported method handler. This behaviour is different from Fastify's default behaviour, which is to return a `404 Not Found` for unhandled methodson a route. |
| 5 | + |
| 6 | +If a route has no registered method handlers, fastify-allow will send the usual `404 Not Found` response. |
| 7 | + |
| 8 | +### Install |
| 9 | + |
| 10 | +```shell |
| 11 | +npm install fastify-allow |
| 12 | +``` |
| 13 | + |
| 14 | +### Usage |
| 15 | +To use the plugin, simply register it _before adding method handlers_ to the fastify instance. |
| 16 | + |
| 17 | +```js |
| 18 | +const fastify = require('fastify')() |
| 19 | + |
| 20 | +fastify.register(require('fastify-allow')) |
| 21 | + |
| 22 | +/* |
| 23 | + The replies for GET and POST to this endpoint will include the header Allow: GET, POST |
| 24 | + This route will reply 405 on HEAD, OPTIONS, PUT, PATCH and DELETE in addition to the header |
| 25 | + Allow: GET, POST |
| 26 | +*/ |
| 27 | +fastify.get('/foo', (req, reply) => { |
| 28 | + reply.send({ hello: 'world' }) |
| 29 | +}) |
| 30 | + |
| 31 | +fastify.post('/foo', (req, reply) => { |
| 32 | + reply.status(201) |
| 33 | +}) |
| 34 | + |
| 35 | +fastify.listen(3000, (err) => { |
| 36 | + if (err) throw err |
| 37 | + console.log('Server listening at http://localhost:3000') |
| 38 | +}) |
| 39 | +``` |
| 40 | + |
| 41 | +### Options |
| 42 | +The plugin can be configured to retain fastify's default behaviour for unsupported methods, which is to respond with `404 Not Found`. Configure the plugin at registration with this option: |
| 43 | + |
| 44 | +```js |
| 45 | +fastify.register(require('fastify-allow', { send405: false })) |
| 46 | +``` |
| 47 | + |
| 48 | +### Typescript Support |
| 49 | +fastify-allow is written in Typescript and includes type declarations for the options. |
| 50 | + |
| 51 | +```typescript |
| 52 | +import Fastify from "fastify" |
| 53 | +import allowPlugin, {AllowOptions} from "fastify-allow" |
| 54 | + |
| 55 | +const fastify = Fastify() |
| 56 | +const allowOpts: AllowOptions = { send405: false } |
| 57 | + |
| 58 | +fastify.register(allowPlugin, allowOpts) |
| 59 | + |
| 60 | +// now register handlers |
| 61 | +``` |
0 commit comments