HTTP2: Server Push (Node.js)

Fahim shares an HTTP2 optimization technique using Node.js and the http2 module. This method involves pushing additional resources (like JavaScript files) alongside the initial request for `index.html`, allowing them to start downloading sooner. The provided code demonstrates how to push specific files based on the requested URL, with potential for further refactoring or integration with a router like Koa/Express for dynamic resource handling. This approach can significantly speed up application load times for users.
generated by granite3.2:8b

To learn more about HTTP2, I found this diagram by @kosamari that is super easy to digest.

Let’s see how we can take advantage of this and reduce the time it takes to load the application for the user.

In the following example when index.html is requested, we can push other resources alongside it. This way the file1.js, file2.js and file3.js assets will be sent to the browser even before index.html file requests them.

const http2 = require("http2");
const server = http2.createServer({ OPTIONS }, handleRequest);
function pushFile(stream, fileName) {
// ... get the file and its headers with file reader
// then push it down the stream
stream.pushStream({ [HTTP2_HEADER_PATH]: fileName }, (pstream) =>
pstream.respondWithFD(file, headers)
);
}
function handleRequest(req, res) {
if (req.url == "/index.html" || req.url == "/") {
// Pushing files depending on req.url
pushFile(res.stream, "file1.js");
pushFile(res.stream, "file2.js");
pushFile(res.stream, "file3.js");
// Proceed serving index.html
}
if (req.url == "/app2.html") {
pushFile(res.stream, "file4.js");
pushFile(res.stream, "file5.js");
// serve app2.html
}
}

We can refactor this code in so many ways + having a router with koa/express can make it more dynamic.

Good luck in your HTTP2 journey!