Node.js › HTTP & HTTPS Modules

How would you implement HTTP/2 server push or basic HTTP/2 support in Node.js using the node:http2 module?

Advanced

Answer

The http2 module provides native support for the HTTP/2 protocol, which offers multiplexed requests over a single connection (avoiding the head-of-line blocking of HTTP/1.1's connection-per-request model), header compression, and server push (letting a server proactively send resources it knows a client will need, before the client explicitly requests them) -- though server push has since been deprecated by most browsers in favor of other techniques like preload hints, multiplexing alone still provides significant performance benefits for applications making many small requests.
const http2 = require('node:http2');
const fs = require('node:fs');

const server = http2.createSecureServer({
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem'),
});

server.on('stream', (stream, headers) => {
  stream.respond({ ':status': 200, 'content-type': 'text/plain' });
  stream.end('Hello over HTTP/2');
});

server.listen(443);
Real-world example An API gateway handling many small, frequent requests from mobile clients over unreliable networks adopts HTTP/2 specifically for its connection multiplexing, letting many concurrent requests share a single TCP connection instead of requiring several separate connections, which particularly benefits clients on high-latency mobile networks.

Common follow-ups: Why has server push fallen out of favor despite initially seeming like a valuable feature?;What compatibility considerations exist when running an HTTP/2 server behind infrastructure (like some older load balancers) that might not fully support the protocol?