Socket
Socket
Sign inDemoInstall

fastify

Package Overview
Dependencies
34
Maintainers
2
Versions
282
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    fastify

Fast and low overhead web framework, for Node.js


Version published
Maintainers
2
Install size
2.31 MB
Created

Package description

What is fastify?

Fastify is a fast and low overhead web framework for Node.js. It is highly performant and provides an extensive plugin architecture, making it suitable for building a wide range of server-side applications and services.

What are fastify's main functionalities?

Web Server

Fastify allows you to create a web server that can handle HTTP requests and send responses. The above code demonstrates setting up a simple server that responds with JSON when the root route is accessed.

const fastify = require('fastify')({ logger: true });

fastify.get('/', async (request, reply) => {
  return { hello: 'world' };
});

fastify.listen(3000, (err, address) => {
  if (err) throw err;
  fastify.log.info(`server listening on ${address}`);
});

Route Shorthand Methods

Fastify provides shorthand methods for different HTTP methods like GET, POST, etc. This makes it easy to define routes for various request types.

fastify.get('/example', (request, reply) => {
  reply.send({ message: 'This is a GET request' });
});

fastify.post('/example', (request, reply) => {
  reply.send({ message: 'This is a POST request' });
});

Schema Validation

Fastify supports schema validation for request payloads, query strings, and parameters using JSON Schema. This ensures that the data received is in the expected format.

const schema = {
  body: {
    type: 'object',
    required: ['name'],
    properties: {
      name: { type: 'string' },
      age: { type: 'number' }
    }
  }
};

fastify.post('/user', { schema }, (request, reply) => {
  // Handle request knowing that the body has been validated against the schema
});

Plugins

Fastify has a powerful plugin system that allows you to extend its core functionality. Plugins can add new features, routes, services, and decorators to the Fastify instance.

const myPlugin = async (fastify, options) => {
  fastify.decorate('utility', () => {
    return 'something useful';
  });
};

fastify.register(myPlugin);

// Now you can use fastify.utility() in your application

Lifecycle Hooks

Fastify provides lifecycle hooks that can be used to execute code at various stages of the request/response cycle, such as onRequest, preHandler, onResponse, etc.

fastify.addHook('onRequest', (request, reply, done) => {
  // Perform some operations before the request handler is executed
  done();
});

Other packages similar to fastify

Readme

Source

Fastify  Build Status Coverage Status

Extremely fast node.js web framework, inspired by Express, Hapi and Restify.

Fastify is alpha software in active development, feel free to contribute!

Install

npm install fastify --save

Usage

'use strict'

const fastify = require('fastify')()
const http = require('http')
const server = http.createServer(fastify)

const schema = {
  out: {
    type: 'object',
    properties: {
      hello: {
        type: 'string'
      }
    }
  }
}

fastify
  .get('/', schema, function (req, reply) {
    reply(null, { hello: 'world' })
  })
  .get('/no-schema', function (req, reply) {
    reply(null, { hello: 'world' })
  })
  .post('/', schema, function (req, reply) {
    reply(null, { hello: 'world' })
  })

server.listen(8000, function (err) {
  if (err) {
    throw err
  }

  console.log(`server listening on ${server.address().port}`)
})

Benchmarks

As far as we know, it is one of the fastest web frameworks in town:

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

All benchmarks where average taken over 5 seconds, on the second run of autocannon -c 100 -d 5 -p 10 localhost:3000.

## API

fastify(req, res)

Returns a new fastify instance, which is a function with some method attached. req and res are the request and response objects from Node Core.

const fastify = require('fastify')()
const http = require('http')
const server = http.createServer(fastify)

server.listen(8000, function (err) {
  if (err) {
    throw err
  }

  console.log(`server listening on ${server.address().port}`)
})

fastify.route(options)

Options:

  • method: currently it supports only GET, POST and PUT.

  • url: the path of the url to match this route, it uses wayfarer as a router.

  • schema: an object containing the schemas for the request and response. They need to be in [JSON Schema][jsonschema] format:

    • payload: validates the body of the request if it is a POST or a PUT. It uses ajv.
    • querystring: validates the querystring. It uses ajv.
    • params: validates the params. It uses ajv.
    • out: filter and generate a schema for the response, setting a schema allows us to have 10-20% more throughput. It uses fast-json-stringify.
  • handler(request, repy(err, statusCode, object): the function that will handle this request. The request parameter is defined in Request. object inside the request is a JavaScript object that will be JSONified, possibly using the schema defined options.schema.out.

For POST and PUT, the incoming request body will be parsed.

Request

An object including the following properties:

  • query - the parsed querystring
  • body - the body
  • params - the params matching the URL
  • req - the incoming HTTP request from Node core

fastify.get(path, [schema], handler)

Calls route with the given path, schemas and handler, setting up the GET method.

fastify.post(path, [schema], handler)

Calls route with the given path, schemas and handler, setting up the POST method.

fastify.put(path, [schema], handler)

Calls route with the given path, schemas and handler, setting up the PUT method.

fastify.register(plugin, [options], [callback])

Used to register one or more plugins.
plugin can be a single function or an array of functions.
In case of the array of functions, the same options object and callback will be passed to them.
boot-in-the-arse is used to load the plugins.
Example:

// server.js
const fastify = require('fastify')()
const http = require('http')
const server = http.createServer(fastify)

fastify.register(require('./plugin'), function (err) {
  if (err) throw err
})

const opts = {
  hello: 'world',
  something: true
}
fastify.register([
  require('./another-plugin')
  require('./yet-another-plugin')
], opts, function (err) {
  if (err) throw err
})

server.listen(8000, function (err) {
  if (err) {
    throw err
  }

  console.log(`server listening on ${server.address().port}`)
})
// plugin.js
module.exports = function (fastify, options, next) {
  fastify.get('/', schema, function (req, reply) {
    reply(null, { hello: 'world' })
  })
  next()
}

The Team

Matteo Collina

https://github.com/mcollina

https://www.npmjs.com/~matteo.collina

https://twitter.com/matteocollina

Tomas Della Vedova

https://github.com/delvedor

https://www.npmjs.com/~delvedor

https://twitter.com/delvedor

Acknowledgements

This project was kindly sponsored by nearForm.

License

Licensed under MIT.

Keywords

FAQs

Last updated on 20 Oct 2016

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc