From Zod to Protobuf: Strongly-Typed Contracts Between Laravel and Next.js Using gRPC-Web over Cloudflare Workers
The Contract Mismatch Problem
Every full-stack developer has felt the pain. You define a schema in Zod for your Next.js form validation, then rebuild similar logic in Laravel with Form Requests or Eloquent casts. The API payload drifts out of sync. A field becomes nullable on the backend but stays required on the frontend. Type errors creep into production through the gaps between systems.
Runtime validation libraries like Zod solve half the problem. They guard JavaScript's boundaries effectively. But Zod schemas are TypeScript artifacts. They cannot cross network boundaries to a PHP backend. They cannot generate client code. They offer no enforcement at the transport layer.
This post demonstrates a complete replacement: Protocol Buffers as the single source of truth, gRPC-Web as the transport, and Cloudflare Workers handling the browser-to-gRPC translation. The result is genuine type safety from Laravel's controller methods through to your React hooks, with no code duplication and runtime guarantees stronger than either Zod or traditional REST.
Why Protobuf Over Zod for Cross-System Contracts
Zod excels within JavaScript runtimes. It composes beautifully, infers TypeScript types automatically, and validates at runtime. These strengths become limitations when multiple languages and networks are involved.
- No native PHP equivalent: You must manually translate Zod schemas to PHP validation rules, Eloquent casts, or PHPDoc annotations.
- No binary serialization: JSON payloads are verbose and slow compared to Protocol Buffers.
- No code generation: Every API change requires manual updates to client and server code.
- No schema evolution: Adding fields safely requires coordination across teams.
Protobuf solves each issue with a language-agnostic IDL, compact binary encoding, and compilers that generate strict types for PHP, TypeScript, Go, or any supported language. The .proto file becomes your contract. Everything else derives from it.
Architecture Overview
Our stack connects four layers:
- Laravel backend: Serves gRPC over HTTP/2 using the
grpc-phpextension and a custom service provider. - Cloudflare Worker: Receives gRPC-Web requests from browsers (HTTP/1.1), translates to standard gRPC, and forwards to Laravel.
- Next.js frontend: Uses generated TypeScript gRPC-Web clients with strongly-typed request/response types.
- Protobuf schema: Defines messages and services consumed by all three layers.
The Cloudflare Worker is essential because browsers cannot speak native gRPC (HTTP/2 with trailers). gRPC-Web wraps gRPC for HTTP/1.1 compatibility, but requires a proxy to translate back to standard gRPC. Cloudflare Workers provide this at the edge with minimal latency.
Defining the Contract in Protobuf
We begin with a single source of truth. This .proto file defines a user creation flow:
syntax = "proto3";
package users;
option php_namespace = "App\\Protobuf";
option php_metadata_namespace = "App\\Protobuf\\GPBMetadata";
service UserService {
rpc CreateUser(CreateUserRequest) returns (UserResponse);
rpc GetUser(GetUserRequest) returns (UserResponse);
}
message CreateUserRequest {
string email = 1;
string password = 2;
string display_name = 3;
}
message GetUserRequest {
int64 id = 1;
}
message UserResponse {
int64 id = 1;
string email = 2;
string display_name = 3;
google.protobuf.Timestamp created_at = 4;
}
Notice the field numbers. These are not decorative. They encode into the binary format, enabling backward-compatible schema evolution. Adding field 5 never breaks existing clients. Changing or reusing numbers does.
Generating Types and Server Code
PHP Generation for Laravel
Install the Protobuf compiler and PHP plugin:
pecl install protobuf
composer require google/protobuf
Generate PHP classes from your schema:
protoc --php_out=./generated \
--grpc_out=./generated \
--plugin=protoc-gen-grpc=/usr/local/bin/grpc_php_plugin \
./proto/users.proto
This produces PSR-4 autoloadable classes under App\Protobuf. The UserResponse message becomes a concrete PHP class with getters, setters, and binary serialization.
TypeScript Generation for Next.js
Install the gRPC-Web protoc plugin:
npm install grpc-web google-protobuf
npm install -D protoc-gen-grpc-web
Generate the client:
protoc --js_out=import_style=commonjs:./generated \
--grpc-web_out=import_style=typescript,mode=grpcwebtext:./generated \
./proto/users.proto
The output includes UserServiceClient with methods like createUser() that accept and return fully typed objects. No any types. No manual interface declarations.
Implementing the Laravel gRPC Server
Laravel does not natively serve gRPC. We bridge this with a custom server implementation using the Swoole or RoadRunner runtime for persistent PHP processes, which gRPC requires for HTTP/2 handling.
First, implement the generated service interface:
namespace App\Grpc;
use App\Protobuf\Users\UserServiceInterface;
use App\Protobuf\Users\CreateUserRequest;
use App\Protobuf\Users\GetUserRequest;
use App\Protobuf\Users\UserResponse;
use App\Models\User;
use Google\Protobuf\Timestamp;
use Spiral\RoadRunner\GRPC\ContextInterface;
class UserService implements UserServiceInterface
{
public function CreateUser(
ContextInterface $context,
CreateUserRequest $request
): UserResponse {
$user = User::create([
'email' => $request->getEmail(),
'password' => bcrypt($request->getPassword()),
'display_name' => $request->getDisplayName(),
]);
$createdAt = new Timestamp();
$createdAt->fromDateTime($user->created_at);
return (new UserResponse())
->setId($user->id)
->setEmail($user->email)
->setDisplayName($user->display_name)
->setCreatedAt($createdAt);
}
public function GetUser(
ContextInterface $context,
GetUserRequest $request
): UserResponse {
$user = User::findOrFail($request->getId());
// ... build response
}
}
Register with RoadRunner's gRPC plugin in .rr.yaml:
grpc:
listen: tcp://0.0.0.0:9001
proto:
- ./proto/users.proto
workers:
command: "php artisan grpc:work"
The critical insight: Laravel controllers and Eloquent remain your application layer. gRPC is transport and contract only. Business logic does not change.
The Cloudflare Worker as gRPC-Web Bridge
Cloudflare Workers receive gRPC-Web calls from browsers and proxy them to the Laravel gRPC server. They handle the protocol translation that browsers cannot perform natively.
import { grpc } from '@improbable-eng/grpc-web';
import { NodeHttpTransport } from '@improbable-eng/grpc-web-node-http-transport';
// Required for service-to-service calls from the Worker runtime
grpc.setDefaultTransport(NodeHttpTransport());
interface Env {
GRPC_TARGET: string; // e.g., "https://grpc.internal.yourservice.com:443"
}
export default {
async fetch(
request: Request,
env: Env,
ctx: ExecutionContext
): Promise<Response> {
const url = new URL(request.url);
// Only intercept gRPC-Web content type
const contentType = request.headers.get('content-type') || '';
if (!contentType.includes('application/grpc-web')) {
return new Response('Not Found', { status: 404 });
}
// Transform gRPC-Web to standard gRPC
const grpcTarget = new URL(env.GRPC_TARGET);
grpcTarget.pathname = url.pathname;
const modifiedHeaders = new Headers(request.headers);
modifiedHeaders.set('content-type', 'application/grpc');
modifiedHeaders.delete('x-grpc-web');
const grpcResponse = await fetch(grpcTarget.toString(), {
method: request.method,
headers: modifiedHeaders,
body: request.body,
// @ts-ignore: Cloudflare supports duplex in recent versions
duplex: 'half',
});
// Transform response back to gRPC-Web
const responseHeaders = new Headers(grpcResponse.headers);
responseHeaders.set('content-type', 'application/grpc-web+proto');
return new Response(grpcResponse.body, {
status: grpcResponse.status,
headers: responseHeaders,
});
},
};
Deploy this Worker to route https://api.yourdomain.com/* to your internal gRPC endpoint. The Worker runs at 300+ edge locations, adding minimal latency compared to a self-hosted Envoy proxy.
Consuming from Next.js with Type Safety
The generated TypeScript client provides IDE autocomplete and compile-time checking that replaces Zod's runtime-only validation:
import { UserServiceClient } from '@/generated/UsersServiceClientPb';
import { CreateUserRequest, UserResponse } from '@/generated/users_pb';
const client = new UserServiceClient('https://api.yourdomain.com');
async function createUser(formData: {
email: string;
password: string;
displayName: string;
}): Promise<UserResponse> {
const request = new CreateUserRequest();
request.setEmail(formData.email);
request.setPassword(formData.password);
request.setDisplayName(formData.displayName);
// TypeScript knows this returns UserResponse, not Promise<any>
return new Promise((resolve, reject) => {
client.createUser(request, {}, (err, response) => {
if (err) reject(err);
else resolve(response!);
});
});
}
For React Server Components or API routes, use the same client without browser restrictions:
// app/api/users/route.ts
import { NextRequest } from 'next/server';
export async function POST(request: NextRequest) {
const body = await request.json();
// Compile error if body is not CreateUserRequest-compatible
const response = await createUser(body);
return Response.json({
id: response.getId(),
email: response.getEmail(),
});
}
Migrating from Zod: A Practical Path
Complete replacement is rarely necessary immediately. Migrate endpoints individually where type safety matters most:
- Identify high-risk boundaries: User creation, payment flows, anything with complex nested objects.
- Define proto replacements: Start with one service definition.
- Run generators in CI: Ensure
.protochanges propagate automatically. - Maintain Zod for form UX: Keep Zod schemas derived from proto-generated interfaces, not as primary sources.
Derive Zod from protobuf types where you need progressive enhancement:
import { CreateUserRequest } from '@/generated/users_pb';
import { z } from 'zod';
// Extract the shape from protobuf, enhance with Zod refinements
type ProtoShape = CreateUserRequest.AsObject;
export const userFormSchema: z.ZodType<
Omit<ProtoShape, 'password'> & { password: string; confirmPassword: string }
> = z.object({
email: z.string().email(),
password: z.string().min(12),
confirmPassword: z.string(),
displayName: z.string().min(1),
}).refine((data) => data.password === data.confirmPassword, {
message: "Passwords don't match",
path: ['confirmPassword'],
});
Zod now enhances the protobuf contract rather than defining it. The core shape cannot drift because it originates from users.proto.
Validation at Every Layer
Protobuf provides structural validation (correct types, required fields). Business validation remains in Laravel:
public function CreateUser(
ContextInterface $context,
CreateUserRequest $request
): UserResponse {
// Protobuf guarantees these are strings, not null
$email = $request->getEmail();
$password = $request->getPassword();
// Business validation stays in application code
if (strlen($password) < 12) {
throw new \InvalidArgumentException('Password too weak');
}
if (User::where('email', $email)->exists()) {
throw new AlreadyExistsException();
}
// ...
}
This separation is clean: Protobuf validates shape and presence. Your application validates meaning and business rules.
Operational Considerations
Schema Evolution Without Deployment Hell
Protobuf's backward compatibility rules enable safe deployment:
- Adding fields: Use new numbers. Old clients ignore them. New clients receive default values.
- Removing fields: Reserve the number and name. Prevents accidental reuse.
- Changing types: Generally unsafe. Use wire-compatible types (int32 to int64) carefully.
Reserved fields in your proto prevent catastrophic mistakes:
message UserResponse {
int64 id = 1;
string email = 2;
reserved 3; // Old phone_number field
reserved "phone_number";
string display_name = 4;
}
Debugging Binary Payloads
Unlike JSON, protobuf is not human-readable over the wire. Use gRPC reflection to enable grpcurl inspection, or configure your Cloudflare Worker to log decoded payloads in development environments.
Bundle Size Impact
Generated gRPC-Web clients add approximately 30-50KB gzipped. For comparison, Zod approaches 45KB alone. The protobuf runtime (google-protobuf) is roughly 80KB. Acceptable for applications where correctness matters.
Conclusion
Zod remains excellent for TypeScript-native validation. When systems must communicate across languages and networks, it becomes a source of duplication and drift. Protocol Buffers with gRPC-Web replace manual contract maintenance with generated, enforced, binary-efficient interfaces.
The architecture presented here, Laravel serving native gRPC, Cloudflare Workers translating for browsers, and Next.js consuming generated TypeScript clients, eliminates an entire class of integration bugs. Your .proto file becomes the single point of truth that Zod schemas could never be: language-agnostic, version-evolvable, and enforced at every layer from transport to type system.