The typed bridge
Your Go handlers, read by static analysis, become the TypeScript types your React pages are checked against. No OpenAPI spec to maintain, no generation step you invoke by hand, no runtime reflection. This page covers writing API routes, what borgogen can see, how Go types map to TypeScript, the generated client, and where the analysis honestly stops.
This is one of the five reasons borgo exists: types that are generated cannot drift from the code they describe, because nobody maintains them.
API routes#
API routes are Go files in api/. Annotate a handler with a route directive and it is mounted for you:
//borgo:route GET /api/tasks
func ListTasks(w http.ResponseWriter, r *http.Request) {
borgo.JSON(w, http.StatusOK, TaskList{Tasks: tasks})
}
Prefer explicitness? borgo.Handle("GET /api/tasks", ListTasks) in an init() works identically and feeds the same types. main.go stays five lines: import your api package, call borgo.Serve().
It is a normal Go module#
This is worth stating plainly, because the framework's own zero-dependency rule sometimes reads as a restriction on your code. It is not. Your api/ package is ordinary Go: go get whatever you want and use it.
go get gorm.io/gorm
go get github.com/jackc/pgx/v5
go get modernc.org/sqlite
//borgo:route GET /api/tasks/recent
func RecentTasks(w http.ResponseWriter, r *http.Request) {
tasks := []Task{}
if err := db.Order("created_at desc").Find(&tasks).Error; err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
borgo.JSON(w, http.StatusOK, TaskList{Tasks: tasks})
}
The bridge does not care where your data came from — it reads the type you hand to borgo.JSON, so a route backed by GORM, database/sql, an HTTP call to another service or a hard-coded slice all type identically. examples/tasks in this repository uses GORM with SQLite; the full template uses database/sql over SQLite, with the migrations the database describes.
What has zero dependencies is the framework: github.com/LuigiDavideMicca/borgo pulls in nothing but the standard library, so the only third-party code in your binary is the code you chose. Types from a dependency reach TypeScript like any other — time.Time becomes a string, a type with MarshalText becomes a string, and one whose custom MarshalJSON runs where it is used maps to unknown until you point a //borgo:type override at it, which is exactly what the GORM example does for gorm.DeletedAt. Whether a marshaler runs at all can depend on the value's position — see addressability.
A malformed directive fails the generator before it writes anything, so a typo can never leave behind a half-generated borgo.gen.go that keeps breaking the build after you fix it. Registering the same pattern twice, or registering after borgo.Serve() has snapshotted the table, panics naming the offending pattern. (Only the malformed pattern panic also names the registering file and line.)
What borgogen reads#
borgogen runs automatically on every api/*.go change in dev, and as part of borgo build and borgo export. It analyzes your api package with go/ast and go/types, and writes two files:
.borgo/api-types.d.ts— a TypeScript interface per Go struct, plus a route map from pattern to request and response typesapi/borgo.gen.go— the mounting code for//borgo:routehandlers
Two more appear only when the package asks for them: .borgo/go.ts when it holds a //borgo:export, and .borgo/middleware.json, which tells borgo export what api/middleware.go covers.
It finds a route's response type from borgo.JSON[T] and inline json.NewEncoder(w).Encode(v) calls reachable from the handler — including through helper functions, both inside the api package and — within the bounds listed under honest limits — across other packages of your module:
func respondTask(w http.ResponseWriter, status int, task Task) {
borgo.JSON(w, status, TaskItem{Task: task})
}
//borgo:route GET /api/tasks/{id}
func GetTask(w http.ResponseWriter, r *http.Request) {
respondTask(w, http.StatusOK, Task{ID: 1, Title: "Buy oranges"})
}
The route still types as TaskItem. Extracting a helper is a refactoring, not a hole in your types.
A handler with more than one success shape produces a union, and error envelopes written with a constant status of 300 or more are deliberately excluded — the client throws an ApiError on any non-2xx, so those bodies never reach the caller as data:
"GET /api/search": { response: Suggestions | Results };
The two rules meet badly in one place. "Constant at the call" is true of borgo.JSON(w, http.StatusNotFound, …) and false of the helper every app ends up writing, fail(w, status, message): the generator follows the helper, finds a status it cannot read, and types the refusal as something the route answers. Nothing fails — a union with one member too many is not an error until somebody reads a field — and every route that can refuse is quietly typed worse. Such a helper calls borgo.Error, which writes the same JSON and which the generator never reads:
type Refusal struct {
Error string `json:"error"`
}
func fail(w http.ResponseWriter, status int, message string) {
borgo.Error(w, status, Refusal{Error: message})
}
Typed request bodies#
Decode with borgo.Bind[T](r) and the route's request is typed too, so the client requires a body of that type:
type TaskCreate struct {
Title string `json:"title"`
Body string `json:"body"`
}
//borgo:route POST /api/tasks
func CreateTask(w http.ResponseWriter, r *http.Request) {
body, err := borgo.Bind[TaskCreate](r)
if err != nil {
borgo.BindError(w, err)
return
}
borgo.JSON(w, http.StatusCreated, TaskItem{Task: Task{Title: body.Title}})
}
The generated entry now carries both directions, and a body of the wrong shape fails tsc:
"POST /api/tasks": { response: TaskItem; request: TaskCreate$Request };
The request side is not TaskCreate. It is a second declaration, TaskCreate$Request, because a struct is read by encoding/json more leniently than it is written — see the request side. In short: every property is optional and admits null, so body: {} compiles, and it compiles because the server accepts it.
Bind reads at most 1 MB, so a route expecting a small payload cannot be fed gigabytes; borgo.BindMax[T](r, 8<<20) raises the cap where a route legitimately needs it (limit <= 0 disables it), and borgogen types it identically. borgo.BindError(w, err) answers with the right status as JSON — 413 past the limit, 415 for a missing or non-JSON Content-Type, 400 for malformed JSON — and the proxy relays those verbatim, so the browser sees the API's answer rather than a wrapped error page.
A form that is wrong: BindValid and Invalid#
A body that decodes is not yet a body the app accepts, and every app with more than a few forms ends up inventing its own answer for "this field is wrong", which the page reading it then has to know. borgo.BindValid is Bind that asks the form itself: after decoding, a type with a Validate() error method is asked, and what it returns is the error. borgo.Invalid is the error to return — a map from field to what is wrong with it:
type Invite struct {
Email string `json:"email"`
Seats int `json:"seats"`
}
func (f Invite) Validate() error {
bad := borgo.Invalid{}
if f.Email == "" {
bad["email"] = "an address is needed"
}
if f.Seats < 1 || f.Seats > 50 {
bad["seats"] = "between 1 and 50"
}
return bad.OrNil()
}
type Invited struct {
Seats int `json:"seats"`
}
//borgo:route POST /api/invites
func CreateInvite(w http.ResponseWriter, r *http.Request) {
form, err := borgo.BindValid[Invite](r)
if err != nil {
borgo.BindError(w, err)
return
}
borgo.JSON(w, http.StatusCreated, Invited{Seats: form.Seats})
}
BindError writes an Invalid as 422 with one shape, whatever the form:
{ "error": "some fields are not acceptable", "fields": { "email": "an address is needed", "seats": "between 1 and 50" } }
On the other side ApiError.fields() reads it back: the fields of that body as Record<string, string>, and an empty object for any other refusal — a 401, a 500, a body that is not JSON — so a form reads error.fields().email without first asking what kind of error it holds:
import { ApiError, type ActionContext } from "borgo-framework";
export async function action({ request, api }: ActionContext) {
const form = await request.formData();
try {
await api("POST /api/tasks", { body: { title: String(form.get("title") ?? "") } });
} catch (error) {
// { title: "..." } after a 422 written for a borgo.Invalid, {} otherwise
if (error instanceof ApiError && error.status === 422) return { fields: error.fields() };
throw error;
}
return { fields: {} };
}
- Return
bad.OrNil(), notbad. An emptyInvalidreturned as anerroris notnil, and would refuse a form with nothing wrong in it. - The field names are yours. Use the JSON names, which are the ones the page knows; nothing checks them against the struct.
Validatemay be on the value or on its pointer, and for a type without oneBindValidisBind.- Other errors keep their meaning. A
borgo.Refuse(status, body)returned fromValidateis answered with that status and body; any other error is a400carrying its message, as a decode error is. - The types are
Bind's. borgogen readsBindValid[T]as it readsBind[T]: the route's request isInvite$Request, every property optional, because that is what the decoder accepts. WhatValidatethen refuses is a runtime answer, not a type. borgo.Signupanswers in the same shape. A signup form whoseValidatereturns anInvalidis answered422with its fields, before the password is hashed.
How Go types become TypeScript#
Fields follow encoding/json semantics, because that is what will actually be on the wire. This table is the response side — what json.Marshal writes. A request body is read by a different, more lenient set of rules, and gets its own declaration; that is the next section.
| Go | TypeScript | Note |
|---|---|---|
string, int, float64, bool |
string, number, boolean |
|
*T |
T | null |
|
[]T |
Array<T> | null |
a nil slice marshals to null, never [] — see below |
[N]T |
Array<T> |
a fixed-size array is always there, so it is never null |
[]byte |
string | null |
Go marshals it as base64; nil is null |
map[string]T |
Record<string, T> | null |
numeric keys too — Go writes them as strings; a nil map is null |
time.Time |
string |
RFC 3339 |
json.RawMessage |
unknown |
|
a type with a value-receiver MarshalText |
string |
|
a type with a value-receiver MarshalJSON |
unknown |
override it with //borgo:type |
| a type whose marshaler has a pointer receiver | depends on where the value sits | see addressability below |
json:"name,omitempty" |
name?: T |
strings, numbers, bools, slices, maps, pointers — not structs, which Go always writes |
json:"name,omitzero" |
name?: T |
Go 1.24+ |
json:"-" |
omitted | but json:"-," means a field literally named - |
json:",string" |
string |
numbers and bools quoted on the wire |
Embedded structs are flattened using the standard library's own depth rules: a field on the outer struct shadows a promoted one at greater depth, and two promoted fields tied at the same depth cancel out, exactly as encoding/json drops them. Fields promoted from an unexported embedded type are included, because they are marshalled. Two same-named structs in different packages get distinct interfaces, prefixed by package. Recursive types terminate. A JSON tag that is not a valid TypeScript identifier is emitted quoted, so json:"user-name" cannot break your typecheck.
Addressability: one type, two shapes#
encoding/json calls a marshaler declared on a pointer receiver only where it can take the value's address. So a type carrying one does not have a JSON shape — it has two, and which one you get depends on the position the value sits in, not on the type. borgogen models this exactly rather than picking a winner.
The rules it follows, which are reflect.Value.CanAddr's:
| Position | Addressable? |
|---|---|
json.Marshal's own argument — the root of a response |
no |
| a slice element, anything behind a pointer | yes, always |
| a struct field, an array element, a value-embedded struct | inherits from whatever holds it |
| a map value, a map key, anything behind an interface | no, ever |
| a field promoted through an embedded pointer | yes — reaching it dereferences, so it is addressable even inside a map value |
The case worth seeing, because it is the one that surprises:
type PM struct {
X int `json:"x"`
}
func (p *PM) MarshalJSON() ([]byte, error) { return []byte(`"pm"`), nil }
type Outer struct {
P PM `json:"p"`
}
Outer never mentions a pointer, and yet:
Outer{} -> {"p":{"x":0}}
[]Outer{{}} -> [{"p":"pm"}]
map[string]Outer{"k": {}} -> {"k":{"p":{"x":0}}}
Same type, three positions, two different JSON shapes — the slice element is addressable, so PM's marshaler runs there and nowhere else. A map value behaves like the root, not like the slice.
Where the shape genuinely depends on position, borgogen emits a second interface beside the first and each reference site picks the right one:
export interface Outer {
p: PM;
}
// Outer as encoding/json writes it where the value is addressable
export interface Outer$Addressable {
p: unknown;
}
$ cannot appear in a Go identifier, so the variant name can never collide with a type of yours — the same is true of the $Request suffix below. A type whose two renderings are identical — the overwhelming majority — gets one interface as before.
This also means the two positions can run different methods. A type with MarshalJSON on the pointer receiver and MarshalText on the value one is unknown where it is addressable and string where it is not, because that is the order encoding/json resolves them in. Give a marshaler a value receiver and all of this collapses: one shape, one interface, everywhere.
Uploads: borgo.BindMultipart#
A body with a file in it is not JSON, and borgo.BindMultipart[T](r) is Bind for it: a multipart/form-data body decoded into a struct, text parts into string, bool, integer, float and []string fields by their json name, files into borgo.File, *borgo.File or []borgo.File. The route's request is typed like any other, with the files as Blob — which a File from an <input type="file"> or a FormData is — and the generated entry carries multipart: true, which lets the body be a FormData of your own too:
type AttachmentForm struct {
Note string `json:"note"`
File borgo.File `json:"file"`
}
// gitignored in development, /data/uploads in a container - see below
var uploads = &borgo.Uploads{Dir: "uploads"}
//borgo:route POST /api/attachments
func UploadAttachment(w http.ResponseWriter, r *http.Request) {
form, err := borgo.BindMultipart[AttachmentForm](r)
if err != nil {
borgo.BindError(w, err)
return
}
stored, err := uploads.Save(form.File)
if errors.Is(err, borgo.ErrNoUpload) {
http.Error(w, "a file is required", http.StatusBadRequest)
return
}
if err != nil {
log.Printf("storing an upload: %v", err)
http.Error(w, "storage failed", http.StatusInternalServerError)
return
}
// keep stored beside who owns it - see "Storing and serving" below
borgo.JSON(w, http.StatusCreated, stored)
}
"POST /api/attachments": { response: Stored; request: AttachmentForm$Request; multipart: true };
// in an action: the File from the posted form goes as it is
await api("POST /api/attachments", { body: { note, file } });
The wire is decided by the value, since the route's type is gone at runtime: a body holding a file goes as a FormData the client builds — a Blob appended as a file, an array as repeated parts, a string, number or boolean as its text, and anything else (a nested object, a Date) refused by name — and a body holding none goes as JSON, which BindMultipart reads too, with every File left zero. So a form whose file is optional works whether or not the user picked one, and a file never arrives any way but as a part. A JSON route refuses a FormData at tsc, and a multipart route refuses a string where a file belongs.
The fields a form can fill are string, bool, the integers, the floats, []string for a repeated part, and File, *File, []File, named as encoding/json names them — the json tag, or the Go name; an untagged embedded struct or pointer to one gives up its fields — and matched exactly, as the typed client sends them. The first of a repeated part fills a scalar; a number outside its field's width is refused. A field of any other type, an embedded File, or two fields answering one name is the app's mistake, not the client's: BindMultipart refuses every request to that form and BindError answers 500, with the field named in the log and nothing about your types in the response.
The body is read at most 32 MiB (BindMultipartMax changes that, and BORGO_MAX_BODY on the public port is the same number by default). A reverse proxy has a limit of its own: the Caddy and nginx configs borgo deploy init writes cap a body at 1 MiB, so raise that line for an upload route, or uploads that worked in development meet a 413 in production. The parser has two limits of its own, and both are a 413 like the cap: at most 1000 parts, and text parts held in memory up to about 18 MiB in total. Files past 8 MiB are spilled to temporary files the server removes when the handler returns, so copy what must outlive the request. 415 is any other content type, 400 a part that does not parse as its field, 500 a file the server could not spill to its temporary directory (the path goes to the log, not to the client). A borgo.File in a type read with Bind or BindMax fails the generator: the client would send it as multipart to a route that only reads JSON.
Name and ContentType on a borgo.File are what the client said, nothing more. Storing the file is the next section's.
Storing and serving: borgo.Uploads#
An upload is the same few decisions in every app, and getting any one of them wrong is a vulnerability: what the bytes really are, the name they live under, where that is, and the headers a download goes out with. borgo.Uploads makes them; who may download what stays yours, because only the app knows who owns a file.
Save(file)sniffs the first 512 bytes (http.DetectContentType) and stores the file under a random 32-character key, never the name the client sent. WithTypesset (media types, case and parameters ignored), a file that sniffs as anything else is refused withErrUploadTypeand nothing is written. List what sniffing can report: an SVG sniffs astext/xmlortext/plain, JSON and CSV astext/plain, a.docxasapplication/zip, and an entry sniffing never reports -image/svg+xml,image/avif- matches no file at all; the first upload logs each such entry once. A field left empty isErrNoUpload, and a write that fails halfway leaves nothing behind. TheStoredit returns holds the key, the sniffed type, the size and the client's name with any path, control and invisible format characters removed, for showing back. Keep it beside the file's owner.SaveReader(name, r, max)isSavefor bytes no form carried — a picture the server fetched from somewhere, an export it wrote — so they are sniffed, keyed and served like every other file instead of taking a second road through your own code. It takes at mostmaxbytes and answersErrUploadTooLargefor one more: a form's file was already bounded byBindMultipart, a reader is bounded by nothing.Serve(w, r, stored)answers with the file once your handler has decided this request may have it. It goes out as the sniffed type withX-Content-Type-Options: nosniff,Cache-Control: private, no-cacheso no shared cache holds a file authorized per request and a browser revalidates it byLast-Modified, and aContent-Security-Policysandbox in case it is opened as a page. PNG, JPEG, GIF and WebP areinline; everything else, HTML and SVG among it, downloads as an attachment under its cleaned name. Ranges and conditional requests work. A key that is not oneSavemakes, names no file, or names a link rather than a file, is a 404.ServePreview(w, r, stored)isServefor a file the page wants to show, not hand over. A PDF goes outinline, and in place of the sandbox — a browser's own viewer does not open inside one — it carriesframe-ancestors 'self'andX-Frame-Options: SAMEORIGIN: a page from the same origin may frame it, and nobody else's may. Every other type is served exactly asServeserves it, so calling it for every file a room holds widens nothing but the PDF. The page that frames it needs no change to the default policy, sincedefault-src 'self'covers an<iframe>of the app's own address; an<object>or an<embed>stays refused byobject-src 'none'.Remove(key)deletes the file; one already gone is not an error.
type Attachment struct {
OwnerID uint
borgo.Stored
}
func findAttachment(owner uint, key string) (Attachment, bool) {
// your database: the row whose key and owner both match
return Attachment{}, false
}
func DownloadAttachment(w http.ResponseWriter, r *http.Request) {
user, ok := borgo.GetSession[struct{ ID uint }](r)
// a zero id is no owner: a session from before the id was stored would
// share it with every other such session
if !ok || user.ID == 0 {
http.Error(w, "unauthenticated", http.StatusUnauthorized)
return
}
a, ok := findAttachment(user.ID, r.PathValue("key"))
if !ok {
// someone else's file is a 404 too: a 403 would confirm the key
http.NotFound(w, r)
return
}
uploads.Serve(w, r, a.Stored)
}
Where Dir lives matters twice. In development, a directory inside the app must be in .gitignore, which the dev watcher honours; otherwise every upload rebuilds the app. In a container, the scaffolded Dockerfile creates /data/uploads owned by the app's user, so Dir: "/data/uploads" on a volume mounted at /data, or at /data/uploads itself, is writable. A volume mounted at a path the image does not have is created root-owned, and Save says so when it cannot write. examples/tasks has the whole story in api/attachments.go and pages/attach.tsx: upload, owner-only download, and the oldest files pruned past twenty per user.
The request side: what the decoder accepts#
A struct handed to borgo.Bind[T] is rendered a second time, under <Name>$Request, as encoding/json reads it rather than as it writes it. The two are not mirror images, and the difference was measured one field per kind against the decoder rather than read off its documentation:
- a field the decoder never receives is not an error — it keeps its zero value;
- a field that arrives as
nullis not an error either, for any kind: pointer or not, container, converter,,stringfield,omitemptyfield alike — the value is left untouched, which on a freshBindis again the zero; - a field of the wrong type is an error (
UnmarshalTypeError), for every kind exceptanyand a customUnmarshalJSON.
So on the inbound side every property becomes optional and admits null, and the third rule is what keeps that exact rather than a shrug: title?: string | null is precisely the set of values the server takes for a string field, not a wider one.
type TaskPatch struct {
Title string `json:"title"`
Tags []string `json:"tags,omitempty"`
Due *string `json:"due"`
}
// TaskPatch as encoding/json writes it
export interface TaskPatch {
title: string;
tags?: Array<string> | null;
due: string | null;
}
// TaskPatch as encoding/json reads it, which is not
// the response it writes: a field the decoder never receives is not an
// error, and neither is one that arrives null, so every property below
// is optional and admits null whatever its Go type is.
export interface TaskPatch$Request {
title?: string | null;
tags?: Array<string> | null;
due?: string | null;
}
A few consequences worth knowing:
omitemptyandomitzerochange nothing here. They are write directives. Reading them as "this is the optional one" reads the wrong direction — the fields without them are no less optional to the decoder.- A nested struct is lenient too, because the same decoder reads it: a field of type
InnerisInner$Request | nullin a request. - A fixed-size array is
Array<T> | nullcoming in, not a tuple:encoding/jsontakes what it is given and pads or drops the rest, so[2]stringaccepts["only"]and["a","b","c"]. ,stringis enforced coming in: the field wants the quoted form and refuses the bare number, which is why it is typedstringboth ways.- A type is rendered once where the two readings coincide — a named scalar (
type Money int), a slice or a map of one. Only a struct with a field on the wire gets the second declaration, and it gets it whether or not some route also answers with it, so the name is not an accident of route order. (A struct whose every field is already optional and nullable going out gets a$Requesttwin of identical text; answering "differs" where nothing does costs one duplicate declaration, and answering "does not" where something does would hand a request body the response's shape, which is the bug this direction exists to fix.) - A
json:"-"field and an unexported one are not in the request type, because the decoder never fills them.
Where the request type cannot be exact#
Some things about a body cannot be said in TypeScript, and a type that pretended otherwise would be worse than one that says where it stops. Each divergence below is pinned by a test (TestWhereTheRequestTypeCannotBeExact in cmd/borgogen) that fails the day it stops diverging, so the list is measured, not remembered. The type is wider than the server in these cases — the body compiles, and the server answers 400:
- One numeric type. TypeScript cannot say integer or width, so
{"count": 1.5}and{"count": 1e300}typecheck against anintfield and the decoder refuses them. - A string is a string. RFC 3339 for
time.Time, base64 for[]byte, and the quoted number of a,stringfield are sub-languages a type cannot spell:"nope","!!!"and"x"all compile and all fail to bind.
And narrower than the server in these, deliberately — nothing the server would do anything with is lost:
- A top-level
nullbody. The decoder accepts it and leaves the zero value; the type does not.nulland{}produce the identical value, so no server state is unreachable through the type. - A key the Go type does not declare. The decoder ignores it;
tscrefuses it, twice over — as an excess property on a fresh literal, and, since every property is optional, as a weak-type mismatch. That includes ajson:"-"field addressed by its Go name. json.Numberalso accepts a numeric string.{"amount": "7"}binds, and the type saysnumber. Widening tonumber | stringwould admit every string the server refuses; the template literal`${number}`looks exact and is not, because TypeScript's numeric-string grammar is its own, not JSON's —" 7","7 ","+7",".5","7.","0x10","0b11","0o7"and"07"all typecheck as`${number}`andencoding/jsonrefuses every one (TestNumericStringIsNotJSONNumber). So it staysnumber, and a caller that really wants to send"7"knows it is stepping outside the type.
Type overrides#
A type borgogen cannot see through — one whose custom MarshalJSON runs in the position it is used — maps to unknown. Override the mapping for any named type with a directive anywhere in the api package:
//borgo:type gorm.io/gorm.DeletedAt string | null
The nil slice trap#
One place where Go's own JSON semantics can surprise you, and where the generated types now say so out loud:
var tasks []Task // nil, not empty
db.Find(&tasks) // still nil if there are no rows
borgo.JSON(w, 200, TaskList{Tasks: tasks})
A nil slice, map or []byte marshals to null, not [] — and there is no tag, no receiver and no analysis that tells the generator which of your handlers has arranged for it not to be nil. So the bridge types the wire: Array<Task> | null. The alternative is a type that is right about intent and wrong about bytes, which fails at tasks.map(...) in the browser, at runtime, in production — the one place TypeScript was supposed to help. A fixed-size array ([N]T) is exempt: it is always there.
You have two ways to deal with the null, and they are both fine.
Handle it on the client, which is what the type is asking for:
const tasks = data.tasks ?? [];
Or make it impossible in Go, which is one line and worth the habit in any handler returning a collection:
tasks := []Task{} // empty, marshals to []
Note that the second one does not change the generated type — borgogen reads the struct, not the handler — so the ?? [] stays. What it buys you is that the null never reaches a client you did not write.
The generated client#
Loaders and actions receive api, a client typed by the map above. The route pattern is the key, path params come from the pattern itself, and the response type follows:
import type { LoaderContext } from "borgo-framework";
export async function loader({ params, api }: LoaderContext) {
const { task } = await api("GET /api/tasks/{id}", { params: { id: params.id } });
return { task };
}
Options are params, query, body, headers and timeout (milliseconds; off by default, because a hard default would break streaming and long-polling callers). A redirect is not followed - it is the api's answer, and following it would carry the request's headers to wherever it points - so a 3xx throws like any other non-2xx. A path param of . or .. throws before anything is sent; {name...} takes a value with slashes and keeps them, and {$} takes none. Non-2xx responses throw ApiError, which carries .status and a size-capped .body:
import { ApiError, redirect, type LoaderContext } from "borgo-framework";
export async function loader({ api }: LoaderContext) {
try {
return { me: await api("GET /api/me") };
} catch (error) {
if (error instanceof ApiError && error.status === 401) return redirect("/login");
throw error;
}
}
What the api wrote with a refusal is on the error. error.body is the response's text — its first 2 kB — and not an object: error.body as { field?: string } compiles and reads undefined from every field, which is how a form ends up showing its own vague sentence where the api had named the input. error.json() is the parsed body, or undefined when it is not JSON at all:
import { ApiError, redirect, type ActionContext } from "borgo-framework";
export async function action({ request, api }: ActionContext) {
const form = await request.formData();
try {
await api("POST /api/login", { body: { username: String(form.get("username")), password: String(form.get("password")) } });
} catch (error) {
if (!(error instanceof ApiError) || error.status >= 500) throw error;
const said = error.json() as { error?: string; field?: string } | undefined;
return { error: said?.error ?? "could not sign in", field: said?.field };
}
return redirect("/");
}
The client forwards the browser's cookies on every call, so Go sees the session during server rendering, and forwards Set-Cookie back — which is what makes a login action actually log the browser in. apiUrl is the escape hatch: the raw base URL, for anything the typed client does not model.
Loader and action code is stripped from client bundles at build time, so server-only imports and secrets used there never reach the browser. CI greps the built assets for a sentinel string to keep that honest.
The same analysis types WebSocket events from borgo.Push calls.
From the browser#
A hydrated page that calls the api itself — on a click, a drop, a keystroke — imports the same client from the package, checked against the same map:
import { ApiError, api } from "borgo-framework";
import { useState } from "react";
export default function Done({ id }: { id: string }) {
const [said, setSaid] = useState("");
const remove = async () => {
try {
await api("DELETE /api/tasks/{id}", { params: { id } });
setSaid("gone");
} catch (error) {
setSaid(error instanceof ApiError ? `refused: ${error.status}` : "offline");
}
};
return <button onClick={remove}>Delete {said}</button>;
}
It is the page's own request: it crosses the proxy, with the session cookie the browser holds and the X-CSRF-Token header attached on unsafe methods, so there is no token to thread through. Rename the route in Go and this line stops compiling, like the loader's. Two differences from the client a loader is handed, both because of where it runs: a failed connection is not retried — it is the visitor's network, not an api restarting beside the render service — and a redirect the api answers with comes back as an ApiError of status 0, since a browser does not let a script read an unfollowed one. apiFetch is still there for what is not a typed route: a streamed response, a Request you built yourself.
On the server the imported api throws, naming the one to use: in a loader or an action, the api the context carries, which reaches Go without crossing the proxy.
Generated files and CI#
Both generated files are committed to your repository, so a fresh clone typechecks before anyone runs dev. Keep them in sync the way this repo does: run the generator in CI and fail if the output differs from what is checked in.
One trap worth knowing: TypeScript skips dot-directories, so .borgo/api-types.d.ts must be named explicitly in tsconfig.json:
{ "include": ["**/*", ".borgo/api-types.d.ts"] }
Every template ships this. If your editor suddenly cannot find the route types, that line is the first thing to check.
Honest limits#
The bridge is static analysis, and it says unknown rather than guessing. What it cannot see:
- helper functions outside your module — a response written by a vendored or third-party package;
- helper functions in another package of your module that are more than three package hops away, or that are methods, or that do not take an
http.ResponseWriter/*http.Request. In-package helpers have none of these restrictions; the hop limit is warned about, the other two are not; - an encoder stored in a variable before use (
enc := json.NewEncoder(w)) rather than the inline chain; - dynamically chosen types:
borgo.JSON(w, s, any(x))types as the static type of the expression, which isany; - anything reached through reflection.
And three things it does not try to be:
- It is not an OpenAPI document. The types are generated for the app's own pages, from the app's own handlers, and there is no export for other consumers. An api that outside parties call wants a contract written for them: keep those routes few and stable, and describe them by hand or with the tool your consumers already use.
- It has no opinion on pagination. A list route takes whatever cursor its query takes and says in its response whether there is more;
borgogives neither a page type nor a helper, because the right shape is the database's. - It does not version the api. The pages and the handlers ship in one deploy and change together, which is what makes the bridge safe; a tab opened before a deploy is sent to load the new page whole. A route other software depends on is versioned the way any Go api is: a new path beside the old one.
The escape hatch is visible, not silent: you get unknown, and a compile error at the point of use, rather than a plausible-looking type that is wrong.
One decoding subtlety, on the Go side rather than the TypeScript one: encoding/json matches field names case-insensitively and lets the last duplicate key win, so {"Username":"a","username":"b"} binds b, and {"USERNAME":…} still matches. borgo.Bind inherits this, because changing it would break the standard library's contract. The practical rule: never validate a JSON body in one layer and act on it in another — bind once, in the Go handler, and validate what that decode produced.