HTTP2

HTTP2

Fastify offers experimental support for HTTP2 starting from Node 8 LTS, which includes HTTP2 without a flag; HTTP2 is supported over either HTTPS or plaintext.

Currently, none of the HTTP2-specific APIs are available through Fastify, but Node’s req and res can be accessed through our Request and Reply interface. PRs are welcome.

Secure (HTTPS)

HTTP2 is supported in all modern browsers only over a secure connection:

  1. 'use strict'
  2. const fs = require('fs')
  3. const path = require('path')
  4. const fastify = require('fastify')({
  5. http2: true,
  6. https: {
  7. key: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.key')),
  8. cert: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.cert'))
  9. }
  10. })
  11. fastify.get('/', function (request, reply) {
  12. reply.code(200).send({ hello: 'world' })
  13. })
  14. fastify.listen(3000)

ALPN negotiation allows support for both HTTPS and HTTP/2 over the same socket. Node core req and res objects can be either HTTP/1 or HTTP/2. Fastify supports this out of the box:

  1. 'use strict'
  2. const fs = require('fs')
  3. const path = require('path')
  4. const fastify = require('fastify')({
  5. http2: true,
  6. https: {
  7. allowHTTP1: true, // fallback support for HTTP1
  8. key: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.key')),
  9. cert: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.cert'))
  10. }
  11. })
  12. // this route can be accessed through both protocols
  13. fastify.get('/', function (request, reply) {
  14. reply.code(200).send({ hello: 'world' })
  15. })
  16. fastify.listen(3000)

You can test your new server with:

  1. $ npx h2url https://localhost:3000

Plain or insecure

If you are building microservices, you can connect to HTTP2 in plain text, however, this is not supported by browsers.

  1. 'use strict'
  2. const fastify = require('fastify')({
  3. http2: true
  4. })
  5. fastify.get('/', function (request, reply) {
  6. reply.code(200).send({ hello: 'world' })
  7. })
  8. fastify.listen(3000)

You can test your new server with:

  1. $ npx h2url http://localhost:3000