Giter Site home page Giter Site logo

fastify / fastify Goto Github PK

View Code? Open in Web Editor NEW
30.6K 293.0 2.2K 7.51 MB

Fast and low overhead web framework, for Node.js

Home Page: https://www.fastify.dev

License: Other

JavaScript 90.79% TypeScript 9.15% Shell 0.06%
webframework performance speed nodejs

fastify's Introduction

CI Package Manager CI Web SIte js-standard-style CII Best Practices

NPM version NPM downloads Security Responsible Disclosure Discord Contribute with Gitpod Open Collective backers and sponsors


An efficient server implies a lower cost of the infrastructure, a better responsiveness under load and happy users. How can you efficiently handle the resources of your server, knowing that you are serving the highest number of requests as possible, without sacrificing security validations and handy development?

Enter Fastify. Fastify is a web framework highly focused on providing the best developer experience with the least overhead and a powerful plugin architecture. It is inspired by Hapi and Express and as far as we know, it is one of the fastest web frameworks in town.

The main branch refers to the Fastify v4 release. Check out the v3.x branch for v3.

Table of Contents

Quick start

Create a folder and make it your current working directory:

mkdir my-app
cd my-app

Generate a fastify project with npm init:

npm init fastify

Install dependencies:

npm i

To start the app in dev mode:

npm run dev

For production mode:

npm start

Under the hood npm init downloads and runs Fastify Create, which in turn uses the generate functionality of Fastify CLI.

Install

To install Fastify in an existing project as a dependency:

Install with npm:

npm i fastify

Install with yarn:

yarn add fastify

Example

// Require the framework and instantiate it

// ESM
import Fastify from 'fastify'
const fastify = Fastify({
  logger: true
})
// CommonJs
const fastify = require('fastify')({
  logger: true
})

// Declare a route
fastify.get('/', (request, reply) => {
  reply.send({ hello: 'world' })
})

// Run the server!
fastify.listen({ port: 3000 }, (err, address) => {
  if (err) throw err
  // Server is now listening on ${address}
})

with async-await:

// ESM
import Fastify from 'fastify'
const fastify = Fastify({
  logger: true
})
// CommonJs
const fastify = require('fastify')({
  logger: true
})

fastify.get('/', async (request, reply) => {
  reply.type('application/json').code(200)
  return { hello: 'world' }
})

fastify.listen({ port: 3000 }, (err, address) => {
  if (err) throw err
  // Server is now listening on ${address}
})

Do you want to know more? Head to the Getting Started.

Note

.listen binds to the local host, localhost, interface by default (127.0.0.1 or ::1, depending on the operating system configuration). If you are running Fastify in a container (Docker, GCP, etc.), you may need to bind to 0.0.0.0. Be careful when deciding to listen on all interfaces; it comes with inherent security risks. See the documentation for more information.

Core features

  • Highly performant: as far as we know, Fastify is one of the fastest web frameworks in town, depending on the code complexity we can serve up to 76+ thousand requests per second.
  • Extensible: Fastify is fully extensible via its hooks, plugins and decorators.
  • Schema based: even if it is not mandatory we recommend to use JSON Schema to validate your routes and serialize your outputs, internally Fastify compiles the schema in a highly performant function.
  • Logging: logs are extremely important but are costly; we chose the best logger to almost remove this cost, Pino!
  • Developer friendly: the framework is built to be very expressive and help the developer in their daily use, without sacrificing performance and security.

Benchmarks

Machine: EX41S-SSD, Intel Core i7, 4Ghz, 64GB RAM, 4C/8T, SSD.

Method:: autocannon -c 100 -d 40 -p 10 localhost:3000 * 2, taking the second average

Framework Version Router? Requests/sec
Express 4.17.3 14,200
hapi 20.2.1 42,284
Restify 8.6.1 50,363
Koa 2.13.0 54,272
Fastify 4.0.0 77,193
-
http.Server 16.14.2 74,513

Benchmarks taken using https://github.com/fastify/benchmarks. This is a synthetic, "hello world" benchmark that aims to evaluate the framework overhead. The overhead that each framework has on your application depends on your application, you should always benchmark if performance matters to you.

Documentation

中文文档地址

Ecosystem

  • Core - Core plugins maintained by the Fastify team.
  • Community - Community supported plugins.
  • Live Examples - Multirepo with a broad set of real working examples.
  • Discord - Join our discord server and chat with the maintainers.

Support

Please visit Fastify help to view prior support issues and to ask new support questions.

Contributing

Whether reporting bugs, discussing improvements and new ideas or writing code, we welcome contributions from anyone and everyone. Please read the CONTRIBUTING guidelines before submitting pull requests.

Team

Fastify is the result of the work of a great community. Team members are listed in alphabetical order.

Lead Maintainers:

Fastify Core team

Fastify Plugins team

Great Contributors

Great contributors on a specific area in the Fastify ecosystem will be invited to join this group by Lead Maintainers.

Past Collaborators

Hosted by

We are a At-Large Project in the OpenJS Foundation.

Sponsors

Support this project by becoming a SPONSOR! Fastify has an Open Collective page where we accept and manage financial contributions.

Acknowledgements

This project is kindly sponsored by:

Past Sponsors:

This list includes all companies that support one or more of the team members in the maintenance of this project.

License

Licensed under MIT.

For your convenience, here is a list of all the licenses of our production dependencies:

  • MIT
  • ISC
  • BSD-3-Clause
  • BSD-2-Clause

fastify's People

Contributors

allevo avatar cemremengu avatar climba03003 avatar delvedor avatar dependabot-preview[bot] avatar dependabot[bot] avatar eomm avatar ethan-arrowood avatar fdawgs avatar fox1t avatar fralonra avatar greenkeeper[bot] avatar ivan-tymoshenko avatar jsumners avatar kibertoad avatar l2jliga avatar lucamaraschi avatar matthyk avatar mcollina avatar metcoder95 avatar nwoltman avatar rafaelgss avatar sebdeckers avatar serayaeryn avatar shogunpanda avatar starptech avatar trivikr avatar uzlopak avatar xtx1130 avatar zekth avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fastify's Issues

Authentication

We need to figure our how authentication would work in fastify.

Confusing payload/body API

const route = {
  method: 'POST',
  path: '/foo',
  handler: (req, reply) => {
    reply.send({bar: req.body.bar})
  },
  schema: {
    payload: {
      type: 'object',
      properties: {
        bar: {type: 'string'}
      }
    }
  }
}

Notice that the validation schema for the POST body is labeled payload, whereas within the handler method it is referenced as body. This mix of terminology is confusing, particularly for someone used to using Hapi. Either the validation config should change "payload" to "body", or the handler should be passed req.payload.

url wildcard support

Are you guys planning on url wildcard support in the routes ? I'm not sure if it's possible with the current setup . Also, I'm not sure if it should be handled on the frame work or inside wayfarer.

Supplying a logger removes the stream of the logger

'use strict'

const log = require('pino')()
const fastify = require('fastify')({logger: log})

log.info('pino is working')

fastify.get('/', (req, reply) => reply.send({hello: 'world'}))

fastify.listen(8000, (err) => {
  if (err) throw err
  // the next line will fail because `pino-http` removes the stream from `log`
  log.info('server started: http://localhost:%s', fastify.server.address().port)
})

Clarification on middleware wildcards

In the docs:

Note that this does not support routes with parameters, (eg: /user/:id/comments) and wildcard is not supported in multiple paths.

Does this mean that /user/* will not match /user/:id/comments?

Error code shorthand in hooks handling does not work correctly

Use case:

// first hook
fastify.addHook('preHanlder', (req, reply, done) => {
  done()
})
// second hook
fastify.addHook('preHanlder', (req, reply, done) => {
  done(new Error('some error'), 400)
})

The expected response must have a statusCode equal to 400, instead we got 500, because of this.
Since the hooks that returns an error is the second, the error status code will be in code[1].

@mcollina suggestions?

Error responses are not stringified correctly

Use case:

fastify.addHook('preHandler', (req, reply, next) => {
  if (someCondition) {
    return next(new Error('some error'))
  }
}

If the error case is triggered, the client will receive {}, because JSON.stringify does not stringify the error properties.
This can be easily fixed by doing the following:

JSON.stringify(new Error('some error', ['message', 'arguments', 'type', 'name']))
// => "{"message":"some error","name":"Error"}"

The reply implementation of the error handling uses fast-json-stringify that does not support replacer functions, so we can make a PR to fast-json-stringify or move to JSON.stringify for the errors.

organization

We should probably do a fastify organization :)

Register - unhandled error

While working at fastify/point-of-view#1 I found that if I pass and error to the next callback of register, even if I handle it, fastify will throw and error.
This because of this specific line of avvio.
Internally we have not a listener for that error event, and node will throw the following error:

< Error: Missing engine
<     at fastifyView (.../point-of-view/index.js:13:10)
<     at Plugin.exec (.../point-of-view/node_modules/avvio/boot.js:191:3)
<     at Boot.loadPlugin (.../point-of-view/node_modules/avvio/boot.js:205:10)
<     at release (.../point-of-view/node_modules/fastq/queue.js:127:16)
<     at Object.resume (.../point-of-view/node_modules/fastq/queue.js:61:7)
<     at _combinedTickCallback (internal/process/next_tick.js:67:7)
<     at process._tickCallback (internal/process/next_tick.js:98:9)
<     at Timeout.Module.runMain [as _onTimeout] (module.js:606:11)
<     at ontimeout (timers.js:365:14)
<     at tryOnTimeout (timers.js:237:5)
< events.js:160
<       throw er; // Unhandled 'error' event
<     

This can be easily fixed with the following line inside Fastify.

app.on('error', () => {})

Now the question is, how do we want to solve this issue?
The faster solution is to update avvio, remove the error emitter and update the noop function is this way:

function noop (err) {
  if (err) throw err
}

But I think that in the scope of avvio as is, that error emitter is useful to catch global errors.
Contrariwise, in Fastify it does not make sense imo, because is counterintuitive for the user.

Thoughts?
cc @mcollina

query string is not being parsed in middleware handlers

hi,

while implementing the fastify integration for graphql-server i have noticed that in the middleware handler you have to manually parse the query string if you need access to while in the route handler it comes already parsed.

is this the expected behaviour? (in express it comes parsed in middlewares too)

you can see the difference between express and fastify integrations:

README

as titled 👯‍♂️ 👯

Update benchmarks

Due to using pino-http, we are losing 2k req/s on my laptop.
maybe we can improve pino-http, but we should update our benchmark.

Out schema for non 2xx response

Currently the out schema is applied to every response.
Is there a way to set a "global" out schema for all non 2xx request?
Or apply the out schema only to the 2xx response?
Any suggestions?

Travis and Coveralls

After moving the repo to the organization both travis and coveralls not behave as before, probably they need to be reconfigured.

querystring validation/parsing

First off, thanks for creating this, I'm very excited to see where this goes, and it has been great to work with thus far.

Question about querystring in the schema, it doesn't appear to be doing anything. I'm hoping you could point out what I'm missing:

Here's an example:

fastify.route({
    "method": "GET",
    "url": "/list",
    "schema": {
      "querystring": {
        "limit": {
          "type": "integer"
        }
      },
      "out": {
        "type": "array",
        "items": {
          "type": "object",
          "properties": {
            "id": {
              "type": "string"
            },
            "count": {
              "type": "integer"
            }
          }
        }
      }
    }
  })

req.query outputs:

Valid query: /list?limit=10
{ limit: '10' } // Limit is a string

Invalid query param: /list?limit=a
{ limit: 'a' } // Invalid limit passed through as string

Extra query params: /list?limit=1&lookatme=true
{ limit: 'a', lookatme: 'true' }

Hopefully you can tell me what I'm doing incorrectly, thanks.

Hooks

Another feature that I think we need to implement are Hooks.

I'm developing in my local copy the onRequest hook to make some experiments and I'm very happy with the result. A decision that I must take at the moment is: where call the onRequestHook inside the lifecycle of fastify.

These are the two options:

  1. after the middleware execution but before the routing function:
new request => middlware => onRequest => router => validation => Request/Reply => handler
  1. after the routing function, the validation and the creation of the object Reques and Repy, but before the user's handler.
new request => middlware => router => validation => Request/Reply => onRequest => handler

From the function perspective the difference is:
in the first case the function makes changes on the "vanilla" request and response object from node core, in the second case the function will work on Request and Reply objects from fastify.

But the main difference is that in the first case the change will work for all the routes (for example can change the req.url), while in the second one the user will access the instances of Request/Reply of the specific route. This means that the user could add methods/data to the Request/Reply instances (at runtime!) and use them in the route handler.

Thoughts?

cc: @mcollina @lucamaraschi @davidmarkclements

Hooks context

If you use decorate to add a new function to Fastify, that function will have Fastify as context, for example:

fastify.decorate('test', function () {
  console.log(this) // this is fastify
})

While if you add a hook the context is undefined. Could be useful bind it by default?

fastify.addHook('onRequest', function (req, reply, next) {
  console.log(this) // undefined
})

Serving static files

I haven't found any documentation about serving static files, then @mcollina put me on the right path suggesting to try a middleware for it.

Express serve-static works like a charm to map a folder to /:

fastify.use(serveStatic(`${__dirname}/public`))
> curl http://localhost:8888/index.html
<html>
  <head><title>public/index.html</title></head>
  <body>Hello world!</body>
</html>

but I couldn't find a way to map a path to the public folder.
If I wanted to do the same on Express I would have something on the lines of

app.use('/assets', serveStatic(`${__dirname}/dist`))

It would be a nice addition

An in-range update of ajv is breaking the build 🚨

Version 5.1.6 of ajv just got published.

Branch Build failing 🚨
Dependency ajv
Current Version 5.1.5
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

ajv is a direct dependency of this project this is very likely breaking your project right now. If other packages depend on you it’s very likely also breaking them.
I recommend you give this issue a very high priority. I’m sure you can resolve this 💪

Status Details
  • coverage/coveralls Coverage pending from Coveralls.io Details
  • continuous-integration/travis-ci/push The Travis CI build could not complete due to an error Details

Commits

The new version differs by 8 commits.

  • ff9f93a 5.1.6
  • 0d6ae42 fix: traverse only schema objects, fixes #521
  • daf7d6b docs: using with draft-04
  • 9f0b563 Merge pull request #508 from epoberezkin/greenkeeper/nyc-11.0.2
  • 55727d9 test: remove node v0.12, v5, add v8 to travis test
  • eac5902 chore(package): update nyc to version 11.0.2
  • f1c9f15 Merge pull request #507 from epoberezkin/greenkeeper/chai-4.0.1
  • d74a381 chore(package): update chai to version 4.0.1

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

An in-range update of find-my-way is breaking the build 🚨

Version 1.3.1 of find-my-way just got published.

Branch Build failing 🚨
Dependency find-my-way
Current Version 1.3.0
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

find-my-way is a direct dependency of this project this is very likely breaking your project right now. If other packages depend on you it’s very likely also breaking them.
I recommend you give this issue a very high priority. I’m sure you can resolve this 💪

Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details
  • coverage/coveralls First build on greenkeeper/find-my-way-1.3.1 at 96.4% Details

Release Notes v1.3.1
  • Call find only one time - #18
  • Fix deopt - #18
Commits

The new version differs by 4 commits.

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Close: Not running error

If you call the close api without an active server, you will get the Error: Not running error.
This is very inconvenient if you are using the inject api in your test.

Example:

const { beforeEach, afterEach, test } = require('tap')
const build = require('./server')

var instance = null

beforeEach(done => {
  build(i => {
    instance = i
    done()
  })
})

afterEach(done => {
  instance.close(err => {
    if (err) throw err
    done() // this will never be called
  })
})

test(...)

Use the close api is very useful if you must close some db connection, but this error is tricky and annoying.
An user-side solution could be:

afterEach(done => {
  instance.close(err => {
    if (err.message !== 'Not running') throw err
    done()
  })
})

Maybe we can directly handle that error in our internals.

fastify.server.close(err => {
  if (err.message === 'Not running') err = null
  cb(err)
})

Thoughts?

Renaming fields on response schema

I've browed the schema specs but was not able to find this. I wonder if you have encountered this issue and how you might suggest dealign with it besides just pre parsing my db output which sort of defeats the purpose a bit.

For example if I wished to pull mongo data and expose it through the schema I might want to rename my _id field to id. This seems like a useful option (also along those lines is the restructuring of the response).

Prefix should support / routes

test('Prefix should support /', t => {
  t.plan(1)
  const fastify = Fastify()

  fastify.register(function (fastify, opts, next) {
    fastify.get('/', (req, reply) => {
      reply.send({ hello: 'world' })
    })
    next()
  }, { prefix: '/v1' })

  fastify.inject({
    method: 'GET',
    url: '/v1'
  }, res => {
    t.same(JSON.parse(res.payload), { hello: 'world' })
  })
})

Response stream?

Is there a way for me to stream a response via fastify (essentially access res.write)?

Graphics

I've designed this graphic, what do you think?
full logo

Add more benchmarks

The current benchmarks are a bit boring and don't say the full story:

Benchmarks

Hapi: 2200 req/sec
Restify: 6133 req/sec
Express: 8534 req/sec
Koa: 9640 req/sec
Fastify: 21287 req/sec

Some information that people would like to know:

  • Time to first byte
  • Response time
  • Scalability

If you Google "nginx vs express.js benchmark" and similar, there will be quite a few benchmarks/ graphs that would be nice to have.

This is your main selling point. I'd focus on that. Good luck.

Proxy feature

Hi

Just wondering whether you are looking at supporting proxies a bit like H2o2?

Thanks
Simon

Content type with charset

When using 'Content-Type': 'application/json' some http client append the charset to the header, so the content type becomes 'application/json;charset=utf-8'.
When this happens, Fastify returns a 415, because of our check

if (req.headers['content-type'] && req.headers['content-type'] === 'application/json') {

An easy fix is use .indexOf or .split(;)[0]

if (req.headers['content-type'] && req.headers['content-type'].indexOf('application/json') > -1) {

I ran the benchmarks and there wasn't any sensible changes.
Any other idea to solve this?

cc @mcollina @lucamaraschi

body schema minLength not working

Just found that minLength in json schema isn't working as expected.
The required works, but not the minLength, am I missing something ?

my code with node js 7.10.0 :

'use strict';

const fastify = require('fastify')();

fastify.post('/test', {
   body: {
      name: {
         type: 'string',
         minLength: 6,
      },
      required: ['name'],
   }
}, (req, res) => {
   console.log(req.body);
   res.send({hello: 'world'});
});

fastify.listen(3400, (err) => {
   if (err) throw err;
   console.log('listening on port 3400');
});

and the response with postman :

screen shot 2017-05-19 at 10 58 49 pm

Expose logger instance?

The configured logger is exposed during requests, but it may be useful to expose it as a property. For example:

const fastify = require('fastify')()
const log = fastify.logger

Thoughts?

Multiple response types

Is there a way to define multiple response types? For example a route response my have a different structure for a success/error response.

I have a route that returns an array of objects on success, but an error object on failure.

Using regex when capturing the parameters

The following route definition works in Express.js, but does not work in Fastify, /cinema-logos/:cinemaId(\\d+)-:cinemaName.svg.

In Fastify, it produces params: { 'cinemaId(\d+)-:cinemaName.svg': '1000146-vue.svg' },, whereas I expect to get cinemaId and cinemaName as separate parameters.

:cinemaId-:cinemaName is not working either, because the matching expression appears to be greedy: 'cinemaId-:cinemaName.svg': '1000146-vue.svg'.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.