- TypeScript 100%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
| docs | ||
| src | ||
| .gitignore | ||
| .oxfmtrc.json | ||
| bun.lock | ||
| package-lock.json | ||
| package.json | ||
| README.md | ||
| tsconfig.json | ||
porto
Type-safe RPC router for browser extension contexts.
Stop writing chrome.runtime.sendMessage and return true by hand. Porto makes popup, background, content scripts, side panels, and offscreen documents feel like they're sharing an API.
// background.ts
import { createRouter } from "porto";
const app = createRouter();
app.handle("delete-client", async ({ clientId }: { clientId: string }) => {
await deleteClient(clientId);
return { ok: true };
});
app.listen();
// popup.ts
import { createClient } from "porto/client";
const client = createClient<typeof app>();
await client.call("delete-client", { clientId: "abc" }); // fully typed
Install
npm install porto
Zod and Valibot are optional peer dependencies — install whichever you use:
npm install zod # or: npm install valibot
Overview
Porto has four concepts:
- Router — lives in your background service worker, registers handlers, calls
listen() - Client — lives in popup / content script / side panel, calls
call() - Middleware — runs before handlers, can inject context (auth tokens, etc.)
- Validation — Zod or Valibot schemas attached to handlers for runtime input checking
Router
createRouter()
import { createRouter } from "porto";
const app = createRouter();
app.handle("sync-now", async () => {
await sync();
return { ok: true };
});
app.handle("get-user", async ({ id }: { id: string }) => {
return await db.users.find(id);
});
app.listen();
Call listen() once in your background service worker. It attaches chrome.runtime.onMessage.addListener internally — you never touch that API again.
Declarative style
Inspired by tRPC. Better for larger routers since routes are co-located with their types:
import { createRouter, procedure } from "porto";
const app = createRouter({
syncNow: procedure.handler(async () => {
await sync();
return { ok: true };
}),
getUser: procedure.input<{ id: string }>().handler(async ({ id }) => {
return await db.users.find(id);
}),
});
app.listen();
export type AppRouter = typeof app;
Export AppRouter and import it in your popup/content script for end-to-end types.
Client
import { createClient } from "porto/client";
import type { AppRouter } from "./background";
const client = createClient<AppRouter>();
client.call(route, input?)
await client.call("syncNow");
await client.call("getUser", { id: "123" });
TypeScript enforces the input shape. Missing or wrong-typed fields are compile errors.
By default the client sends to the background service worker via chrome.runtime.sendMessage. To target a specific tab (e.g. from background → content script):
const client = createClient<AppRouter>({ tabId: tab.id });
Validation
Attach a Zod or Valibot schema to any handler. Porto runs it at runtime before your handler executes — bad input never reaches your code.
Zod
import { z } from "zod";
app.handle(
"delete-client",
{
input: z.object({
clientId: z.string(),
}),
},
async ({ clientId }) => {
await deleteClient(clientId);
return { ok: true };
},
);
Valibot
import * as v from "valibot";
app.handle(
"delete-client",
{
input: v.object({
clientId: v.string(),
}),
},
async ({ clientId }) => {
await deleteClient(clientId);
return { ok: true };
},
);
Custom adapter
Anything with a .parse(input): T method works:
app.handle(
"delete-client",
{
input: {
parse(input: unknown) {
if (typeof (input as any).clientId !== "string") {
throw new Error("clientId must be a string")
}
return input as { clientId: string }
},
},
},
async ({ clientId }) => { ... },
)
Middleware
Middleware runs before every handler on the router. Use it for auth, logging, or injecting shared state into context.
app.use(async (ctx, next) => {
const token = await getAccessToken();
ctx.set("token", token);
return next();
});
app.handle("sync", async (_, ctx) => {
const token = ctx.get<string>("token");
await sync(token);
return { ok: true };
});
Multiple middleware run in registration order:
app.use(loggingMiddleware);
app.use(authMiddleware);
app.use(rateLimitMiddleware);
Procedure-scoped middleware
Use procedure.use() to scope middleware to specific routes rather than the whole router:
import { procedure } from "porto";
const authProcedure = procedure.use(async (ctx, next) => {
const token = await getToken();
if (!token) throw new PortoError("NOT_AUTHENTICATED", "Please log in first");
ctx.set("token", token);
return next();
});
const app = createRouter({
publicRoute: procedure.handler(async () => "anyone can call this"),
privateRoute: authProcedure.handler(async (_, ctx) => {
return `authenticated: ${ctx.get("token")}`;
}),
});
Error handling
Throw from any handler. Porto catches it, serializes it over the wire, and re-throws on the client.
// background
app.handle("login", async () => {
throw new Error("Something went wrong");
});
// popup
try {
await client.call("login");
} catch (error) {
console.error(error.message); // "Something went wrong"
}
Typed errors
Use PortoError to attach a machine-readable code:
import { PortoError } from "porto";
app.handle("get-user", async ({ id }: { id: string }) => {
const user = await db.users.find(id);
if (!user) throw new PortoError("NOT_FOUND", `User ${id} not found`);
return user;
});
import { PortoError } from "porto/client";
try {
await client.call("get-user", { id });
} catch (error) {
if (error instanceof PortoError && error.code === "NOT_FOUND") {
showToast("User not found");
}
}
Namespaces
Group related routes under a prefix. Routes are accessible as namespace:name.
const tabs = app.namespace("tabs");
tabs.handle("list", async () => chrome.tabs.query({}));
tabs.handle("focus", async ({ tabId }: { tabId: number }) => {
await chrome.tabs.update(tabId, { active: true });
return { ok: true };
});
await client.call("tabs:list");
await client.call("tabs:focus", { tabId: 42 });
Context
Every handler receives a Context as its second argument. It's populated by middleware and contains request metadata.
interface Context {
sender: chrome.runtime.MessageSender; // which context sent this message
signal: AbortSignal; // cancelled if the sender disconnects
requestId: string; // unique ID for this request
set(key: string, value: unknown): void;
get<T>(key: string): T;
}
Wire protocol
Porto uses chrome.runtime.sendMessage internally. The messages it sends look like:
{ "id": "req_x7k2m", "route": "delete-client", "input": { "clientId": "abc" } }
Responses:
{ "id": "req_x7k2m", "success": true, "data": { "ok": true } }
{ "id": "req_x7k2m", "success": false, "error": { "code": "NOT_FOUND", "message": "..." } }
This is an implementation detail. You shouldn't need to think about it.
Migrating from raw sendMessage
Before:
// background.ts
chrome.runtime.onMessage.addListener((msg, _sender, reply) => {
if (msg.type === "delete-client") {
deleteClient(msg.clientId)
.then(() => reply({ ok: true }))
.catch((e) => reply({ error: e.message }));
return true; // ← easy to forget, breaks async
}
});
// popup.ts
chrome.runtime.sendMessage({ type: "delete-client", clientId: "abc" }, (response) => {
if (response.error) handleError(response.error);
});
After:
// background.ts
app.handle("delete-client", async ({ clientId }: { clientId: string }) => {
await deleteClient(clientId);
return { ok: true };
});
// popup.ts
await client.call("delete-client", { clientId: "abc" });
Roadmap
- Long-lived connections (
client.channel()via Chrome Ports) - Fire-and-forget events (
client.emit()) - Streaming responses (
app.stream()/client.stream()) - Background → content script push
License
MIT