Websites delivered using HTTP/2 enjoys a wide range of new features including -
fully multiplexed connections: all requests and responses to a domain are fully multiplexed via a single connection, making best use of available bandwidth.
header compression: repeated headers are compressed with HPACK compression so that they are not resent with every request and response.
PUSH: resources can be pre-emptively pushed by the server to the client, speeding up page load times.
Node.js just launched support(v8.8.1) for HTTP/2 as part of their core. In this post, we will create a simple HTTP/2 server to serve static files and then demonstrate some cool features like HTTP/2 PUSH.
Get an SSL certificate
Even though the HTTP/2 spec does not mandate HTTPS, browsers have decided that they will only support HTTP/2 on a HTTPS connection. This would also mitigate interference from older proxies which may not understand newer protocol.
For your local server, a self-signed certificate will work. You can find how to setup a self-signed certificate here
Building a Static File Server
Let us start with a simple server which just serves static files. Note that if you are using node.js 8.7.0, you need to run node with the --expose-http2 flag.
We will be listening to the stream event and responding to it with the corresponding file from the server root(public, in this case) using the respondWithFile API. We are using the mime-type module to look up the correct mime type to send along with the response.
Now we have simpel HTTP/2 server running, lets try to use one of the new featues in HTTP/2 - HTTP/2 PUSH. This can lead to significant performance improvements in high latency environments, if done correctly.
We are loading a simple HTML file pointing to style.css which references to our font file. The request to the font file is only made after css file is discovered in the HTML, downloaded and then parsed. This is how the waterfall would have usually looked like:
You can initate a new PUSH with the pushStream API. Since we know that the browser is going to be requesting the font file in the future, we can PUSH the font file as soon as the server receives the request for the HTML file.
When the actual request for the font file takes place, it is claimed from the PUSH cache, instead of making a network request then.