NodeJS native http2 support
Asked Answered
P

4

18

Does NodeJS 4.x or 5.x natively support the HTTP/2 protocol? I know there's http2 package but it's an external thing.

Are there some plans to merge http2 support into the Node's core?

Phrase answered 17/2, 2016 at 10:26 Comment(0)
P
9

--expose-http2 flag enables experimental HTTP2 support. This flag can be used in nightly build (Node v8.4.0) since Aug 5, 2017 (pull request).

node --expose-http2 client.js

client.js

const http2 = require('http2');
const client = http2.connect('https://stackoverflow.com');

const req = client.request();
req.setEncoding('utf8');

req.on('response', (headers, flags) => {
  console.log(headers);
});

let data = '';
req.on('data', (d) => data += d);
req.on('end', () => client.destroy());
req.end();

--experimental-modules flag also can be added since Node v8.5.0.

node --expose-http2 --experimental-modules client.mjs

client.mjs

import http2 from 'http2';

const client = http2.connect('https://stackoverflow.com');

I use NVS (Node Version Switcher) for testing nightly builds.

nvs add nightly
nvs use nightly
Pallua answered 6/8, 2017 at 4:45 Comment(2)
Don't forget to add process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; for self-signed certs to be able to make SSL connection.Jacklin
See also the up-to-date client-side example in the Node.js documentation: nodejs.org/api/http2.html#http2_client_side_example.Cuttlefish
H
8

No, not yet.

Here is the discussion about adding HTTP/2 support to core NodeJS: https://github.com/nodejs/NG/issues/8

Hooge answered 1/3, 2016 at 18:28 Comment(0)
D
2

From node v8.8.1, you do not need the --expose-http2 flag when you are running your code.

The simplest way to get started with HTTP/2 is to make use of the compatibility API that Node.js exposes.

const http2 = require('http2');
const fs = require('fs');

const options = {
    key: fs.readFileSync('./selfsigned.key'),
    cert: fs.readFileSync('./selfsigned.crt'),
    allowHTTP1: true
}

const server = http2.createSecureServer(options, (req, res) => {
  res.setHeader('Content-Type', 'text/html');
  res.end('ok');
});

server.listen(443);

I have written more about about using the native HTTP/2 Node.js exposes to create a server here.

Dollie answered 3/11, 2017 at 6:58 Comment(1)
See also the up-to-date server-side example in the Node.js documentation: nodejs.org/api/http2.html#http2_server_side_example.Cuttlefish
B
1

Node 8.4.0 has an experimental Http2 API. Docs here nodejs http2

Baxy answered 8/9, 2017 at 3:26 Comment(1)
Do you know when http2 support in nodejs will be no longer experimental?Protohistory

© 2022 - 2024 — McMap. All rights reserved.