Skip to main content

APIs · Intermediate · 24 min

Build a gRPC service and client with Protocol Buffers

By Padding · Updated 18 Nov 2026
Node.js 26.13 · @grpc/grpc-js 1.14 · node:26 image

You will define a stock-price service in a .proto file, run it with @grpc/grpc-js 1.14 on Node.js 26 with a one-off call and a streaming call, handle deadlines and status codes, inspect it with grpcurl, and add a field without breaking older clients.

On this page

gRPC is a way for one program to call functions in another over the network. You describe the functions and their data in a .proto file, written in the Protocol Buffers language. Both sides load that file, so the server and every client agree on the exact shape of each request and response. Messages travel as compact binary over HTTP/2, and a single call can return a stream of messages instead of one.

That makes gRPC a strong fit for traffic between your own services. You own both ends, so the shared contract is easy to keep in step. Binary messages are smaller and cheaper to parse than the same data as JSON, which adds up on busy internal links and on metered links between regions. Streaming suits live feeds. It is a weaker fit for public APIs that browsers call directly: a browser cannot speak native gRPC, and needs gRPC-Web and a proxy in between. For that comparison in depth, see choosing between REST, GraphQL and gRPC.

In this tutorial you build a small stock-price service in Node.js 26 with @grpc/grpc-js, the official pure-JavaScript gRPC library. It has two calls. GetPrice returns one price (a unary call). WatchPrices sends a stream of price updates (a server-streaming call). The prices are made-up demo data held in memory, for three invented companies quoted in US dollars, Nigerian naira and Kenyan shillings.

Step 1 · Create the project and install the gRPC packages

Make a throwaway folder, set it up as an ES module project, and install two packages at exact versions. @grpc/grpc-js runs the server and clients. @grpc/proto-loader reads a .proto file at runtime, so you do not need a code generator:

Bash
mkdir -p ~/grpc-demo
cd ~/grpc-demo
npm init -y
npm pkg set type=module
npm install --save-exact @grpc/grpc-js@1.14.7 @grpc/proto-loader@0.8.1

Check it worked

Bash
npm ls --depth=0

The list shows @grpc/grpc-js@1.14.7 and @grpc/proto-loader@0.8.1.

Step 2 · Describe the service in a .proto file

The .proto file is the contract. Create it in its own folder, because clients in other projects will need a copy:

Bash
mkdir -p proto
cat > proto/stocks.proto <<'PROTO'
syntax = "proto3";

package stocks.v1;

service StockService {
  // One request in, one response out.
  rpc GetPrice(PriceRequest) returns (Price);
  // One request in, a stream of responses out.
  rpc WatchPrices(WatchRequest) returns (stream Price);
}

message PriceRequest {
  string symbol = 1;
}

message WatchRequest {
  string symbol = 1;
  int32 count = 2;
  int32 interval_ms = 3;
}

message Price {
  string symbol = 1;
  // Price in the smallest unit of the currency (cents, kobo), never a float.
  int64 price_minor = 2;
  int64 timestamp_ms = 3;
}
PROTO

Three things in this file matter later:

  • The numbers after each field (= 1, = 2) are field numbers. The binary format sends the number, not the name. Once a client is using a message, a field's number is permanent.
  • package stocks.v1 puts a version in the name. If you ever need a change that cannot be made compatibly, you add stocks.v2 next to it instead of breaking v1.
  • stream Price on WatchPrices is the only thing that makes it a streaming call.

Now write a small module that loads the contract. Both the server and the clients import it:

Bash
cat > load.js <<'JS'
import grpc from '@grpc/grpc-js';
import protoLoader from '@grpc/proto-loader';

export function loadStocks(file = 'proto/stocks.proto') {
  const definition = protoLoader.loadSync(file, {
    longs: Number, // int64 fields become JS numbers (exact below 2^53)
    defaults: true, // fields the sender left out get their zero value
  });
  return grpc.loadPackageDefinition(definition).stocks.v1;
}
JS

proto-loader turns snake_case field names into camelCase for JavaScript, so price_minor becomes priceMinor in your code. On the wire nothing changes, because only the numbers are sent.

Check it worked

Load the file and list the methods it defines:

Bash
node --input-type=module -e "import { loadStocks } from './load.js'; console.log(Object.keys(loadStocks().StockService.service));"

The output is [ 'GetPrice', 'WatchPrices' ]. A typo in the .proto file shows up here as a parse error with a line number.

Step 3 · Implement the server

Keep the code that builds a Price message in its own small file. You will change only this file when the message gains a field:

Bash
cat > price.js <<'JS'
// Builds a Price message from a stock record.
export function toPrice(symbol, stock) {
  return { symbol, priceMinor: stock.priceMinor, timestampMs: Date.now() };
}
JS

Now the server. Each handler either answers or fails with a gRPC status code. INVALID_ARGUMENT means the caller sent something wrong and should not retry it unchanged. NOT_FOUND means the request was fine but the thing does not exist:

Bash
cat > server.js <<'JS'
import grpc from '@grpc/grpc-js';
import { loadStocks } from './load.js';
import { toPrice } from './price.js';

const { StockService } = loadStocks();

// Made-up demo data. Prices are in minor units (cents, kobo).
const stocks = new Map([
  ['ACME', { priceMinor: 12550, currency: 'USD' }],
  ['KOLA', { priceMinor: 4210, currency: 'NGN' }],
  ['BAOBAB', { priceMinor: 98000, currency: 'KES' }],
]);

function find(symbol) {
  if (!symbol) {
    return { error: { code: grpc.status.INVALID_ARGUMENT, details: 'symbol is required' } };
  }
  const key = symbol.toUpperCase();
  const stock = stocks.get(key);
  if (!stock) {
    return { error: { code: grpc.status.NOT_FOUND, details: `no stock called ${key}` } };
  }
  return { key, stock };
}

function getPrice(call, callback) {
  const { error, key, stock } = find(call.request.symbol);
  if (error) {
    callback(error);
    return;
  }
  callback(null, toPrice(key, stock));
}

function watchPrices(call) {
  const { error, key, stock } = find(call.request.symbol);
  const count = call.request.count || 5;
  const intervalMs = Math.max(call.request.intervalMs || 500, 100);
  if (error) {
    call.emit('error', error);
    return;
  }
  if (count > 100) {
    call.emit('error', { code: grpc.status.INVALID_ARGUMENT, details: 'count must be 100 or less' });
    return;
  }

  let sent = 0;
  const timer = setInterval(() => {
    // Move the price a little so the stream shows change.
    stock.priceMinor = Math.max(1, stock.priceMinor + Math.round((Math.random() - 0.5) * 50));
    call.write(toPrice(key, stock));
    sent += 1;
    if (sent === count) {
      clearInterval(timer);
      call.end();
    }
  }, intervalMs);

  // The client hung up or its deadline passed: stop sending.
  call.on('cancelled', () => {
    clearInterval(timer);
    console.log(`watch for ${key} cancelled`);
  });
}

const server = new grpc.Server();
server.addService(StockService.service, { GetPrice: getPrice, WatchPrices: watchPrices });

const address = '127.0.0.1:50051';
server.bindAsync(address, grpc.ServerCredentials.createInsecure(), (err) => {
  if (err) {
    console.error(err.message);
    process.exit(1);
  }
  console.log(`StockService listening on ${address}`);
});

for (const signal of ['SIGINT', 'SIGTERM']) {
  process.on(signal, () => server.tryShutdown(() => process.exit(0)));
}
JS

A unary handler gets the request as call.request and answers once through callback. A streaming handler gets a writable call: it calls write for each message and end when it is done. Notice that the stock records hold a currency, but the Price message has no field for it yet, so toPrice leaves it out.

The server listens on 127.0.0.1 only, without encryption (createInsecure). That is fine for one machine. Between machines, use grpc.ServerCredentials.createSsl with a certificate, or keep the traffic inside a private network behind a TLS-terminating proxy.

Start the server in your second terminal, from ~/grpc-demo, and leave it running:

Bash
cd ~/grpc-demo
node server.js

Check it worked

The second terminal prints StockService listening on 127.0.0.1:50051 and stays open. If it prints No address added out of total 1 resolved or a message about the address being in use, another program has port 50051. Stop it, or change the port in server.js and in the clients you write next.

Step 4 · Call the service from a client

Back in your first terminal, write a client for GetPrice. It sets a deadline: the latest time by which it wants an answer. Without one, a call to a stuck server can wait forever. Every gRPC call in production code should have a deadline:

Bash
cd ~/grpc-demo
cat > get.js <<'JS'
import grpc from '@grpc/grpc-js';
import { loadStocks } from './load.js';

const { StockService } = loadStocks(process.env.PROTO_FILE);
const client = new StockService('127.0.0.1:50051', grpc.credentials.createInsecure());

const symbol = process.argv[2] ?? 'ACME';
const deadline = new Date(Date.now() + 2000);

client.getPrice({ symbol }, { deadline }, (err, price) => {
  if (err) {
    console.log(`error ${grpc.status[err.code]}: ${err.details}`);
  } else {
    const amount = (price.priceMinor / 100).toFixed(2);
    console.log([price.symbol, amount, price.currency].filter(Boolean).join(' '));
  }
  client.close();
});
JS
node get.js ACME
node get.js nope
node get.js ""

The client object has a method for each call in the contract, in camelCase (getPrice for GetPrice). On failure, err.code is a number, and grpc.status[err.code] turns it back into its name. The last line of the console.log prints a currency when the message has one. It has none yet.

Check it worked

The three commands print:

  • ACME 125.50
  • error NOT_FOUND: no stock called NOPE
  • error INVALID_ARGUMENT: symbol is required

Step 5 · Stream prices and stop at a deadline

A streaming call returns a readable stream. Each message arrives as a data event. When the call finishes, a status event reports how it ended, and a failure also raises an error event:

Bash
cat > watch.js <<'JS'
import grpc from '@grpc/grpc-js';
import { loadStocks } from './load.js';

const { StockService } = loadStocks(process.env.PROTO_FILE);
const client = new StockService('127.0.0.1:50051', grpc.credentials.createInsecure());

const symbol = process.argv[2] ?? 'ACME';
const count = Number(process.argv[3] ?? 5);
const timeoutMs = Number(process.argv[4] ?? 10000);
const deadline = new Date(Date.now() + timeoutMs);

const call = client.watchPrices({ symbol, count, intervalMs: 300 }, { deadline });

call.on('data', (price) => {
  const time = new Date(price.timestampMs).toISOString().slice(11, 19);
  console.log(`${time} ${price.symbol} ${(price.priceMinor / 100).toFixed(2)}`);
});
call.on('error', (err) => {
  console.log(`error ${grpc.status[err.code]}: ${err.details}`);
});
call.on('status', (status) => {
  if (status.code === grpc.status.OK) {
    console.log('stream complete');
  }
  client.close();
});
JS
node watch.js ACME 5

Five updates arrive about 0.3 seconds apart, then the stream ends. Now ask for 20 updates, which takes about six seconds, but give the call a deadline of one second:

Bash
node watch.js ACME 20 1000

The client prints the updates that arrive in time, then gives up with DEADLINE_EXCEEDED. The deadline travels to the server with the call, so the server knows too: its cancelled handler runs and the timer stops. A server that ignores cancellation keeps working for a caller that has already left.

Check it worked

The first command prints five lines such as 14:02:07 ACME 125.41, with prices that move a little each time, and then stream complete. The second prints about three price lines and then error DEADLINE_EXCEEDED: Deadline exceeded (the exact wording after the code can vary between versions). The server terminal shows watch for ACME cancelled.

Step 6 · Inspect calls with grpcurl

grpcurl is to gRPC what curl is to HTTP: it sends a call from the command line and prints the reply as JSON. It is a single binary. On macOS, install it with brew install grpcurl. On Linux, download the release for your processor, check it against the published checksum, and install it:

Bash
GRPCURL_VERSION=1.9.4
case "$(uname -m)" in
  x86_64) GRPCURL_ARCH=x86_64 ;;
  aarch64 | arm64) GRPCURL_ARCH=arm64 ;;
  *) echo "No grpcurl build for $(uname -m) in this guide"; false ;;
esac
GRPCURL_FILE="grpcurl_${GRPCURL_VERSION}_linux_${GRPCURL_ARCH}.tar.gz"
cd "$(mktemp -d)"
curl -fsSLO "https://github.com/fullstorydev/grpcurl/releases/download/v${GRPCURL_VERSION}/${GRPCURL_FILE}"
curl -fsSLO "https://github.com/fullstorydev/grpcurl/releases/download/v${GRPCURL_VERSION}/grpcurl_${GRPCURL_VERSION}_checksums.txt"
grep " ${GRPCURL_FILE}\$" "grpcurl_${GRPCURL_VERSION}_checksums.txt" | sha256sum -c -
tar -xzf "$GRPCURL_FILE" grpcurl
sudo install -m 755 grpcurl /usr/local/bin/grpcurl
cd ~/grpc-demo
grpcurl -version

sha256sum prints OK for the file. A binary installed by hand gets no updates from your package manager: to upgrade, run the same commands with a newer GRPCURL_VERSION from the grpcurl releases page.

Your server does not advertise its contract over the network (that needs the optional reflection service), so point grpcurl at the .proto file. Listing and describing work without a server:

Bash
grpcurl -import-path proto -proto stocks.proto list
grpcurl -import-path proto -proto stocks.proto describe stocks.v1.Price

Now make real calls. -plaintext matches the server's unencrypted port, and -d gives the request as JSON:

Bash
grpcurl -plaintext -import-path proto -proto stocks.proto \
  -d '{"symbol": "KOLA"}' 127.0.0.1:50051 stocks.v1.StockService/GetPrice
grpcurl -plaintext -import-path proto -proto stocks.proto \
  -d '{"symbol": "BAOBAB", "count": 3, "interval_ms": 200}' 127.0.0.1:50051 stocks.v1.StockService/WatchPrices

Then a call that fails:

Bash
grpcurl -plaintext -import-path proto -proto stocks.proto \
  -d '{"symbol": "NOPE"}' 127.0.0.1:50051 stocks.v1.StockService/GetPrice

Check it worked

list prints stocks.v1.StockService, and describe prints the Price message with its three fields and numbers. The GetPrice call prints something like this. Note that the int64 fields are quoted: the JSON form of Protocol Buffers writes 64-bit integers as strings, because JavaScript numbers cannot hold every 64-bit value.

JSON
{
  "symbol": "KOLA",
  "priceMinor": "4210",
  "timestampMs": "1795612345678"
}

The WatchPrices call prints three such objects, one per update. The failing call prints Code: NotFound and Message: no stock called NOPE, and grpcurl exits with a non-zero code, so scripts can detect it.

Step 7 · Add a field without breaking old clients

Clients built against today's contract will keep running after you change it, often for months. Protocol Buffers is designed so that a message can grow safely, provided you follow its rules. Add a currency field to Price with a new, unused number.

First, keep a copy of the current contract. It stands in for an older client that was deployed before the change and still has the old file:

Bash
cd ~/grpc-demo
mkdir -p old
cp proto/stocks.proto old/stocks.proto

Now write the new contract. Only the Price message changes:

Bash
cat > proto/stocks.proto <<'PROTO'
syntax = "proto3";

package stocks.v1;

service StockService {
  // One request in, one response out.
  rpc GetPrice(PriceRequest) returns (Price);
  // One request in, a stream of responses out.
  rpc WatchPrices(WatchRequest) returns (stream Price);
}

message PriceRequest {
  string symbol = 1;
}

message WatchRequest {
  string symbol = 1;
  int32 count = 2;
  int32 interval_ms = 3;
}

message Price {
  string symbol = 1;
  // Price in the smallest unit of the currency (cents, kobo), never a float.
  int64 price_minor = 2;
  int64 timestamp_ms = 3;
  // Added later. A new number, never one that was used before.
  string currency = 4;
}
PROTO
cat > price.js <<'JS'
// Builds a Price message from a stock record.
export function toPrice(symbol, stock) {
  return { symbol, priceMinor: stock.priceMinor, timestampMs: Date.now(), currency: stock.currency };
}
JS

Restart the server so it loads the new contract: press Ctrl+C in the second terminal, then run it again:

Bash
node server.js

Call it with the new contract, then with the old copy:

Bash
node get.js KOLA
PROTO_FILE=old/stocks.proto node get.js KOLA

The new client reads field 4 and prints the currency. The old client receives the same bytes, finds a field number its contract does not know, and skips it. It does not fail.

It works in the other direction too. A new client talking to a server that has not been upgraded gets no field 4, so currency holds its default, an empty string. Your code must treat that empty value as "not known".

The rules that keep changes safe:

  • Add fields with new numbers. Never reuse a number, and never change a field's number or type.
  • When you remove a field, reserve its number and name so nobody reuses them by accident:
Text
message Price {
  reserved 3;
  reserved "timestamp_ms";
  string symbol = 1;
  int64 price_minor = 2;
  string currency = 4;
}
  • Renaming a field does not break the binary format, but it does change the JSON form that grpcurl and gRPC gateways use, so treat a rename as a breaking change.
  • For a change that cannot follow these rules, publish a stocks.v2 package and run both while clients move over.

Check it worked

The first command prints KOLA 42.10 NGN. The second prints KOLA 42.10, with no currency and no error.

Step 8 · Stop the server and clean up

Stop the server with Ctrl+C in the second terminal. tryShutdown lets calls in progress finish before the process exits.

Call the service once more, now that nothing is listening:

Bash
cd ~/grpc-demo
node get.js ACME

Then remove the project and grpcurl. Node.js stays installed:

Bash
cd ~
rm -rf ~/grpc-demo
sudo rm -f /usr/local/bin/grpcurl

On macOS, if you installed grpcurl with Homebrew, run brew uninstall grpcurl instead of the last line.

Check it worked

The last call prints a line that starts with error UNAVAILABLE: and goes on to say that no connection could be made. UNAVAILABLE is the status code clients usually retry, with a short wait between tries, because the server may come back. After the clean-up, ls ~/grpc-demo reports that there is no such directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.