Search code examples
loopbackjsloopback4

how to use http2 in loopback 4 application?


We are planning to implement http2 in a loopback 4 application. We had used http, socket servers but never http2.

What is the procedure to use http2 in my application?


Solution

  • Here's what you have to do in your existing app:

    Step 1: Install spdy

    npm i spdy
    

    Step 2: Configure index.ts

    Change your main function in src/index.ts with this:

    import spdy from "spdy";
    
    export async function main(options: ApplicationConfig = {}) {
      
      // specify cert and key file paths for SSL
      const serverOptions: spdy.ServerOptions = {
        key: fs.readFileSync(
          path.join(__dirname, '..', 'keys', 'localhost-privkey.pem'),
        ),
        cert: fs.readFileSync(
          path.join(__dirname, '..', 'keys', 'localhost-cert.pem'),
        ),
      };
    
      // setting listenOnStart to false will not start the default httpServer
      options.rest.listenOnStart = false;
    
      // Replace YourApplication with your class
      const app = new YourApplication(options);
      await app.boot();
      await app.start();
    
      // create server
      const server = spdy.createServer(serverOptions, app.requestHandler);
    
      // to avoid process exit on warnings
      server.on('warning', console.warn);
    
      server.listen(3000, () => {
        console.log('Listening on https://localhost:3000/');
      });
    
      return app;
    }
    

    All we're doing in the above code is, preventing the default http server from being started and starting the server using spdy with loopback's request handler app.requestHandler that will be used for all incoming request.

    Check out this pastebin containing entire index.ts file content after the changes.

    To generate certificate and keys for localhost use:

    openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \
      -keyout localhost-privkey.pem -out localhost-cert.pem
    

    You may need to allow self-signed certificates in Chrome as well for /explorer to work as expected.

    And that's it, you can now run your app, and enjoy the power of http2 :)

    Blog Post: https://shubham-web.medium.com/how-to-use-http2-in-loopback-4-applications-5e83881c7b38