Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use HTTP/2 with Nest.js (Node)

I have read that Express 4.x is not compatible with Node.js native HTTP2 (from 8.4+), and I was hoping for more progess on Express 5.x than it has. But as I started thinking that Express5.x will probably be released to late for my next Node.js project - I came over Nest.js.

Does anyone know if Nest.js can be used with native HTTP2 support ??

The only Node.js framework that I have heard of that supports this is Fastify. Or are there any other out there ? Preferable one that support Express plugins.

like image 311
iToreTS Avatar asked May 10 '18 13:05

iToreTS


1 Answers

You can use HTTP/2 (and SPDY) in NestJS using the node-spdy package:

Setup packages

yarn add spdy
yarn add -D @types/spdy

Generate certificate

H2 generally requires TLS, so generate a new key and certificate:

openssl req -x509 -newkey rsa:2048 -nodes -sha256 -keyout test.key -out test.crt

Modify startup

Next, modify main.ts:

// main.ts
async function bootstrap() {

  const expressApp: Express = express();

  const spdyOpts: ServerOptions = {
    key: fs.readFileSync('./test.key'),
    cert: fs.readFileSync('./test.crt'),
  };

  const server: Server = spdy.createServer(spdyOpts, expressApp);

  const app: NestApplication = await NestFactory.create(
    AppModule,
    new ExpressAdapter(expressApp),
  );
  
  await app.init();
  await server.listen(3000);
}

bootstrap();

Test client

$ curl -I -k https://localhost:3000/
HTTP/2 200 
x-powered-by: Express
content-type: text/html; charset=utf-8
content-length: 12
etag: W/"c-Lve95gjOVATpfV8EL5X4nxwjKHE"

Notice HTTP/2 being sent in the response headers.

like image 113
Jeffrey Mixon Avatar answered Oct 07 '22 08:10

Jeffrey Mixon