UNPKG

2.26 kBMarkdownView Raw
1<h1 align="center">Fastify</h1>
2
3## HTTP2
4
5_Fastify_ offers **experimental support** for HTTP2 starting from Node
68.8.0, which includes HTTP2 without a flag. _Fastify_ supports HTTP2
7both over HTTPS or over plaintext. Note that HTTP2 is available only for node versions >= `8.8.1`.
8
9Currently 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
15HTTP2 is supported in all modern browsers __only over a secure
16connection__:
17
18```js
19'use strict'
20
21const fs = require('fs')
22const path = require('path')
23const 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
31fastify.get('/', function (request, reply) {
32 reply.code(200).send({ hello: 'world' })
33})
34
35fastify.listen(3000)
36```
37
38ALPN negotiation allows support for both HTTPS and HTTP/2 over the same socket.
39Node core `req` and `res` objects can be either [HTTP/1](https://nodejs.org/api/http.html)
40or [HTTP/2](https://nodejs.org/api/http2.html).
41_Fastify_ supports this out of the box:
42
43```js
44'use strict'
45
46const fs = require('fs')
47const path = require('path')
48const 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
58fastify.get('/', function (request, reply) {
59 reply.code(200).send({ hello: 'world' })
60})
61
62fastify.listen(3000)
63```
64
65You can test your new server with:
66
67```
68$ npx h2url https://localhost:3000
69```
70
71### Plain or insecure
72
73If you are building microservices, you can connect to HTTP2 in plain
74text, however this is not supported by browsers.
75
76```js
77'use strict'
78
79const fastify = require('fastify')({
80 http2: true
81})
82
83fastify.get('/', function (request, reply) {
84 reply.code(200).send({ hello: 'world' })
85})
86
87fastify.listen(3000)
88```
89
90You can test your new server with:
91
92```
93$ npx h2url http://localhost:3000
94```
95