node.jsnestjsgrpc

Create a SSL authentication on gRPC server using Nest.js


I'm trying to implement a gRPC server with SSL authentication using Nest.js following the documentation but it throws a compilation throws an error.

When I try to follow the official docs to set the server credentials like this:

{
  transport: Transport.GRPC,
  options: {
    url: `0.0.0.0:9090`,
    package: ['myProto'],
    protoPath: ['protoPath/myProto.proto'],
    credentials: grpc.ServerCredentials.createSsl(
      null,
      [
        {
          cert_chain: certChain,
          private_key: privateKey,
        },
      ],
    ),
  },
}

It just throws TypeError: Channel credentials must be a ChannelCredentials object.

I tried to ignore the docs and set a ChannelCredentials:

{
  transport: Transport.GRPC,
  options: {
    url: `0.0.0.0:9090`,
    package: ['myProto'],
    protoPath: ['protoPath/myProto.proto'],
    credentials: grpc.ChannelCredentials.createSsl(
      rootCert,
      privateKey,
      certChain,
    ),
  },
}

But then it throws TypeError: creds must be a ServerCredentials object.

The Nest interface specifies credentials as any, so it doesn't help so much.


Solution

  • I solved the problem just not following the example provided by the documentation.

    The Documentation example uses:

    const app = await NestFactory.create(AppModule);
    app.connectMicroservice<MicroserviceOptions>(grpcClientOptions);
    
    await app.startAllMicroservices();
    await app.listen(3001);
    

    Which throws the error indicated previously. Instead, I used ServerCredentials on my grpcClientOptions and then:

    const app = await NestFactory.createMicroservice(
      AppModule,
      grpcClientOptions,
    );
    app.listen();
    

    Just with this little change everything works as intended, even the server reflection.