1 | <h1 align="center">Fastify</h1>
|
2 |
|
3 | ## HTTP2
|
4 |
|
5 | _Fastify_ offers **experimental support** for HTTP2 starting from Node
|
6 | 8.8.0, which includes HTTP2 without a flag. _Fastify_ supports HTTP2
|
7 | both over HTTPS or over plaintext. Note that HTTP2 is available only for node versions >= `8.8.1`.
|
8 |
|
9 | Currently none of the HTTP2-specific APIs are available through
|
10 | _Fastify_, but Node's `req` and `res` can be access through our
|
11 | `Request` and `Reply` interface. PRs are welcome.
|
12 |
|
13 | ### Secure (HTTPS)
|
14 |
|
15 | HTTP2 is supported in all modern browsers __only over a secure
|
16 | connection__:
|
17 |
|
18 | ```js
|
19 | 'use strict'
|
20 |
|
21 | const fs = require('fs')
|
22 | const path = require('path')
|
23 | const fastify = require('fastify')({
|
24 | http2: true,
|
25 | https: {
|
26 | key: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.key')),
|
27 | cert: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.cert'))
|
28 | }
|
29 | })
|
30 |
|
31 | fastify.get('/', function (request, reply) {
|
32 | reply.code(200).send({ hello: 'world' })
|
33 | })
|
34 |
|
35 | fastify.listen(3000)
|
36 | ```
|
37 |
|
38 | ALPN negotiation allows support for both HTTPS and HTTP/2 over the same socket.
|
39 | Node core `req` and `res` objects can be either [HTTP/1](https://nodejs.org/api/http.html)
|
40 | or [HTTP/2](https://nodejs.org/api/http2.html).
|
41 | _Fastify_ supports this out of the box:
|
42 |
|
43 | ```js
|
44 | 'use strict'
|
45 |
|
46 | const fs = require('fs')
|
47 | const path = require('path')
|
48 | const fastify = require('fastify')({
|
49 | http2: true,
|
50 | https: {
|
51 | allowHTTP1: true, // fallback support for HTTP1
|
52 | key: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.key')),
|
53 | cert: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.cert'))
|
54 | }
|
55 | })
|
56 |
|
57 | // this route can be accessed through both protocols
|
58 | fastify.get('/', function (request, reply) {
|
59 | reply.code(200).send({ hello: 'world' })
|
60 | })
|
61 |
|
62 | fastify.listen(3000)
|
63 | ```
|
64 |
|
65 | You can test your new server with:
|
66 |
|
67 | ```
|
68 | $ npx h2url https://localhost:3000
|
69 | ```
|
70 |
|
71 | ### Plain or insecure
|
72 |
|
73 | If you are building microservices, you can connect to HTTP2 in plain
|
74 | text, however this is not supported by browsers.
|
75 |
|
76 | ```js
|
77 | 'use strict'
|
78 |
|
79 | const fastify = require('fastify')({
|
80 | http2: true
|
81 | })
|
82 |
|
83 | fastify.get('/', function (request, reply) {
|
84 | reply.code(200).send({ hello: 'world' })
|
85 | })
|
86 |
|
87 | fastify.listen(3000)
|
88 | ```
|
89 |
|
90 | You can test your new server with:
|
91 |
|
92 | ```
|
93 | $ npx h2url http://localhost:3000
|
94 | ```
|
95 |
|