Back to results for “Performance”
Node.js › HTTP & Web Servers

What is the difference between HTTP/1.1 and HTTP/2, and how does Node.js support HTTP/2 via the node:http2 module?

Intermediate

Answer

HTTP/1.1 opens a new TCP connection (or reuses a limited number via keep-alive) for each set of requests, processing them largely sequentially per connection, leading to head-of-line blocking. HTTP/2 introduces multiplexing -- multiple requests and responses can be interleaved over a single TCP connection simultaneously, along with header compression (HPACK) and server push, meaningfully reducing latency for pages or APIs involving many concurrent requests -- Node.js supports HTTP/2 via the dedicated node:http2 module, requiring TLS for full browser compatibility.
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 });
  stream.end('Hello over HTTP/2');
});
Real-world example An API serving many small, related resources to a single-page application adopts HTTP/2 specifically to take advantage of multiplexing, letting the browser fetch a dozen resources over one connection simultaneously rather than being limited by HTTP/1.1's per-connection request concurrency limits.

Common follow-ups: Why does HTTP/2 in browsers effectively require TLS even though the HTTP/2 spec itself doesn't strictly mandate it?;How does adopting HTTP/2 change (or not change) how an Express application's route handlers are written?