typescriptadvanced

HTTP/2 Server with Stream Push

Create an HTTP/2 server with server push, multiplexed streams, and TLS configuration in Node.js.

typescript
import http2 from 'http2';
import fs from 'fs';
import path from 'path';

// For production, use real TLS certs
const server = http2.createSecureServer({
  key: fs.readFileSync('server.key'),
  cert: fs.readFileSync('server.cert'),
  allowHTTP1: true, // fallback for HTTP/1.1 clients
});

const MIME: Record<string, string> = {
  '.html': 'text/html',
  '.css': 'text/css',
  '.js': 'application/javascript',
  '.json': 'application/json',
  '.png': 'image/png',
};

server.on('stream', (stream, headers) => {
  const reqPath = headers[':path'] as string;
  const method = headers[':method'] as string;

  console.log(`${method} ${reqPath}`);

  if (reqPath === '/' || reqPath === '/index.html') {
    // Push CSS before client requests it
    stream.pushStream({ ':path': '/styles.css' }, (err, pushStream) => {
      if (!err) {
        pushStream.respond({ ':status': 200, 'content-type': 'text/css' });
        pushStream.end('body { font-family: system-ui; margin: 2rem; }');
      }
    });

    // Push JS
    stream.pushStream({ ':path': '/app.js' }, (err, pushStream) => {
      if (!err) {
        pushStream.respond({ ':status': 200, 'content-type': 'application/javascript' });
        pushStream.end('console.log("Loaded via HTTP/2 push");');
      }
    });

    // Respond with HTML
    stream.respond({ ':status': 200, 'content-type': 'text/html' });
    stream.end(`<!DOCTYPE html>
<html><head>
  <link rel="stylesheet" href="/styles.css">
  <script src="/app.js" defer></script>
</head><body>
  <h1>HTTP/2 Server Push</h1>
  <p>CSS and JS were pushed before you requested them!</p>
</body></html>`);
  } else {
    stream.respond({ ':status': 404 });
    stream.end('Not Found');
  }
});

server.listen(8443, () => {
  console.log('HTTP/2 server running on https://localhost:8443');
});

Use Cases

  • High-performance web servers
  • Asset preloading with server push
  • HTTP/2 API endpoints

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.