UNPKG

12.6 kBMarkdownView Raw
1<h1 align="center">Fastify</h1>
2
3## Getting Started
4Hello! Thank you for checking out Fastify!<br>
5This document aims to be a gentle introduction to the framework and its features. It is an elementary introduction with examples and links to other parts of the documentation.<br>
6Let's start!
7
8<a name="install"></a>
9### Install
10Install with npm:
11```
12npm i fastify --save
13```
14Install with yarn:
15```
16yarn add fastify
17```
18
19<a name="first-server"></a>
20### Your first server
21Let's write our first server:
22```js
23// Require the framework and instantiate it
24const fastify = require('fastify')({
25 logger: true
26})
27
28// Declare a route
29fastify.get('/', function (request, reply) {
30 reply.send({ hello: 'world' })
31})
32
33// Run the server!
34fastify.listen(3000, function (err, address) {
35 if (err) {
36 fastify.log.error(err)
37 process.exit(1)
38 }
39 fastify.log.info(`server listening on ${address}`)
40})
41```
42
43Do you prefer to use `async/await`? Fastify supports it out-of-the-box.<br>
44*(we also suggest using [make-promises-safe](https://github.com/mcollina/make-promises-safe) to avoid file descriptor and memory leaks)*
45```js
46const fastify = require('fastify')()
47
48fastify.get('/', async (request, reply) => {
49 return { hello: 'world' }
50})
51
52const start = async () => {
53 try {
54 await fastify.listen(3000)
55 } catch (err) {
56 fastify.log.error(err)
57 process.exit(1)
58 }
59}
60start()
61```
62
63Awesome, that was easy.<br>
64Unfortunately, writing a complex application requires significantly more code than this example. A classic problem when you are building a new application is how handle multiple files, asynchronous bootstrapping and the architecture of your code.<br>
65Fastify offers an easy platform that helps solve all of problems, and more.
66
67> ## Note
68> The above examples, and subsequent examples in this document, default to listening *only* on the localhost `127.0.0.1` interface. To listen on all available IPv4 interfaces the example should be modified to listen on `0.0.0.0` like so:
69>
70> ```js
71> fastify.listen(3000, '0.0.0.0', function (err, address) {
72> if (err) {
73> fastify.log.error(err)
74> process.exit(1)
75> }
76> fastify.log.info(`server listening on ${address}`)
77> })
78> ```
79>
80> Similarly, specify `::1` to accept only local connections via IPv6. Or specify `::` to accept connections on all IPv6 addresses, and, if the operating system supports it, also on all IPv4 addresses.
81>
82> When deploying to a Docker, or other type of, container this would be the easiest method for exposing the application.
83
84<a name="first-plugin"></a>
85### Your first plugin
86As with JavaScript everything is an object, with Fastify everything is a plugin.<br>
87Before digging into it, let's see how it works!<br>
88Let's declare our basic server, but instead of declaring the route inside the entry point, we'll declare it in an external file (checkout the [route declaration](https://github.com/fastify/fastify/blob/master/docs/Routes.md) docs).
89```js
90const fastify = require('fastify')({
91 logger: true
92})
93
94fastify.register(require('./our-first-route'))
95
96fastify.listen(3000, function (err, address) {
97 if (err) {
98 fastify.log.error(err)
99 process.exit(1)
100 }
101 fastify.log.info(`server listening on ${address}`)
102})
103```
104
105```js
106// our-first-route.js
107
108async function routes (fastify, options) {
109 fastify.get('/', async (request, reply) => {
110 return { hello: 'world' }
111 })
112}
113
114module.exports = routes
115```
116In this example we used the `register` API. This API is the core of the Fastify framework, and is the only way to register routes, plugins and so on.
117
118At the beginning of this guide we noted that Fastify provides a foundation that assists with the asynchronous bootstrapping of your application. Why this is important?
119Consider the scenario where a database connection is needed to handle data storage. Obviously the database connection needs to be available prior to the server accepting connections. How do we address this problem?<br>
120A typical solution is to use a complex callback, or promises, system that will mix the framework API with other libraries and the application code.<br>
121Fastify handles this internally, with minimum effort!
122
123Let's rewrite the above example with a database connection.<br>
124*(we will use a simple example, for a robust solution consider using [`fastify-mongo`](https://github.com/fastify/fastify-mongodb) or another in the Fastify [ecosystem](https://github.com/fastify/fastify/blob/master/docs/Ecosystem.md))*
125
126**server.js**
127```js
128const fastify = require('fastify')({
129 logger: true
130})
131
132fastify.register(require('./our-db-connector'), {
133 url: 'mongodb://localhost:27017/'
134})
135fastify.register(require('./our-first-route'))
136
137fastify.listen(3000, function (err, address) {
138 if (err) {
139 fastify.log.error(err)
140 process.exit(1)
141 }
142 fastify.log.info(`server listening on ${address}`)
143})
144```
145
146**our-db-connector.js**
147```js
148const fastifyPlugin = require('fastify-plugin')
149const MongoClient = require('mongodb').MongoClient
150
151async function dbConnector (fastify, options) {
152 const url = options.url
153 delete options.url
154
155 const db = await MongoClient.connect(url, options)
156 fastify.decorate('mongo', db)
157}
158
159// Wrapping a plugin function with fastify-plugin exposes the decorators,
160// hooks, and middlewares declared inside the plugin to the parent scope.
161module.exports = fastifyPlugin(dbConnector)
162```
163
164**our-first-route.js**
165```js
166async function routes (fastify, options) {
167 const database = fastify.mongo.db('db')
168 const collection = database.collection('test')
169
170 fastify.get('/', async (request, reply) => {
171 return { hello: 'world' }
172 })
173
174 fastify.get('/search/:id', async (request, reply) => {
175 const result = await collection.findOne({ id: request.params.id })
176 if (result.value === null) {
177 throw new Error('Invalid value')
178 }
179 return result.value
180 })
181}
182
183module.exports = routes
184```
185
186Wow, that was fast!<br>
187Let's recap what we have done here since we've introduced some new concepts.<br>
188As you can see, we used `register` both for the database connector and the routes registration.
189This is one of the best features of Fastify, it will load your plugins in the same order you declare them, and it will load the next plugin only once the current one has been loaded. In this way we can register the database connector in the first plugin and use it in the second *(read [here](https://github.com/fastify/fastify/blob/master/docs/Plugins.md#handle-the-scope) to understand how to handle the scope of a plugin)*.
190Plugin loading starts when you call `fastify.listen()`, `fastify.inject()` or `fastify.ready()`
191
192We have used the `decorate` API. Let's take a moment to understand what it is and how it works. A scenario is to use the same code/library in different parts of an application. A solution is to require the code/library that it is needed. This works, but is annoying because of duplicated code repeated and, if needed, long refactors.<br>
193To solve this Fastify offers the `decorate` API, which adds custom objects to the Fastify namespace, so that they can be used everywhere.
194
195To dig deeper into how Fastify plugins work, how to develop new plugins, and for details on how to use the whole Fastify API to deal with the complexity of asynchronously bootstrapping an application, read [the hitchhiker's guide to plugins](https://github.com/fastify/fastify/blob/master/docs/Plugins-Guide.md).
196
197<a name="plugin-loading-order"></a>
198### Loading order of your plugins
199To guarantee a consistent and predictable behavior of your application, we highly recommend to always load your code as shown below:
200```
201└── plugins (from the Fastify ecosystem)
202└── your plugins (your custom plugins)
203└── decorators
204└── hooks and middlewares
205└── your services
206```
207In this way you will always have access to all of the properties declared in the current scope.<br/>
208As discussed previously, Fastify offers a solid encapsulation model, to help you build your application as single and independent services. If you want to register a plugin only for a subset of routes, you have just to replicate the above structure.
209```
210└── plugins (from the Fastify ecosystem)
211└── your plugins (your custom plugins)
212└── decorators
213└── hooks and middlewares
214└── your services
215
216 └── service A
217 │ └── plugins (from the Fastify ecosystem)
218 │ └── your plugins (your custom plugins)
219 │ └── decorators
220 │ └── hooks and middlewares
221 │ └── your services
222
223 └── service B
224 └── plugins (from the Fastify ecosystem)
225 └── your plugins (your custom plugins)
226 └── decorators
227 └── hooks and middlewares
228 └── your services
229```
230
231<a name="validate-data"></a>
232### Validate your data
233Data validation is extremely important and is a core concept of the framework.<br>
234To validate incoming requests, Fastify uses [JSON Schema](http://json-schema.org/).
235Let's look at an example demonstrating validation for routes:
236```js
237const opts = {
238 schema: {
239 body: {
240 type: 'object',
241 properties: {
242 someKey: { type: 'string' },
243 someOtherKey: { type: 'number' }
244 }
245 }
246 }
247}
248
249fastify.post('/', opts, async (request, reply) => {
250 return { hello: 'world' }
251})
252```
253This example shows how to pass an options object to the route, which accepts a `schema` key, that contains all of the schemas for route, `body`, `querystring`, `params` and `headers`.<br>
254Read [Validation and Serialization](https://github.com/fastify/fastify/blob/master/docs/Validation-and-Serialization.md) to learn more.
255
256<a name="serialize-data"></a>
257### Serialize your data
258Fastify has first class support for JSON. It is extremely optimized to parse a JSON body and to serialize JSON output.<br>
259To speed up JSON serialization (yes, it is slow!) use the `response` key of the schema option like so:
260```js
261const opts = {
262 schema: {
263 response: {
264 200: {
265 type: 'object',
266 properties: {
267 hello: { type: 'string' }
268 }
269 }
270 }
271 }
272}
273
274fastify.get('/', opts, async (request, reply) => {
275 return { hello: 'world' }
276})
277```
278Simply by specifying a schema as shown, a speed up your of serialization by 2x or even 3x can be achieved. This also helps protect against leaking of sensitive data, since Fastify will serialize only the data present in the response schema.
279Read [Validation and Serialization](https://github.com/fastify/fastify/blob/master/docs/Validation-and-Serialization.md) to learn more.
280
281<a name="extend-server"></a>
282### Extend your server
283Fastify is built to be extremely extensible and very minimal, We believe that a bare minimum framework is all that is necessary to make great applications possible.<br>
284In other words, Fastify is not a "batteries included" framework, and relies on an amazing [ecosystem](https://github.com/fastify/fastify/blob/master/docs/Ecosystem.md)!
285
286<a name="test-server"></a>
287### Test your server
288Fastify does not offer a testing framework, but we do recommend a way to write your tests that uses the features and the architecture of Fastify.<br>
289Read the [testing](https://github.com/fastify/fastify/blob/master/docs/Testing.md) documentation to learn more!
290
291<a name="cli"></a>
292### Run your server from CLI
293Fastify also has CLI integration thanks to
294[fastify-cli](https://github.com/fastify/fastify-cli).
295
296First, install `fastify-cli`:
297
298```
299npm i fastify-cli
300```
301
302You can also install it globally with `-g`.
303
304Then, add the following lines to `package.json`:
305```json
306{
307 "scripts": {
308 "start": "fastify start server.js"
309 }
310}
311```
312
313And create your server file(s):
314```js
315// server.js
316'use strict'
317
318module.exports = async function (fastify, opts) {
319 fastify.get('/', async (request, reply) => {
320 return { hello: 'world' }
321 })
322}
323```
324
325Then run your server with:
326```bash
327npm start
328```
329
330<a name="slides"></a>
331### Slides and Videos
332- Slides
333 - [Take your HTTP server to ludicrous speed](https://mcollina.github.io/take-your-http-server-to-ludicrous-speed) by [@mcollina](https://github.com/mcollina)
334 - [What if I told you that HTTP can be fast](https://delvedor.github.io/What-if-I-told-you-that-HTTP-can-be-fast) by [@delvedor](https://github.com/delvedor)
335
336- Videos
337 - [Take your HTTP server to ludicrous speed](https://www.youtube.com/watch?v=5z46jJZNe8k) by [@mcollina](https://github.com/mcollina)
338 - [What if I told you that HTTP can be fast](https://www.webexpo.net/prague2017/talk/what-if-i-told-you-that-http-can-be-fast/) by [@delvedor](https://github.com/delvedor)