Http2 server implementation for Nodejs

Posted By : Sakshi Gadia | 22-Jan-2018

Why HTTP/2?

The HTTP/1 disadvantage is that as browser parses responses and fetch its assets, a user has to wait, these delay in rendering and fetching will increase browser load times.

Node.js 8.4.0 has come with the experimental support of HTTP/2. HTTP/2 major goal is to reduce latency, it allows multiplexing, stream priority, server push, header compression.

 

Benefits of HTTP/2

  1. Multiplexing: Browsers can send multiple requests during a single TCP(transmission control protocol) connection so that it successively allows browsers to request all the assets in parallel.
  2. Stream priority: Specify the priority of assets to browsers. For example, the browser can request HTML first to render it before any styles or JavaScript.
  3. Server push: Servers can push web assets (CSS, JS, images) before a browser is aware of it wants them that hurries up page load times by reducing the number of requests.
  4. Header compression: All HTTP/1.1 requests have to be compelled to have headers which are generally duplicate the same info, whereas H2 forces all HTTP headers to be sent during a compressed format, it reduced data redundancy.
  5. De facto mandatory encryption: Although the encryption isn't needed, most major browsers implement H2 only over TLS (HTTPS).

Installation

It can be accessed by:

const http2 = require('http2');

 

Sample Node Server:

You can create a sample of self-signed SSL certificate or get a valid SSL from authorized SSL providers.

$ openssl req -x509 -nodes -newkey rsa:2048 -keyout example.com.key -out example.com.crt

 

Server-side example

The following illustrates a plain-text HTTP/2 server using the Core API:

const http2 = require('http2');
const fs = require('fs');

const server = http2.createSecureServer({
 key: fs.readFileSync('localhost-privkey.pem'),
 cert: fs.readFileSync('localhost-cert.pem')
});

server.on('error', (err) => console.error(err));
server.on('socketError', (err) => console.error(err));

server.on('stream', (stream, headers) => {
 // stream is a Duplex
 stream.respond({
   'content-type': 'text/html',
   ':status': 200
 });
 stream.end('<h1>Hello World</h1>');
});

server.listen(8084);

 

Example of server push

HTTP/2 Server Push allows the server to send assets to the browser before any request has been coming for them whereas in HTTP/1 the client sends a request to the server, that replies with the requested content, sometimes with an HTML file that contains links to several assets (.js, .css, etc. files). As browser processes this primary HTML file, it starts to resolve these links and makes separate requests to fetch them. The interesting part is that we have a tendency to push different resources once the index.html is requested:

 
const http2 = require('http2')
const server = http2.createSecureServer(
  { cert, key },
  onRequest
)

function push (stream, filePath) {
  const { file, headers } = getFile(filePath)
  const pushHeaders = { [HTTP2_HEADER_PATH]: filePath }

  stream.pushStream(pushHeaders, (pushStream) => {
    pushStream.respondWithFD(file, headers)
  })
}

function onRequest (req, res) {
  // Push files with index.html
  if (reqPath === '/index.html') {
    push(res.stream, 'bundle1.js')
    push(res.stream, 'bundle2.js')
  }

  // Serve file
  res.stream.respondWithFD(file.fileDescriptor, file.headers)
}

 

Note:

Express does not support HTTP/2 yet. Spdy provides Node developers an easy way to enable pushes in your Express app. You can go to the link

 

About Author

Author Image
Sakshi Gadia

An experienced MEAN Stack developer having good knowledge in Nodejs, MongoDb. Apart from these in my spare time, I enjoy playing chess and ready to learn new technologies.

Request for Proposal

Name is required

Comment is required

Sending message..