typescriptadvanced
HTTP/2 Server with Stream Push
Create an HTTP/2 server with server push, multiplexed streams, and TLS configuration in Node.js.
typescriptPress ⌘/Ctrl + Shift + C to copy
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.
typescriptadvanced
Node.js Worker Threads for Parallel Processing
Use Worker Threads to run CPU-intensive tasks in parallel without blocking the event loop.
Best for: CPU-intensive data processing without blocking
#nodejs#worker-threads
typescriptadvanced
Node.js Cluster Mode for Scaling
Scale Node.js across CPU cores using the cluster module with automatic worker respawning.
Best for: Utilizing all CPU cores for HTTP servers
#nodejs#cluster
typescriptadvanced
Performance Measurement
Measure execution time with performance.now(), Performance API marks, measures, and PerformanceObserver.
Best for: Function execution profiling
#nodejs#performance
typescriptintermediate
In-Memory Caching with LRU Strategy
Implement LRU cache with TTL expiration, size limits, and cache-aside pattern for Node.js applications.
Best for: API response caching
#nodejs#caching