From .proto to a typed TypeScript client
TL;DR
This post follows one Taproot feature from its written definition all the way to the screen that uses it.
Most of the code that connects the server and the browser is generated by tools instead of written by hand, so the two sides always match.
Automatic checks regenerate that code and compare it with what's saved, so mismatches get caught before they ship.
The trade-off is upkeep: four code generators to keep current, and a big generated description of the system (about 45,000 lines) to review when it changes.
Why I generate the TypeScript clients
Generating TypeScript clients ensures they match what is on the server. Including that generation step along with the tests also creates another opportunity to write tests that enforce the contract.
Those tests give AI tooling another place to check whether things were done correctly, and I have found that forcing AI to ask questions about the quality of the work increases said quality.
Why we start every API change with a shared contract, and when that's worth it, is in contract-first development and when it pays off. This post is the hands-on part: one real endpoint, followed from the .proto file to the browser component that calls it, with the actual config, commands and checks.
The endpoint is GetPendingLegalAcceptances. Before someone signs up, buys a plan or publishes a membership product, Taproot asks the API which legal documents they still need to accept. It's a normal read with a few optional inputs, which makes it a good one to trace.

Here's the chain we'll follow:
protos/Legal.proto
├─► C# service base class (Grpc.Tools)
│ └─► REST endpoint (gRPC JSON transcoding)
│ └─► OpenAPI document ─► committed snapshot ─► browser SDK (Hey API)
└─► TypeScript gRPC clients for Node services (ts-proto + nice-grpc)Why generate the whole stack from one contract?
Taproot's backend is a .NET API that speaks gRPC. The static site generator, image processor and server-side rendering layer are Node services that call it over gRPC too, while the browser calls the same API over HTTP and JSON. That's one contract serving two transports and two languages.
You could handle each half separately, with gRPC between services and a handwritten REST API for the browser, or start from OpenAPI and skip protobuf. Microsoft's docs present JSON transcoding and gRPC-Web (opens in a new tab) as two answers to the browser problem. We wanted one place to define a request, at the price of a longer chain with more links that can drift. That's why the last step is all checks.
Step 1: write the contract
Everything starts in protos/, which holds 37 first-party .proto files. The Legal service has a public RPC and an internal one:
service Legal {
rpc GetPendingLegalAcceptances(GetPendingLegalAcceptancesRequest)
returns (GetPendingLegalAcceptancesResponse) {
option (google.api.http) = {get: "/v1/legal/acceptances/pending"};
}
// Internal: gRPC only, with no REST mapping.
// Internal-only: returns the published/superseded version index ...
// Omits google.api.http so it is not transcoded to REST.
rpc GetLegalDocumentSnapshots(GetLegalDocumentSnapshotsRequest)
returns (GetLegalDocumentSnapshotsResponse) {}
}The google.api.http option is an HTTP rule (opens in a new tab) from Google's API annotations that maps an HTTP request onto the RPC. Every public RPC gets one with a path under /v1/. Internal RPCs leave it off so they never become REST endpoints, and an architecture test makes them start their comment with // Internal:, so dropping a rule by accident fails the tests. GetLegalDocumentSnapshots exists only for the site generator, so the browser has no route to it.
The request message carries a flow plus a few optional nested messages, such as the account plan someone is signing up for:
message GetPendingLegalAcceptancesRequest {
LegalAcceptanceFlow flow = 1;
AccountPlanLegalOffering account_plan = 2;
MembershipProductLegalOffering membership_product = 3;
CreatorMerchantLegalOffering creator_merchant = 4;
// ...
}We lint the contracts with buf lint in CI. Code generation uses protoc, through the tools below.
Step 2: generate the C# service base class
On the API side, Grpc.Tools (opens in a new tab) generates C# from the protos at build time. One item in the project file covers every contract:
<Protobuf ProtoRoot="../../../protos" Include="../../../protos/*.proto"
GrpcServices="Server" />
<!-- Image-processor is an internal gRPC service we call as a client -->
<Protobuf Update="../../../protos/ImageProcessor.proto" GrpcServices="Client" />The ProtoRoot points outside the project, at the shared folder. That only works because the API, the frontend and the Node services live in one repository, which I wrote about in moving Taproot to a monorepo.
The build produces a Legal.LegalBase class with a virtual method per RPC, and we write the implementation:
public sealed class LegalService(/* dependencies */) : Legal.LegalBase
{
[OpenApiOperation("GetPendingLegalAcceptances")]
public override async Task<GetPendingLegalAcceptancesResponse> GetPendingLegalAcceptances(
GetPendingLegalAcceptancesRequest request,
ServerCallContext context)
{
// validation, authorization and the actual lookup
}
}Ignore the attribute for now. It comes back in step 4.
Step 3: expose it as REST with gRPC JSON transcoding
gRPC JSON transcoding (opens in a new tab) (Microsoft.AspNetCore.Grpc.JsonTranscoding) reads those HTTP rules and serves each annotated RPC as a JSON endpoint inside the same ASP.NET Core app, with no separate gateway process. Registration in Program.cs looks like this:
builder.Services.AddGrpc(options => { /* message size limits, interceptors */ })
.AddJsonTranscoding(options =>
{
options.TypeRegistry = TypeRegistry.FromFiles(
ErrorDetailsReflection.Descriptor, // gRPC's built-in error detail types
TypeReflection.Descriptor);
});
app.UsePathBase(new PathString("/api"));
app.MapGrpcService<LegalService>();The type registry lets transcoding serialize the error details our services attach to failed calls, so the browser gets more than a bare status code.
A GET has no body, so the fields that aren't in the path become query parameters, and nested fields use dotted names (opens in a new tab). The account_plan message above turns into accountPlan.planTier and accountPlan.billingCadence in the query string, with no routing code of our own.
Step 4: produce an OpenAPI document with stable operation IDs
The browser SDK is generated from an OpenAPI document, so the API has to describe its transcoded endpoints. We use ASP.NET Core's built-in generator, Microsoft.AspNetCore.OpenApi, plus a gRPC integration kept in our own repository, because Microsoft no longer ships one (more under costs):
// Program.cs
builder.Services.AddTaprootOpenApi(Path.Combine(System.AppContext.BaseDirectory, "taproot-api.xml"));
app.MapOpenApi("/openapi/{documentName}.json");
// TaprootOpenApiServiceExtensions.cs (trimmed)
services.AddGrpcOpenApi(DocumentName); // the vendored gRPC integration
services.Configure<OpenApiOptions>(DocumentName, options =>
{
options.OpenApiVersion = OpenApiSpecVersion.OpenApi3_0;
options.AddOperationTransformer(new OpenApiOperationIdTransformer());
options.IncludeGrpcXmlComments(xmlDocumentationPath, includeControllerXmlComments: true);
// ...
});OpenApiOperationIdTransformer copies the value of our [OpenApiOperation] attribute onto each operation. The document stays on OpenAPI 3.0 instead of .NET 10's default of 3.1, so the generated client diff stays reviewable.
The operation ID matters because Hey API's SDK plugin builds function names from (opens in a new tab)operationId (opens in a new tab). Whatever the document says becomes the name every developer, and every AI tool, types. That's how the browser gets getPendingLegalAcceptances and not a name derived from the route.
IncludeGrpcXmlComments carries the comments from the .proto file into the document, so the summary on the endpoint is the same sentence a developer reads in the contract. Scalar (opens in a new tab) renders the same document as our API reference.
As of October 2026 the document has 467 operations, and an architecture test fails if a public RPC's implementation lacks the attribute. The one operation without our ID is an image upload endpoint on a plain ASP.NET Core controller, which the test doesn't cover. Its SDK function is putV1ImagesUploadsByUploadIdContent, which is what you get when nobody picks a name.
Step 5: snapshot the document and commit it
The client generator doesn't read the live API. It reads a copy of the OpenAPI document that we commit to the repository. One npm script refreshes it from the running local stack:
cd ux
npm run snapshot-openapi # fetch /api/openapi/v1.json, pretty-print, format with dprint
npm run generate-open-api-clientsThe snapshot lets you generate clients, and lets CI type-check against them, without starting the API, its database and the rest of the local Kubernetes stack. An API change also shows up in the pull request as a readable JSON diff next to the code that caused it.
For our endpoint, the snapshot contains the path, the dotted query parameters and the operation ID:
"/v1/legal/acceptances/pending": {
"get": {
"tags": ["Legal"],
"operationId": "GetPendingLegalAcceptances",
"parameters": [
{ "name": "flow", "in": "query", "schema": { "$ref": "#/components/schemas/LegalAcceptanceFlow" } },
{ "name": "accountPlan.planTier", "in": "query", "schema": { "type": "string" } }
]
}
}The internal GetLegalDocumentSnapshots RPC isn't in there at all, which is the HTTP rule convention doing its job.
Step 6: generate the browser SDK with Hey API
Hey API (opens in a new tab) (@hey-api/openapi-ts) turns the snapshot into TypeScript types and one function per operation. This is the whole config:
export default defineConfig({
input: "./openapi/v1.json",
output: {
path: path.resolve(configDir, "generated/api"),
importFileExtension: ".js",
},
plugins: [
"@hey-api/typescript",
{ name: "@hey-api/client-fetch", baseUrl: "/api" },
"@hey-api/sdk",
],
});The generated sdk.gen.ts has a function for our endpoint, and the code that decides whether to show the legal acceptance gate imports it like any other module:
import { getPendingLegalAcceptances } from "../generated/api/sdk.gen.js";
const result = await getPendingLegalAcceptances({
query: {
flow: options.flow,
"accountPlan.planTier": options.accountPlan.planTier,
"accountPlan.billingCadence": options.accountPlan.billingCadence,
},
});That function knows the path, the HTTP method and the query parameter types. If someone renames a field in Legal.proto, the next regeneration changes the types and the TypeScript compiler points at this call.
The generated folders are gitignored. Only the snapshot is committed, and the build, test, lint and typecheck scripts all regenerate the SDK before they run. Lint also fails on a raw fetch() call in the client unless it carries a taproot-allow-raw-fetch marker, so normal API calls go through the SDK.
Step 7: generate Node gRPC clients with ts-proto and nice-grpc
The Node services skip HTTP. They call the API over gRPC, with clients generated by ts-proto (opens in a new tab) and run on nice-grpc (opens in a new tab). The generator's generate-grpc-clients script runs protoc (from the grpc-tools npm package) with these options:
grpc_tools_node_protoc \
--plugin=protoc-gen-ts_proto=./node_modules/.bin/protoc-gen-ts_proto \
--ts_proto_out=./src/grpc-generated \
--ts_proto_opt=esModuleInterop=true \
--ts_proto_opt=importSuffix=.js \
--ts_proto_opt=outputServices=nice-grpc \
--ts_proto_opt=outputServices=generic-definitions \
--ts_proto_opt=useExactTypes=false \
--proto_path=../protos ../protos/*.protooutputServices=nice-grpc and generic-definitions go together (the ts-proto README says so) and produce a service definition nice-grpc can turn into a client. importSuffix=.js adds the extension ES modules need, and useExactTypes=false relaxes exact-type checking on the generated create and fromPartial helpers.
The site generator uses the internal RPC that the browser can't reach:
export const legalClient = createClient(LegalDefinition, channel);
const response = await legalClient.getLegalDocumentSnapshots(
{ pageId: pageIds },
{ metadata: internalMetadata() },
);The image processor generates only its own contract, and the frontend's Fastify server generates clients for server-side rendering. Same command, different output folders.
Step 8: check every link for drift
Each generator reproduces whatever input it gets, stale or not, so each link has its own check. The general idea is in how we enforce coding standards; here's what each check compares.
A script called check-generated-artifacts.sh regenerates the browser SDK and the generator and image processor gRPC clients into temporary folders, then runs diff -qr against the working tree. That proves the generated TypeScript matches its inputs.
That doesn't prove the snapshot matches the API. An August 2026 review of our guard rails caught that gap: the SDK could agree perfectly with a snapshot the server had stopped honoring. So our check-openapi-snapshot.mjs script runs in two modes.
node scripts/check-openapi-snapshot.mjs # offline
node scripts/check-openapi-snapshot.mjs --served <url> # against the running APIOffline mode checks that the snapshot survives a round trip through the same formatting the refresh script uses, which catches hand edits, and that it has at least 242 paths, which catches a truncated download. Served mode sorts the keys on both documents and reports structural differences as JSON pointers, because a text diff of a large reordered JSON file is unreadable.
In CI, a job called API OpenAPI Drift builds the API, starts it against a throwaway PostgreSQL 17 container, waits for the health check, downloads the served document and runs the served comparison. Locally, our verify-changed.sh script runs the generated-artifact check and the offline snapshot check when a change touches the relevant paths.
What does this pipeline cost to maintain?
Generator upkeep
Four generators sit in this chain (Grpc.Tools, protoc through grpc-tools, ts-proto and Hey API), plus a pinned protoc in CI. Hey API's docs say it's in initial development and ask you to pin an exact version. We use ^0.99.0, which for a 0.x package allows patch releases only, and the lockfile pins the rest. Any upgrade can change output across hundreds of operations.
The snapshot needs a running API
Refreshing it locally means having the Tilt stack up. Booting the API in CI took a Postgres service and about a dozen dummy settings, because the API refuses to start without its secrets and storage configuration.
Big generated diffs
The snapshot is about 1.3 MB and 45,000 lines, and 190 commits have touched it since it was added in February 2026; the largest changed close to 8,000 lines. Gitignoring the generated TypeScript (about 33,000 lines for the browser SDK alone) keeps it out of review, but someone still has to read the snapshot diff, or at least skim it with intent.
Replacing a deprecated package
Until October 2026 the OpenAPI step ran on Microsoft.AspNetCore.Grpc.Swagger, which was always marked experimental. Microsoft deprecated it (opens in a new tab) in June 2026 with no direct replacement (dotnet/aspnetcore#67134 (opens in a new tab)), and it held the API on Swashbuckle 6 and an older Microsoft.OpenApi that conflicted with the built-in generator. We moved to Microsoft.AspNetCore.OpenApi and vendored the piece Microsoft stopped shipping: an MIT-licensed community port of the original package, plus a few route helpers ASP.NET Core keeps internal. That code is ours to maintain now, but because Hey API only needs the right paths and operation IDs, the swap stayed inside the API project. It's the risk I described in why I avoid third-party packages: when a maintainer winds a package down, you change your application on their timeline. I'll write up how the replacement went as a follow-up to that article.
Conventions only tests can enforce
Generators will happily produce a badly named function or a public route for something meant to stay internal, which is why both conventions above are architecture tests. Tests only see what they were written to look for, though. GetPublishingReadiness has a GET binding plus a POST binding, because a page selection can run past a URL's length limit. Both share one operation ID, so Hey API names the POST function getPublishingReadiness2, and the deploy review screen imports it as getPublishingReadiness2 as getPublishingReadiness. It works, and nothing flags the name.
What to keep if your project is smaller
If the browser is your only consumer, the protobuf half of this post is optional. I'd still consider the gRPC pipeline for its shared logging and error handling; the contract-first post linked at the top shows the interceptor that does it.
If you have services that want gRPC and a browser that wants JSON, give the OpenAPI step the most scrutiny. On .NET it's the link Microsoft no longer supports for gRPC, and it's where your function names get decided. A check for missing operation IDs is cheap to write while you have ten of them.
The committed snapshot transfers most easily. It turns API changes into a reviewable diff and lets clients build without a running server, as long as something keeps proving it matches what the server serves. Plan that check from the start.
Try it on one endpoint
You don't need the whole chain to see whether it fits. On an existing ASP.NET Core gRPC service:
Add an HTTP rule to one RPC. Import
google/api/annotations.protoand addoption (google.api.http) = { get: "/v1/..." };. On .NET 8 and later, Microsoft's docs say to set<IncludeHttpRuleProtos>true</IncludeHttpRuleProtos>in the project file so the Google protos are available. (We vendor them next to our own protos instead.)Add the
Microsoft.AspNetCore.Grpc.JsonTranscodingpackage and changeAddGrpc()toAddGrpc().AddJsonTranscoding(). Call the route with curl and check that the JSON looks like your message.Get an OpenAPI document for that endpoint, save it to a file and commit it. Make sure the operation has the
operationIdyou want your TypeScript function to be called.Generate a client:
npm install @hey-api/openapi-ts -D -E, thennpx @hey-api/openapi-ts -i ./openapi/v1.json -o ./src/client. Call the generated function from one screen.Rename a field in the
.proto, rebuild, refresh the document and regenerate. See whether the compiler finds the call site.Write the check before you need it: something that regenerates and diffs, and something that compares your saved document with the one the server serves.
If step 5 points you at the right line of code, the chain is working. If keeping step 6 honest feels like more work than the feature, that's a reasonable sign your project doesn't need the whole thing yet.