Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork40
Defaults for Fastify that everyone can agree on
License
fastify/fastify-sensible
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Defaults for Fastify that everyone can agree on™.
This plugin adds some useful utilities to your Fastify instance, see the API section to learn more.
Why are these APIs here and not included with Fastify?
Because Fastify aims to be as small and focused as possible, every utility that is not essential should be shipped as a standalone plugin.
npm i @fastify/sensible| Plugin version | Fastify version |
|---|---|
>=6.x | ^5.x |
^5.x | ^4.x |
^4.x | ^3.x |
>=2.x <4.x | ^2.x |
^1.x | ^1.x |
Please note that if a Fastify version is out of support, then so are the corresponding versions of this pluginin the table above.SeeFastify's LTS policy for more details.
constfastify=require('fastify')()fastify.register(require('@fastify/sensible'))fastify.get('/',(req,reply)=>{reply.notFound()})fastify.get('/async',async(req,reply)=>{throwfastify.httpErrors.notFound()})fastify.get('/async-return',async(req,reply)=>{returnreply.notFound()})fastify.listen({port:3000})
If you set thesharedSchemaId option, a shared JSON Schema is added and can be used in your routes.
constfastify=require('fastify')()fastify.register(require('@fastify/sensible'),{sharedSchemaId:'HttpError'})fastify.get('/async',{schema:{response:{404:{$ref:'HttpError'}}},handler:async(req,reply)=>{returnreply.notFound()}})fastify.listen({port:3000})
Object that exposescreateError and all of the4xx and5xx error constructors.
Use of4xx and5xx error constructors follows the same structure asnew createError[code || name]([msg])) inhttp-errors:
// the custom message is optionalconstnotFoundErr=fastify.httpErrors.notFound('custom message')
4xx
fastify.httpErrors.badRequest()fastify.httpErrors.unauthorized()fastify.httpErrors.paymentRequired()fastify.httpErrors.forbidden()fastify.httpErrors.notFound()fastify.httpErrors.methodNotAllowed()fastify.httpErrors.notAcceptable()fastify.httpErrors.proxyAuthenticationRequired()fastify.httpErrors.requestTimeout()fastify.httpErrors.conflict()fastify.httpErrors.gone()fastify.httpErrors.lengthRequired()fastify.httpErrors.preconditionFailed()fastify.httpErrors.payloadTooLarge()fastify.httpErrors.uriTooLong()fastify.httpErrors.unsupportedMediaType()fastify.httpErrors.rangeNotSatisfiable()fastify.httpErrors.expectationFailed()fastify.httpErrors.imateapot()fastify.httpErrors.misdirectedRequest()fastify.httpErrors.unprocessableEntity()fastify.httpErrors.locked()fastify.httpErrors.failedDependency()fastify.httpErrors.tooEarly()fastify.httpErrors.upgradeRequired()fastify.httpErrors.preconditionRequired()fastify.httpErrors.tooManyRequests()fastify.httpErrors.requestHeaderFieldsTooLarge()fastify.httpErrors.unavailableForLegalReasons()
5xx
fastify.httpErrors.internalServerError()fastify.httpErrors.notImplemented()fastify.httpErrors.badGateway()fastify.httpErrors.serviceUnavailable()fastify.httpErrors.gatewayTimeout()fastify.httpErrors.httpVersionNotSupported()fastify.httpErrors.variantAlsoNegotiates()fastify.httpErrors.insufficientStorage()fastify.httpErrors.loopDetected()fastify.httpErrors.bandwidthLimitExceeded()fastify.httpErrors.notExtended()fastify.httpErrors.networkAuthenticationRequired()
createError
Use ofcreateError follows the same structure ascreateError([status], [message], [properties]) inhttp-errors:
consterr=fastify.httpErrors.createError(404,'This video does not exist!')
Thereply interface is decorated with all of the functions declared above, using it is easy:
fastify.get('/',(req,reply)=>{reply.notFound()})
Thereply interface is decorated withjshttp/vary, the API is the same, but you do not need to pass the res object.
fastify.get('/',(req,reply)=>{reply.vary('Accept')reply.send('ok')})
Thereply interface is decorated with a helper to configure cache control response headers.
// configure a single typefastify.get('/',(req,reply)=>{reply.cacheControl('public')reply.send('ok')})// configure multiple typesfastify.get('/',(req,reply)=>{reply.cacheControl('public')reply.cacheControl('immutable')reply.send('ok')})// configure a type timefastify.get('/',(req,reply)=>{reply.cacheControl('max-age',42)reply.send('ok')})// the time can be defined as stringfastify.get('/',(req,reply)=>{// all the formats of github.com/vercel/ms are supportedreply.cacheControl('max-age','1d')// will set to 'max-age=86400'reply.send('ok')})
Thereply interface is decorated with a helper to set the cache control header to a no caching configuration.
fastify.get('/',(req,reply)=>{// will set cache-control to 'no-store, max-age=0, private'// and for HTTP/1.0 compatibility// will set pragma to 'no-cache' and expires to 0reply.preventCache()reply.send('ok')})
Thereply interface is decorated with a helper to set the cache control header to a no caching configuration.
fastify.get('/',(req,reply)=>{reply.revalidate()// will set to 'max-age=0, must-revalidate'reply.send('ok')})
Thereply interface is decorated with a helper to set the cache control header to a public and immutable configuration.
fastify.get('/',(req,reply)=>{// the time can be defined as a stringreply.staticCache(42)// will set to 'public, max-age=42, immutable'reply.send('ok')})
Thereply interface is decorated with a helper to set the cache control header forstale content.
fastify.get('/',(req,reply)=>{// the time can be defined as a stringreply.stale('while-revalidate',42)reply.stale('if-error',1)reply.send('ok')})
Thereply interface is decorated with a helper to set max age of the response. It can be used in conjunction withreply.stale, seehere.
fastify.get('/',(req,reply)=>{// the time can be defined as a stringreply.maxAge(86400)reply.stale('while-revalidate',42)reply.send('ok')})
Therequest interface is decorated withjshttp/forwarded, the API is the same, but you do not need to pass the request object:
fastify.get('/',(req,reply)=>{reply.send(req.forwarded())})
Therequest interface is decorated withjshttp/type-is, the API is the same but you do not need to pass the request object:
fastify.get('/',(req,reply)=>{reply.send(req.is(['html','json']))})
Verify if a given condition is true, if not it throws the specified http error.
Useful if you work withasync routes:
// the custom message is optionalfastify.assert(req.headers.authorization,400,'Missing authorization header')
Theassert API also exposes the following methods:
fastify.assert.ok()fastify.assert.equal()fastify.assert.notEqual()fastify.assert.strictEqual()fastify.assert.notStrictEqual()fastify.assert.deepEqual()fastify.assert.notDeepEqual()
Async await wrapper for easy error handling without try-catch, inspired byawait-to-js:
const[err,user]=awaitfastify.to(db.findOne({user:'tyrion'}))
Do you feel there is some utility thateveryone can agree on that is not present?
Open an issue and let's discuss it! Even better a pull request!
The project name is inspired byvim-sensible, an awesome package that if you use vim you should use too.
Licensed underMIT.
About
Defaults for Fastify that everyone can agree on
Topics
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.