HTTP2: Server Push (Node.js)

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!