Defining Services and Messages in Protobuf
Author .proto contracts and generate typed interfaces for NestJS microservices.
Why Protobuf Drives the Contract
In a NestJS gRPC microservice, the .proto file is the single source of truth. It defines the wire format, the RPC surface, and — once compiled — the TypeScript types both client and server share.
- Messages describe the data shapes that travel over the wire.
- Services declare the callable RPC methods and their request/response messages.
Unlike REST + OpenAPI (where the schema is often written after the code), with gRPC you author the contract first and generate code from it. This is contract-first design.
Anatomy of a .proto File
Every contract starts by declaring the syntax version and a package. The package becomes a namespace that NestJS uses to locate your service at runtime.
syntax = "proto3";— always proto3 for modern gRPC.package billing;— the namespace referenced in the NestJS transport options.
Below is a minimal but complete contract for an invoicing service.
// proto/billing.proto
syntax = "proto3";
package billing;
service InvoiceService {
rpc GetInvoice (GetInvoiceRequest) returns (Invoice);
}
message GetInvoiceRequest {
string id = 1;
}
message Invoice {
string id = 1;
string customer_id = 2;
int64 amount_cents = 3;
string currency = 4;
}All lessons in this course
- Defining Services and Messages in Protobuf
- Implementing and Consuming gRPC Methods
- Streaming RPCs and Backpressure
- Contract Evolution and Backward Compatibility