Skip to content
Complete API reference
ReferenceComplete API reference
On this page

Complete API reference

The public framework surface in one place. Follow the linked guides for examples and behavior in context.

Package entry points

EntryExports and purpose
goribuLink, NavLink, navigate, Form, Stylesheet, ClientEntry, and UI/metadata types.
goribu/serverdefineConfig, low-level createApp, and request, response, config, data, and middleware types.
goribu/clientSide-effect browser bootstrap. Import once from the client entry.
goribu/vitegoribu() Vite plugin for development and build integration.

Keep server runtime imports out of browser-reachable components. Type-only imports do not create runtime dependencies.

Route exports

ExportContract
defaultReact page component. Receives the props passed to res.render().
GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS(req, res) => ResponseResult, optionally async.
metaMetadata object or synchronous ({ props, url }) => metadata.
prerenderOptional boolean. False requires Worker rendering; true requires successful static output.

A page has an implicit GET when no explicit GET exists. Goribu derives HEAD and OPTIONS when needed. Special files are _document, _404, _500, and _middleware. A middleware default export is one function or an array of functions; return nothing to continue or a response result to stop.

Request

Handlers and middleware share one request object.

MemberType or result
methodHTTP method string.
pathURL pathname string.
paramsNamed dynamic segments, each a string.
queryURLSearchParams.
headersHeaders.
envWorker environment and bindings.
cookiesCookie jar described below.
d1D1 query facade described below.
kvKV facade described below.
body()Promise of an object, FormData, or string, according to Content-Type.
rawBody()Promise of Uint8Array bytes, sharing the cached read with body().
waitUntil(promise)Register background work with the Worker execution context.

JSON bodies must have an object root. URL-encoded repeated fields become arrays; multipart returns FormData; text returns a string. Empty or unsupported bodies return an empty object. Malformed supported bodies produce 400. See Request handlers.

Response

Return one terminal result from every handler. status() and headers() configure the builder and return it for chaining.

MethodContract
status(code)Set the HTTP status. Default is 200, except helper-specific defaults.
headers(object)Add header strings or arrays of strings.
render(props = {})Render this route's page with serializable object props.
json(data)JSON response.
text(body)Plain text response.
invalid(errors, status = 422)Field-error object or string mapped to root.
redirect(location)Redirect with default status 303. Explicit allowed statuses: 301, 302, 303, 307, 308.
notFound(props = {})Render the 404 page with optional props.

A handler cannot return a raw Response or JSX. Bodyless statuses reject a body. Enhanced Form outcomes are JSON, invalid, redirect, and same-page render. See Forms.

Cookies

MethodContract
req.cookies.get(name)Incoming string value or null.
req.cookies.set(name, value, options?)Queue a Set-Cookie header.
req.cookies.delete(name, { path?, domain? }?)Queue deletion using matching scope.

Options are domain, path, expires (Date), maxAge (seconds), httpOnly, secure, and sameSite (Lax, Strict, or None, also lowercase). Cookie security options have no implicit defaults. Encode structured or Unicode data before setting it.

APIExtra props or arguments
LinkNormal anchor props, replace = false, prefetch = true.
NavLinkLink props plus end = false and a string or ({ isActive }) => className callback. Goribu owns aria-current.
navigate(target, { replace? }?)Returns Promise<void>. Requires a browser and an HTTP(S) destination.

NavLink matches pathname boundaries, ignoring query and hash. Root is exact-only. Link enhancement preserves native behavior for external links, downloads, modifier clicks, and same-document anchors. See Links & navigation.

Form

Import Form from goribu. It accepts ordinary form props except that Goribu owns encoding and defines its method/action behavior.

PropContract
methodRequired: get, post, put, patch, or delete, in upper or lower case.
actionDefaults to the current URL when submitted.
childrenReact children or ({ pending, errors, data }) => children.
replaceReplace history during enhanced navigation; defaults false.
resetReset controls after successful JSON or same-page render; defaults false.
onSubmitRuns first and may cancel with preventDefault().
onResultRuns after state/render commit and before redirect navigation.
refReceives the HTML form; extended-method forms expose it after hydration.

State starts as { pending: false, errors: null, data: null }. errors is an object of message strings. onResult receives { ok: true, data?, response? } or { ok: false, errors, data?, response? }.

Do not pass encType. GET/POST work natively; PUT/PATCH/DELETE require hydration. A submitter's formMethod supports only GET/POST, so declare extended methods on Form itself. See Forms.

Metadata

meta is a RouteMetadata object or synchronous function receiving { props, url }, where url is a URL object.

FieldShape
titleString. Missing title produces an empty managed title.
description, canonical, robotsStrings.
metaArray of { name, content } or { property, content }.
linksArray of descriptors with required rel and href.

Optional link fields are as, type, media, sizes, hrefLang, crossOrigin, referrerPolicy, fetchPriority, imageSrcSet, imageSizes, and color, all strings. Unknown fields, event handlers, async results, and duplicate canonical/description representations are rejected.

Document and browser entry

DocumentProps contains { children, head, nonce? }. Keep children under #root and head inside the document head.

Stylesheet() renders the current graph's styles and takes no public props. ClientEntry({ src, nonce? }) renders the browser entry; src is the development fallback and production resolves its built asset. Keep one of each in a custom Document.

Import goribu/client once to hydrate and install navigation and Forms. Browser environment values use only import.meta.env.PUBLIC_*. See Rendering.

D1

Use the req.d1 tagged template in handlers or middleware. Values become parameters. A statement is lazy until a terminal runs.

APIResult or purpose
.get()Promise of first row or null.
.all()Promise of row array.
.value()Promise of first column of first row or null.
.run()Promise of { changes, lastRowId }.
req.d1.atomic(statements)Atomic batch of unexecuted statements; entries have rows, changes, and lastRowId.
req.d1.unsafe(text, params?)Statement from application-controlled SQL structure and explicit values.
req.d1.freshQuery facade that starts each tagged terminal at the primary.
req.d1.publicQuery facade without the visitor's bookmark.
.sessionSession object for integrations; raw binding when replication is disabled.
.bindingPlain Cloudflare D1Database binding.

Tagged values support strings, numbers, booleans, null, ArrayBuffer, ArrayBufferView, and non-empty arrays of these scalar values. Unsafe parameters are a flat scalar array. Undefined, dates, objects, nested/empty arrays, functions, symbols, and bigints are rejected.

Default queries use the visitor session when replication is enabled. Fresh/public cannot be chained, and atomic belongs to the default facade. A batch rebinds passed statements to its own session. See D1.

KV

APIOptions
get(key, options?)type: text/json/arrayBuffer/stream; cacheTtl; metadata: boolean.
put(key, value, options?)expiration, expirationTtl, JSON-serializable metadata.
delete(key)No options.
list(options?)prefix, limit, cursor.

Reads return text or null by default. JSON is parsed only when requested. Metadata reads return { value, metadata, cacheStatus }; missing value and metadata are null. Lists return keys, list_complete, and an optional cursor. Await all operations.

Keys for get/put/delete are non-empty strings. JSON writes need explicit stringification. There is no bulk-get array, string shorthand for options, or separate getWithMetadata method. KV is eventually consistent, including cached misses. See KV store.

Configuration

defineConfig(config) validates and returns a frozen configuration. The fields are name, compatibilityDate, optional compatibilityFlags, database, kv, and responseHeaders.

Database is { type: "d1", name, replication? }; KV is { name }. The header callback receives { request, env, mode, nonce } and returns a plain object of string or string-array values synchronously. See Configuration for defaults, allowed names, environment files, and header restrictions.

CLI

Run from the application directory. The app scripts wrap the installed Goribu CLI.

CommandBehavior
pnpm devLocal Worker development with Vite.
pnpm buildProduction bundles and static output.
pnpm checkRead-only production deployment plan.
pnpm run deployAuthenticate, build, provision, migrate, and upload.
pnpm exec goribu migrate:new <name>Create the next numbered SQL migration.
pnpm exec goribu migrateApply pending local migrations.
pnpm exec goribu migrate:statusRead migration status.
pnpm exec goribu migrate:downRoll back one migration.
pnpm exec goribu migrate:seedRun local seed.sql; cannot target production.
pnpm exec goribu --helpPrint usage.
pnpm exec goribu --versionPrint the installed version.

Migrate, status, and down accept --remote for production. Dev, build, check, and deploy take no arguments. Failures exit non-zero. pnpm typecheck is the TypeScript starter's separate tsc --noEmit script.

pnpm create goribu@latest <name> creates an app. Scaffolder options are --js, --help, and --goribu-tarball <path> for a matching local framework archive. It never installs, authenticates, or deploys for you.

TypeScript

Use import type. Types annotate behavior; they do not validate request input or stored JSON.

EntryPublic types
goribuLinkProps, NavLinkProps, FormProps, FormMethod, FormState, FormResult, FormErrors, DocumentProps, RouteMetadata, Meta.
goribu/serverApplicationConfig, DefinedConfig, ResponseHeaders, CookieOptions, Cookies, D1Value, D1WriteResult, D1Statement, D1Queries, D1, KV, GoribuRequest, GoribuResponse, ResponseResult, Handler, Middleware, ServerErrorProps, WorkerContext, WorkerApp, RouteManifestEntry, ClientAsset, AppOptions.

Useful generics include Handler<Props, Env, Params>, Middleware<Env>, Meta<Props>, Form<Data>, req.d1<Row>, and req.kv.get<Value>(key, { type: "json" }). Request body values still need narrowing and validation.

Low-level app creation

createApp(options) from goribu/server returns a Worker app with fetch(request, env, ctx): Promise<Response>. Normal applications use goribu() in Vite; the build supplies the route graph and calls this API for them.

Required options are manifest, modules, and errorPages. Optional fields are documentId, middlewareByRoute, mode, clientAssetManifest, clientAssetBase, and applicationConfig. These describe compiled routes, error pages, assets, and validated config; they are not additional fields for goribu.config.js.