UNPKG

12.5 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 preface 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 to handle multiple files, asynchronous bootstrapping and the architecture of your code.<br>
65Fastify offers an easy platform that helps to solve all of the problems outlined above, 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 using `0.0.0.0` or `::` would be the easiest method for exposing the application.
83
84<a name="first-plugin"></a>
85### Your first plugin
86As with JavaScript, where 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 (check out 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, which is the core of the Fastify framework. It is the only way to add routes, plugins, et cetera.
117
118At the beginning of this guide, we noted that Fastify provides a foundation that assists with asynchronous bootstrapping of your application. Why is this important?
119Consider the scenario where a database connection is needed to handle data storage. Obviously, the database connection needs to be available before the server is accepting connections. How do we address this problem?<br>
120A typical solution is to use a complex callback, or promises - a 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
126First, install `fastify-plugin`:
127
128```
129npm install --save fastify-plugin
130```
131
132**server.js**
133```js
134const fastify = require('fastify')({
135 logger: true
136})
137
138fastify.register(require('./our-db-connector'), {
139 url: 'mongodb://localhost:27017/'
140})
141fastify.register(require('./our-first-route'))
142
143fastify.listen(3000, function (err, address) {
144 if (err) {
145 fastify.log.error(err)
146 process.exit(1)
147 }
148 fastify.log.info(`server listening on ${address}`)
149})
150```
151
152**our-db-connector.js**
153```js
154const fastifyPlugin = require('fastify-plugin')
155const MongoClient = require('mongodb').MongoClient
156
157async function dbConnector (fastify, options) {
158 const url = options.url
159 delete options.url
160
161 const db = await MongoClient.connect(url, options)
162 fastify.decorate('mongo', db)
163}
164
165// Wrapping a plugin function with fastify-plugin exposes the decorators,
166// hooks, and middlewares declared inside the plugin to the parent scope.
167module.exports = fastifyPlugin(dbConnector)
168```
169
170**our-first-route.js**
171```js
172async function routes (fastify, options) {
173 const database = fastify.mongo.db('db')
174 const collection = database.collection('test')
175
176 fastify.get('/', async (request, reply) => {
177 return { hello: 'world' }
178 })
179
180 fastify.get('/search/:id', async (request, reply) => {
181 const result = await collection.findOne({ id: request.params.id })
182 if (result.value === null) {
183 throw new Error('Invalid value')
184 }
185 return result.value
186 })
187}
188
189module.exports = routes
190```
191
192Wow, that was fast!<br>
193Let's recap what we have done here since we've introduced some new concepts.<br>
194As you can see, we used `register` both for the database connector and the registration of the routes.
195This 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)*.
196Plugin loading starts when you call `fastify.listen()`, `fastify.inject()` or `fastify.ready()`
197
198We have also used the `decorate` API to add custom objects to the Fastify namespace, making them available for use everywhere. Use of this API is encouraged to faciliate easy code reuse and to decrease code or logic duplication.
199
200To 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).
201
202<a name="plugin-loading-order"></a>
203### Loading order of your plugins
204To guarantee a consistent and predictable behaviour of your application, we highly recommend to always load your code as shown below:
205```
206└── plugins (from the Fastify ecosystem)
207└── your plugins (your custom plugins)
208└── decorators
209└── hooks and middlewares
210└── your services
211```
212In this way, you will always have access to all of the properties declared in the current scope.<br/>
213As 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 just have to replicate the above structure.
214```
215└── plugins (from the Fastify ecosystem)
216└── your plugins (your custom plugins)
217└── decorators
218└── hooks and middlewares
219└── your services
220
221 └── service A
222 │ └── plugins (from the Fastify ecosystem)
223 │ └── your plugins (your custom plugins)
224 │ └── decorators
225 │ └── hooks and middlewares
226 │ └── your services
227
228 └── service B
229 └── plugins (from the Fastify ecosystem)
230 └── your plugins (your custom plugins)
231 └── decorators
232 └── hooks and middlewares
233 └── your services
234```
235
236<a name="validate-data"></a>
237### Validate your data
238Data validation is extremely important and a core concept of the framework.<br>
239To validate incoming requests, Fastify uses [JSON Schema](http://json-schema.org/).
240Let's look at an example demonstrating validation for routes:
241```js
242const opts = {
243 schema: {
244 body: {
245 type: 'object',
246 properties: {
247 someKey: { type: 'string' },
248 someOtherKey: { type: 'number' }
249 }
250 }
251 }
252}
253
254fastify.post('/', opts, async (request, reply) => {
255 return { hello: 'world' }
256})
257```
258This 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>
259Read [Validation and Serialization](https://github.com/fastify/fastify/blob/master/docs/Validation-and-Serialization.md) to learn more.
260
261<a name="serialize-data"></a>
262### Serialize your data
263Fastify has first class support for JSON. It is extremely optimized to parse JSON bodies and to serialize JSON output.<br>
264To speed up JSON serialization (yes, it is slow!) use the `response` key of the schema option as shown in the following example:
265```js
266const opts = {
267 schema: {
268 response: {
269 200: {
270 type: 'object',
271 properties: {
272 hello: { type: 'string' }
273 }
274 }
275 }
276 }
277}
278
279fastify.get('/', opts, async (request, reply) => {
280 return { hello: 'world' }
281})
282```
283Simply by specifying a schema as shown, you can speed up serialization by a factor of 2-3. This also helps to protect against leakage of potentially sensitive data, since Fastify will serialize only the data present in the response schema.
284Read [Validation and Serialization](https://github.com/fastify/fastify/blob/master/docs/Validation-and-Serialization.md) to learn more.
285
286<a name="extend-server"></a>
287### Extend your server
288Fastify is built to be extremely extensible and minimal, we believe that a bare bones framework is all that is necessary to make great applications possible.<br>
289In 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)!
290
291<a name="test-server"></a>
292### Test your server
293Fastify does not offer a testing framework, but we do recommend a way to write your tests that uses the features and architecture of Fastify.<br>
294Read the [testing](https://github.com/fastify/fastify/blob/master/docs/Testing.md) documentation to learn more!
295
296<a name="cli"></a>
297### Run your server from CLI
298Fastify also has CLI integration thanks to [fastify-cli](https://github.com/fastify/fastify-cli).
299
300First, install `fastify-cli`:
301
302```
303npm i fastify-cli
304```
305
306You can also install it globally with `-g`.
307
308Then, add the following lines to `package.json`:
309```json
310{
311 "scripts": {
312 "start": "fastify start server.js"
313 }
314}
315```
316
317And create your server file(s):
318```js
319// server.js
320'use strict'
321
322module.exports = async function (fastify, opts) {
323 fastify.get('/', async (request, reply) => {
324 return { hello: 'world' }
325 })
326}
327```
328
329Then run your server with:
330```bash
331npm start
332```
333
334<a name="slides"></a>
335### Slides and Videos
336- Slides
337 - [Take your HTTP server to ludicrous speed](https://mcollina.github.io/take-your-http-server-to-ludicrous-speed) by [@mcollina](https://github.com/mcollina)
338 - [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)
339
340- Videos
341 - [Take your HTTP server to ludicrous speed](https://www.youtube.com/watch?v=5z46jJZNe8k) by [@mcollina](https://github.com/mcollina)
342 - [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)