← Back to Node.js, page 9

nodejs-0168 · Medium mid

What is gRPC, and how do you build a service in Node.js with a .proto file, a unary call and a server streaming call?

gRPC is an RPC framework that uses HTTP/2 and Protocol Buffers. You describe services and messages in a .proto file, load it in Node with @grpc/proto-loader and @grpc/grpc-js, implement handlers on the server and call generated client methods. It supports unary calls, server streaming, client streaming and bidirectional streaming, and it is compact and fast, which suits service to service traffic.

Full answer

Why gRPC

  • Contract first: the .proto file defines services, methods and typed messages. Clients and servers in different languages stay in sync, and code generation or dynamic loading removes manual parsing.
  • Protocol Buffers are a binary format, smaller and faster than JSON. Field numbers (not names) go on the wire, so you may add fields but must not reuse or change numbers.
  • HTTP/2 gives multiplexing and streaming over one connection.

Call types

  • Unary: one request, one response (like a normal function call).
  • Server streaming: one request, many responses (live updates, large result sets).
  • Client streaming: many requests, one response (uploads).
  • Bidirectional streaming: both sides stream independently (chat).

In Node

  • @grpc/proto-loader reads the .proto at run time (loadSync) and @grpc/grpc-js gives the server and client. Static code generation (grpc-tools, ts-proto, protobuf-ts) adds type safety.
  • Server: server.addService(definition, { Method: (call, callback) => ... }). For unary calls use callback(null, response). For server streaming use call.write(message) and call.end().
  • Client: new Service(address, credentials). Unary methods take (request, callback). Streams are Node Readable objects.
  • Use TLS credentials in production (createSsl), and a deadline on every call.

When not to use it: public browser APIs (browsers need grpc-web or a proxy), and simple CRUD where REST is enough.

javascript
const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'grpc-'));
const protoFile = path.join(dir, 'school.proto');
fs.writeFileSync(protoFile, `
syntax = "proto3";
package school;
service Marks {
  rpc GetStudent (StudentRequest) returns (Student);
  rpc ListMarks (StudentRequest) returns (stream Mark);
}
message StudentRequest { int32 id = 1; }
message Student { int32 id = 1; string name = 2; }
message Mark { string subject = 1; int32 score = 2; }
`);

const definition = protoLoader.loadSync(protoFile, { keepCase: true, defaults: true });
const school = grpc.loadPackageDefinition(definition).school;

const server = new grpc.Server();
server.addService(school.Marks.service, {
  GetStudent: (call, callback) => callback(null, { id: call.request.id, name: 'Asha' }),         // unary
  ListMarks: (call) => {                                                                          // server streaming
    for (const [subject, score] of [['maths', 91], ['physics', 78], ['english', 85]]) call.write({ subject, score });
    call.end();
  },
});

server.bindAsync('127.0.0.1:0', grpc.ServerCredentials.createInsecure(), (err, port) => {
  const client = new school.Marks(`127.0.0.1:${port}`, grpc.credentials.createInsecure());

  client.GetStudent({ id: 7 }, (error, student) => {
    console.log('unary response:', JSON.stringify(student));

    const stream = client.ListMarks({ id: 7 });
    const marks = [];
    stream.on('data', (mark) => marks.push(`${mark.subject}=${mark.score}`));
    stream.on('end', () => {
      console.log('streamed marks:', marks.join(', '));
      client.close();
      server.forceShutdown();
      fs.rmSync(dir, { recursive: true });
    });
  });
});

The proto file is written to a temporary folder, a server and client run in one process on a free port, and both a unary and a streaming call are made. Install first with npm install @grpc/grpc-js @grpc/proto-loader (run here with @grpc/grpc-js 1.14.7, @grpc/proto-loader 0.8.1). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): unary response: {"id":7,"name":"Asha"} streamed marks: maths=91, physics=78, english=85

Key points

  • The .proto file is the contract: services and typed messages.
  • Protocol Buffers over HTTP/2 are compact and support streaming.
  • Four call types: unary, server, client and bidirectional streaming.
  • grpc-js plus proto-loader is the usual Node setup.
  • Never change or reuse field numbers.

Common mistakes

  • Reusing or renumbering field numbers.
  • No deadline on client calls.
  • Exposing gRPC directly to browsers without grpc-web or a proxy.
  • Using insecure credentials outside local development.
  • Putting very large payloads in one message.

Follow-ups

  • How do deadlines and metadata work in gRPC?
  • What is the difference between proto2 and proto3?
  • How do you do load balancing with gRPC and HTTP/2?

Tips

  • Say 'contract first with protobuf'.
  • List the four call types.
  • Mention deadlines.