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

1

9

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.

Sepulcher answered 10/5, 2018 at 13:36 Comment(1)
I don’t know the answer to your question but as an alternative why not just through a webserver (e.g. Apache or Nginx) in front of it and keep Node on HTTP/1.1 until HTTP/2 is better supported on it? To be honest having a webserver in front for static resources is usually better anyway.Crocodile
A
15

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.

Apoplectic answered 21/11, 2020 at 0:7 Comment(1)
What are the .key and .crt file?Feigned

© 2022 - 2024 — McMap. All rights reserved.