Go owns the request: sessions, auth, the database. The renderer owns
rendering, because that half is React. A server component reaches Go by
calling rpc(), which leaves the renderer as an ordinary POST; a middleware.ts
names guards Go runs before a page renders; a server action the browser calls
is a Go function the build wrote a stub for.
A BAP with Go behind it. There is no JavaScript to write for Go: the app is what the scaffold writes, and the Go side is one package answering the endpoint every backend answers.
go get github.com/rsc-kit/goWiring
In a Go module, init sees go.mod and does the JavaScript half — the
project’s first package.json if it has none, the route tree,
vite.config.ts, .env with RSC_BACKEND and a generated secret, the scripts
— and prints the Go half for you to add. Nothing in the Go module is touched:
bunx rsc-kit@latest init # in the directory with go.mod
bun create rsc-kit@latest my-app --backend=http://127.0.0.1:8080 # or a new appWhat it wrote is two lines, read by vite in development and by the built
server in production:
RSC_BACKEND=http://127.0.0.1:8080
RSC_HOST_CALL_SECRET=… # openssl rand -base64 32 - see Secrets under DeploymentAnd the endpoint, on whatever mux you already have:
reg := rsckit.NewRegistry()
// … Register, Middleware, RegisterAction below …
callback, err := rsckit.NewCallbackHandler(reg, os.Getenv("RSC_HOST_CALL_SECRET"))
if err != nil {
log.Fatal(err) // refuses to exist without a secret
}
mux := http.NewServeMux()
mux.Handle("POST /__rsc/host-call", callback)
// PORT when the platform names one, 8080 otherwise, on every address: a
// host that sends backend urls straight here (backendPaths) reaches it at
// the machine's own address, not loopback. RSC_BACKEND stays
// http://127.0.0.1:8080 - the renderer still calls over loopback.
http.ListenAndServe(":"+cmp.Or(os.Getenv("PORT"), "8080"), mux)It listens on every address, not loopback alone. Once an app names
backendPaths, a proxy in front may send
those urls straight to the backend at the machine’s own address, and a
backend bound to 127.0.0.1 can’t be reached. The secret is what guards
the host-call endpoint, and the proxy refuses it from outside
(deployment).
The renderer forwards any url its route tree does not own to RSC_BACKEND,
so a Go route on that mux — /login, a webhook, an upload — is reachable at
the renderer’s origin too.
When a page route would match it
One url, one owner: the route tree has it, or the backend does. A dynamic route
at the root, [team]/[app], has every url of two segments, the backend’s
/gitlab/connect among them. It renders and says notFound(), and a page that
said that is the app’s 404, so it is not handed on. Sign-in and an OAuth
callback become a team called gitlab.
Name the prefixes Go owns, and they are forwarded before any page is asked:
rscKit({ backendPaths: ['/auth', '/github', '/gitlab'] })Each is a prefix at a segment boundary: /auth is /auth and everything under
it, for every method, and never /authors. A team called auth is then
unreachable, which is the price of the name. / and the renderer’s own /_rsc
are refused where they are written, and with no backend where the server runs
such a url is the app’s not-found page. A test reaches it as it does any
backend url, with createTestApp({ backend }).
In the browser a named prefix is never a page. A Link, visit() or
redirect('/gitlab/connect') to it loads the document and is never
prefetched, so the Go route may answer with a redirect to another site, as an
OAuth start does — see redirects.
Running it locally
Two processes: the Go program, and Vite, which is the renderer in
development. Run Go with RSC_DEBUG=1, so a failure says where in Go it
happened:
RSC_DEBUG=1 go run . # the backend, on 127.0.0.1:8080
bun run dev # the renderer; open its addressNever set RSC_DEBUG in production: a trace names your files.
Environment variables
| Variable | Read by | What it is |
|---|---|---|
RSC_BACKEND |
the renderer | Where the Go endpoint is, e.g. http://127.0.0.1:8080. Falls back to APP_URL. Read from .env by vite, and from the environment by the built server; the url forwarding is fixed at build time. |
RSC_HOST_CALL_SECRET |
both | The shared secret. The renderer sends it; your Go code passes it to NewCallbackHandler. Without it neither side talks. |
RSC_HOST_CALL_SECRET_PREVIOUS |
Go | The secret being rotated away from, answered as well while set, so a rotation refuses no call. Rotating one. |
RSC_HOST_CALL_PATH |
the renderer | The endpoint’s path. Default /__rsc/host-call. |
RSC_DEBUG |
Go | 1 sends a failure’s trace with its answer. Development only. |
RSC_TRUST_FORWARDED |
the renderer | 1 passes the visitor’s X-Forwarded-For through to Go. Only behind a proxy you control that writes it. |
The Go adapter reads only RSC_DEBUG itself. The secret reaches it through
your code, as above.
Reading from Go
Register an ordinary Go function with Handle, and its types reach the app:
reg.Handle("Orders.recent", func(ctx context.Context, limit int) ([]Order, error) {
// The visitor's cookie, forwarded from the page request: this runs as
// them, not as nobody.
return db.RecentOrders(ctx, rsckit.HeadersFrom(ctx).Get("Cookie"), limit)
})const orders = await rpc('Orders.recent', 5) // Order[]; rpc('Orders.recent', 'five') fails the typecheck- Any parameters, in order.
rpc()’s arguments are bound to the function’s parameters positionally, whatever JSON can carry: numbers, strings, structs, slices, maps. A leadingcontext.Contextis the call’s. - Optional and variadic. A trailing pointer parameter may be left out
and is
nil; a variadic one takes the rest. - What it returns. A value and an error, only an error, or only a value.
- Types for the app. The parameter and result types are written to
rsc-host.jsonas JSON Schema. The build turns each struct into a TypeScript interface in theRscHostnamespace, by itsjsontags:omitemptyis optional, a pointer is| null,time.Timeis a string. A type with its ownMarshalJSONisunknown, since its shape is its own, unless it says what it writes with aJSONSchemamethod (below). - Empty, not null. A nil slice or map in the result is sent as
[]or{}, as its type says; only a nil pointer isnull. - Who is asking.
rsckit.ClientIP(ctx)andrsckit.ClientUserAgent(ctx)are the visitor’s address and browser, sent by the renderer and believed because the call carried the secret.r.RemoteAddrandr.UserAgent()would be the renderer’s own, the same for every visitor. Both are empty when there is no visitor: a build, or a page stored for everyone.
A type that writes its own JSON
A MarshalJSON says nothing about the shape it writes, so the build has nothing
to type it by. Give the type a JSONSchema method that says it:
type Money struct{ cents int64 }
func (m Money) MarshalJSON() ([]byte, error) { … } // "12.50"
func (Money) JSONSchema() rsckit.Schema { return rsckit.Schema{"type": "string"} }Money is then string wherever it appears, *Money is string | null and
[]Money is string[], with no narrowing helper in the page. The method is
called once on the zero value, at startup, with a value or a pointer receiver.
Its schema is used as it stands, so keep to what the build reads: type (one
name), items, properties with required, additionalProperties, enum
and anyOf. Anything else is unknown. It needs github.com/rsc-kit/go
v0.11.0.
Register still takes the untyped form, binding by hand:
reg.Register("Orders.recent", func(ctx context.Context, args rsckit.Args) (any, error) {
var limit int
if err := args.Bind(&limit); err != nil {
return nil, err
}
// The visitor's cookie, forwarded from the page request: this runs as
// them, not as nobody.
session := rsckit.HeadersFrom(ctx).Get("Cookie")
return db.RecentOrders(ctx, session, limit)
})export default async function Orders() {
const orders = await rpc<Order[]>('Orders.recent', 5)
return <ul>{orders.map((o) => <li key={o.id}>{o.number}</li>)}</ul>
}args.Bind decodes the positional arguments rpc() was given; too few is an
error, extra ones are ignored. Whatever the function returns is encoded as
JSON and decoded on the other side as whatever rpc<T>() was told: an
untyped function is unknown until you say.
When it fails
In development, set Debug on the callback handler, or RSC_DEBUG=1 in the
environment, and a failure says where in Go it happened: a panic sends the
frames it unwound, an error the chain it wraps. The renderer shows them under
its own stack, as the error’s cause:
Error: Host call "Orders.recent" failed: host function panicked: runtime error: slice bounds out of range
Caused in the backend by Backend panic(runtime.boundsError): …
at backend/main.go:64 main.main.func3A server action that fails this way opens Vite’s error overlay on the page in development, with the same type and frames; frames from the module cache are counted rather than listed. Never in production: a trace names your files.
Refusing
Return a value and it is the result. Return one of these and the render is told what happened, rather than handed a 500:
| return | the render gets |
|---|---|
rsckit.InvalidField("name", "…"), rsckit.Invalid(map) |
422, each message under its input on the form that submitted |
rsckit.Unauthenticated() |
401, the engine’s own authentication error |
rsckit.Unauthorized("…") |
403 |
rsckit.Redirect("/login") |
the browser goes there |
rsckit.Refuse(429, "slow down") |
that status, kept. An action shows the message to the visitor as written |
rsckit.RefuseWith(409, "still in use", data) |
the same, with data the page can act on: see server actions |
any other error |
500, with the message |
Wrapped errors still answer as what they are — errors.As finds the refusal
inside fmt.Errorf("…: %w", err) — and a panic becomes an error for that one
call rather than taking the server down.
Route middleware
export const middleware = ['auth', 'can:manage-orders', 'throttle:60,1']reg.Middleware("auth", func(ctx context.Context, _ string) error {
if !signedIn(rsckit.HeadersFrom(ctx)) {
return rsckit.Redirect("/login")
}
return nil
})
reg.Middleware("can", func(ctx context.Context, ability string) error {
if !allowed(ctx, ability) {
return rsckit.Unauthorized("you may not " + ability)
}
return nil
})The renderer sends the list before anything at or below admin/ renders —
including a page it froze at build time, before the file is served. A guard
receives what follows the colon in its name ("manage-orders", "60,1",
""); guards run in order and stop at the first refusal. A name nothing is
registered for refuses rather than passes: a declared check that silently
does not happen is the failure this exists to prevent.
A guard is asked about a page, not about the call that carries it:
reg.Middleware("owns-order", func(ctx context.Context, _ string) error {
page, _ := rsckit.PageFrom(ctx) // the url the visitor asked for, and the route's params
if !owns(ctx, page.Params["order"]) {
return rsckit.Unauthorized("not your order")
}
return nil
})
reg.Middleware("throttle", func(ctx context.Context, rule string) error {
if !limiter.Allow(rsckit.ClientIP(ctx), rule) { // the visitor's address, not the renderer's
return rsckit.Refuse(429, "slow down")
}
return nil
})page.URL is under the public host and scheme when a proxy forwarded them,
so a signature checks against the link the visitor followed; it is empty
during a build. page.Params holds only what the route’s segments bound,
never the query. ClientIP is read only once the secret matched, and is
empty when there is no visitor. One page load asks once, so a throttle
counts it once.
Server actions
reg.HandleAction("ordersCancel", "Orders.cancel", func(ctx context.Context, id int) error {
if err := orders.Cancel(ctx, id); err != nil {
return err
}
rsckit.Revalidate(ctx, "orders")
return nil
})
// The actions and every function, for the build: stubs, and rpc()'s type.
reg.WriteManifest("rsc-host.json")'use client'
import { ordersCancel } from '../../server-actions.generated'
export function CancelButton({ id }: { id: number }) {
return <button onClick={() => ordersCancel(id)}>Cancel</button>
}The stub is typed from the Go function, plus the one answer Go can give it that
is not its result: ordersCancel(id: number): Promise<void | Redirected>. An
action that returns rsckit.Redirect("/login") (or a guard that does, for an
expired session) resolves the call with { redirected } once the browser is on
its way, so narrow with isRedirected before reading a value or reporting
success. A call the backend refuses (rsckit.Refuse(429, "slow down")) is not a
result at all: awaited directly the stub rejects with an ActionRefusedError
carrying the message and the status, and <Form> shows it as formError. An
input the backend refuses (rsckit.Invalid) rejects with a
ServerValidationError, whose .fieldErrors and .formErrors are the
messages. Only a redirect resolves. See Redirects.
An action that signs someone in sets the session cookie with
rsckit.SetCookie(ctx, &http.Cookie{...}), and the renderer puts it on the
page’s response.
Tag the structs a form posts with json names. An untagged field goes into
the manifest under Go’s name, Type, while a form posts type and the backend
refuses under type, so error('type') is a type error on a bound stub. A tag
(json:"type") gives the form, the manifest and the refusal one spelling.
Where tags are not an option, fields adds the other names on top.
A form can post to an action directly, <Form action={ordersCreate}>, and its
fields arrive as the struct parameter: the first, or the one after the
arguments you bound. An action scoped to a team, func(ctx, team string, in NewApp),
is <Form action={appsCreate.bind(null, team)}>. Numbers and booleans are
coerced by the struct’s types and a repeated field is a slice.
An admin resource takes the generated actions in place of a schema, its create
func(ctx, in ProductInput) and its update the record’s key after the struct,
func(ctx, in ProductInput, id string). See
the admin guide. A list too
big to count pages by cursor: answer a struct tagged json:"rows",
json:"next" and json:"prev", and read the cursor from the query’s cursor
(pages by count, or by cursor).
Revalidate names a section or page, and the answer to
the action carries it re-rendered rather than the browser being told to ask
again.
Have Vite write the manifest, so it cannot go stale: give the program a flag that writes it and exits, and name the command in the config. It runs as dev and every build start, and a build fails if it does:
rscKit({ hostManifest: { command: ['go', 'run', '.', '-manifest', '../rsc-host.json'], cwd: 'backend' } })The manifest also lists every registered function, so rpc() is typed by
the names Go holds and rpc('Orders.recnet') fails the typecheck. Tests
answer these functions without Go running:
Testing it.
Saying data changed
An action can say what it changed. A webhook, a job or another visitor’s action cannot reach the tab that is showing the data - so a section names what it depends on, and Go says when that changed, from anywhere with a context:
export default section('repos', Repos, { refreshOn: ({ params }) => [`team:${params.team}:repos`] })// in the GitHub webhook handler
reg.Changed(ctx, "team:"+teamID+":repos")Every open tab showing the section refreshes it, the moment the webhook
lands, with nothing polling. The registry answers __rsc.changed by holding
the renderer’s ask until a version moves - woken at once by a Changed in
this process, checking the store every rsckit.ChangedPoll (1s) for one made
by another instance.
Versions live in a VersionStore. The default is in memory, which is one
instance; with more than one, a webhook lands on whichever instance the
balancer picked, so give them all the same store:
// CREATE TABLE rsc_versions (name TEXT PRIMARY KEY, version BIGINT NOT NULL)
reg.Versions(&rsckit.SQLVersions{DB: db, Placeholder: rsckit.Dollar}) // Postgres; nil Placeholder is "?"To hear another instance’s change at once instead of within the second - and
stop reading the store while nothing changes - set Notify so each bump
sends a pg_notify, and run a listener with WakeOn. The adapter depends on
no driver, so the listener is yours; with pgx:
reg.Versions(&rsckit.SQLVersions{DB: db, Placeholder: rsckit.Dollar, Notify: "rsc_versions"})
reg.WakeOn(ctx, func(ctx context.Context, connected, wake func()) error {
conn, err := pool.Acquire(ctx)
if err != nil {
return err
}
defer conn.Release()
if _, err := conn.Exec(ctx, "LISTEN rsc_versions"); err != nil {
return err
}
connected()
for {
if _, err := conn.Conn().WaitForNotification(ctx); err != nil {
return err
}
wake()
}
})A listener that drops runs again with backoff, and the poll covers the gap. Through PgBouncer in transaction mode, connect the listener straight to Postgres. One instance needs none of this.
Anything with a Bump and a Versions fits. Set RSC_SIGNING_SECRET for the renderer, the same on every instance:
it signs the names a page hands the tab, and is not the host-call secret.
Generating and rotating both: Secrets. Sections
has the whole picture.
Pages kept between requests
export const revalidate = 60 keeps a page and refreshes it behind the visitor,
and reg.Changed(ctx, "posts") renders it again at once on every instance, when
it read that tag through cache(). A kept page calls Go as nobody: no Cookie,
no Authorization. With CDN_PURGE_URL set, Changed purges the CDN as
well; reg.SetPurger replaces it. Call it after your transaction commits.
ISR has the whole of it.
Public forms
A contact form or a sign-up anyone may fill in is an action that takes a struct, and a few lines of TypeScript handing that action to a form. There is no schema to write: the fields and the browser’s checks come from the struct.
1. The action. Its json tags are the field names, a validate tag adds
what the browser can check, and rsckit.InvalidField is a refusal under that
field:
type ContactInput struct {
Name string `json:"name" validate:"required,min=2"`
Email string `json:"email" validate:"required,email"`
Topic string `json:"topic" validate:"required,oneof=sales support"`
Message string `json:"message" validate:"required,min=10,max=2000"`
}
reg.HandleAction("contactSend", "Contact.send", func(ctx context.Context, in ContactInput) error {
if blocked(in.Email) {
return rsckit.InvalidField("email", "That address is blocked.")
}
return messages.Insert(ctx, in)
})The tag is read, never run: check what was sent in the function too, since a post need not come from a browser.
2. The form. The build generates contactSend from the manifest, and
bunx rsc-kit make:form contactSend writes the form around it:
import { defineBlueprint } from '@rsc-kit/press/forms'
import { shadcn } from '@rsc-kit/press/shadcn'
import { contactSend } from '../server-actions.generated'
export const contact = defineBlueprint({
name: 'contact',
actions: { create: contactSend },
fields: { message: { type: 'textarea' } },
theme: shadcn,
done: 'Thanks - we will be in touch.',
})Then place it in a page, which stays static:
import { contact } from '../../forms/contact'
export default function ContactPage() {
return <contact.Form />
}oneof draws a select, and a field is required unless its json tag says
omitempty. required_if=Topic support shows the field only while topic is
support. Blueprints has every tag that is read.
It needs @rsc-kit/press 0.30.52 and github.com/rsc-kit/go v0.16.0.
Production
bun run build and bun run start with the same two variables in the
renderer’s environment. Put the renderer in front and restrict
/__rsc/host-call at the web server, as Laravel’s page
shows; a Go worker is held for the length of a host call, never a render.
Or put Go in front: rsckit.NewRenderer(url) is a streaming reverse proxy
to the renderer, and rsckit.NewHandler(renderer, callback, path) routes
the callback path to the endpoint and everything else through it. Both sides
mark what they forward, so a url neither owns is a 404 rather than a loop.
On a Worker, the two variables are a var and a secret in wrangler.json,
and the Go process has to be reachable from Cloudflare’s network — an
https origin behind the secret and, ideally, an allow-list, since loopback
is not an option there.
The runnable version is
examples/go-backend
in the repository: bun run backend, bun run dev, open the renderer.