Routing
A page is a file
An app's URLs come from the files under its routes/ directory, as in SvelteKit. A +page.rocx is the page at its directory's path, wrapped by the +layout.rocx files above it. A +server.roc answers HTTP requests at its path, and +error.rocx is shown where nothing answers. Every page gets a typed path and every endpoint a typed function, so a link to a missing page, or a call to a missing endpoint, fails to compile.
The files#
This site's route files, one for every page you can open here:
+error.rocx # where no page is
+layout.rocx # around every page
+middleware.roc # around every request
+page.rocx # /
(members)/+middleware.roc # around every route in it and below it
calls/+page.rocx # /calls
components/+page.rocx # /components
ecosystem/+page.rocx # /ecosystem
examples/+page.rocx # /examples
openapi.html/+server.roc # /openapi.html, its endpoints
openapi.json/+server.roc # /openapi.json, its endpoints
platform/+page.rocx # /platform
rocx/+page.rocx # /rocx
routing/+page.rocx # /routing
safety/+page.rocx # /safety
showcase/+page.rocx # /showcase
syntax/+page.rocx # /syntax
tooling/+page.rocx # /tooling
(members)/members/+page.rocx # /members, behind Middlewares.member
api/calls/+server.roc # /api/calls, its endpoints
api/facts/+server.roc # /api/facts, its endpoints
api/planner/+server.roc # /api/planner, its endpoints
api/reader/+server.roc # /api/reader, its endpoints
api/shelf/+server.roc # /api/shelf, its endpoints
api/shout/+server.roc # /api/shout, its endpoints
ecosystem/admin/+page.rocx # /ecosystem/admin
ecosystem/ai/+page.rocx # /ecosystem/ai
ecosystem/audio/+page.rocx # /ecosystem/audio
ecosystem/auth/+page.rocx # /ecosystem/auth
ecosystem/charts/+page.rocx # /ecosystem/charts
ecosystem/chat/+page.rocx # /ecosystem/chat
ecosystem/crypto/+page.rocx # /ecosystem/crypto
ecosystem/email/+page.rocx # /ecosystem/email
ecosystem/forms/+page.rocx # /ecosystem/forms
ecosystem/guard/+page.rocx # /ecosystem/guard
ecosystem/headless/+page.rocx # /ecosystem/headless
ecosystem/intl/+page.rocx # /ecosystem/intl
ecosystem/jobs/+page.rocx # /ecosystem/jobs
ecosystem/local/+page.rocx # /ecosystem/local
ecosystem/markdown/+page.rocx # /ecosystem/markdown
ecosystem/mcp/+page.rocx # /ecosystem/mcp
ecosystem/otel/+page.rocx # /ecosystem/otel
ecosystem/posthog/+page.rocx # /ecosystem/posthog
ecosystem/presence/+page.rocx # /ecosystem/presence
ecosystem/push/+page.rocx # /ecosystem/push
ecosystem/qr/+page.rocx # /ecosystem/qr
ecosystem/slack/+page.rocx # /ecosystem/slack
ecosystem/storage/+page.rocx # /ecosystem/storage
ecosystem/stripe/+page.rocx # /ecosystem/stripe
ecosystem/testing/+page.rocx # /ecosystem/testing
ecosystem/tools/+page.rocx # /ecosystem/tools
ecosystem/vibrate/+page.rocx # /ecosystem/vibrate
ecosystem/video/+page.rocx # /ecosystem/video
ecosystem/virtual/+page.rocx # /ecosystem/virtual
ecosystem/websocket/+page.rocx # /ecosystem/websocket
examples/board/+page.rocx # /examples/board
examples/checkboxes/+page.rocx # /examples/checkboxes
examples/echo/+page.rocx # /examples/echo
examples/hello/+page.rocx # /examples/hello
examples/journal/+page.rocx # /examples/journal
examples/js-framework-benchmark/+page.rocx # /examples/js-framework-benchmark
examples/notes/+page.rocx # /examples/notes
examples/plate/+page.rocx # /examples/plate
examples/pomodoro/+page.rocx # /examples/pomodoro
examples/quiz/+page.rocx # /examples/quiz
examples/rack/+page.rocx # /examples/rack
examples/sqlite-vs-turso/+page.rocx # /examples/sqlite-vs-turso
examples/tasks/+page.rocx # /examples/tasks
examples/uptime/+page.rocx # /examples/uptime
members/join/+middleware.roc # around every route in it and below it
members/join/+page.rocx # /members/join, behind Middlewares.visitor
platform/actors/+page.rocx # /platform/actors
platform/browser/+page.rocx # /platform/browser
platform/crypto/+page.rocx # /platform/crypto
platform/database/+page.rocx # /platform/database
platform/http/+page.rocx # /platform/http
platform/kv/+page.rocx # /platform/kv
platform/live/+page.rocx # /platform/live
platform/reference/+page.rocx # /platform/reference
platform/server/+page.rocx # /platform/server
platform/settings/+page.rocx # /platform/settings
(members)/api/members/+server.roc # /api/members, its endpoints, behind Middlewares.member
api/count/[to]/+server.roc # /api/count/[to], its endpoints
api/echo/[message]/+server.roc # /api/echo/[message], its endpoints
api/members/join/+server.roc # /api/members/join, its endpoints
api/members/leave/+server.roc # /api/members/leave, its endpoints
api/planner/move/+server.roc # /api/planner/move, its endpoints
api/shout/[word]/+server.roc # /api/shout/[word], its endpoints
api/platform/live/lobby/+server.roc # /api/platform/live/lobby, its endpoints| File | What it is |
|---|---|
routes/+page.rocx | the page at / |
routes/blog/+page.rocx | the page at /blog |
routes/blog/[slug]/+page.rocx | the page at /blog/anything, given params.slug |
+layout.rocx | wraps every page in its directory and below it |
routes/+error.rocx | what a browser sees at a path nothing answers (404), and when a page fails |
routes/api/blog/+server.roc | the endpoints at /api/blog, which the page at /blog reads: get!, post!, put!, patch! and delete!; events!, a stream of events; channel!, a channel pages subscribe to; respond!, every other method |
routes/admin/+middleware.roc | the middleware around every page, endpoint and channel in admin/ and below it (below); routes/+middleware.roc runs around every request |
routes/(members)/… | a group: a directory in parentheses adds nothing to the path, so files at different paths share its middleware and layout |
routes/.well-known/… | routed, as RFC 8615 asks; any other directory whose name starts with a dot is skipped |
Each directory names one part of the path, in lower case (blog, getting-started, feed.xml), or a param in brackets ([slug]). It may start with an underscore, for a path another service names (_verify is verify in Api and Paths). rocx build refuses other names, and says why.
A page#
A route file has no module header: imports, then definitions. A page defines view!, the component that renders it, and may define meta, a record its layouts are given. On this site, meta holds the title, the description and the table of contents on the right:
import pf.Html
import ../../Demos/Birds
import ../../Demos/Snake
import ../../Demos/Timers
import ../../Ui/Heading
import ../../Ui/Callout
import ../../Ui/Code
import ../../Generated/Sources
import ../../Generated/Paths
import ../../Ui/Feature
import ../../Ui/FeatureGrid
import ../../Ui/Note
import ../../Ui/PageHero
import ../../Ui/Demo
meta = {
title: "Showcase",
description: "Snake, a flock of bouncing Roc birds and the browser's timers: components Roc runs frame by frame in your browser, compiled to WebAssembly, with sound from a handler.",
toc: [
{ id: "snake", label: "Snake" },
{ id: "flock", label: "A flock of Roc birds" },
{ id: "how", label: "How they work" },
{ id: "sound", label: "Sound, from a handler" },
…view!is given the page's params:view! = |{ params }| …, a record of strings, or of the types it gives them ({}without params; write|_|). A page is an effectful component: its body runs once, and it may make signals.- Its data comes from endpoints. A page isn't given the request. It reads its location with
Router.location!({})and its data withApi.get_….read!(), answered by the server as it renders (talking to the server). What middleware knows, such as who is signed in, comes the same way, from an endpoint behind it (below). - Imports are relative to the file. This one is two directories down, so the site's components are under
../../Ui. - A route file can define components of its own (
Board := [].{ view! = … }) and use them as<Board />. Put them before or after the file's definitions, not between: rocx writes them as types beside the page's module, so theirview!isn't taken for the page's (an example). They can use the file's other definitions; a name a component defines itself is its own.
Layouts#
A +layout.rocx wraps every page in its directory and below it. Layouts nest, the outermost first. The root one, routes/+layout.rocx, renders the whole document (<html>, <head>, <body>); without one, an app gets a plain document. A layout's view! is given:
children: the page, or the next layout in;params: the ones its directory names (routes/[lang]/+layout.rocxgetslang; the root layout gets{});meta: the page'smeta. Every page under a layout that takes it must give it the same type;rocx buildreports a page whosemetahas other fields, or none. Where no page is, the error page'smetastands in.
On navigation, a layout stays, with its state, while its file and its own params are the same (navigating). This site's one layout, the document around every page, reads the location where it uses it, so it is kept:
import pf.Html
import pf.Router
import pf.Store
import ../Facts
import ../Ui/Nav
…
import ../Generated/Paths
…
## The document around every page: the bar, which goes from one part of the docs to the other,
## this part's pages, what is on this one, and the footer with what the build measured. `meta` is the
## page's (its title, description and contents); where it is, the location's (`Router.location!`);
## the facts the build measured, the server's (`Facts.facts!`). Each part is a component of the
## site's design system (site/Ui), with its stories. Where it is is read where it is used, each
## part of it a selection of a store of the path (D-053), which tells its readers only when that
## part changes: so a navigation keeps the layout (D-040), the sidebar is kept within a part, and
## the bar, the pager and what is on the page are made again only when what they show changes.
view! = |{ meta, children, .. }| {
facts = Facts.facts!({})
at = Store.of(|| Router.location!({}).path)
…
# The front page is Roc Solid's, in no part: no sidebar, and no part current in the bar.
landing! = || at.get!(Nav.is_landing)Params, and typed links#
A directory in brackets is a param: routes/blog/[slug]/+page.rocx is the page at any /blog/…, and its view! is given params : { slug : Str }. A param is a string, decoded from the URL, unless a handler or the page gives it another type (below). Fixed parts are tried before params, so /blog/new can be a page of its own beside /blog/[slug]. A directory may name a file, with dots between letters or digits: routes/sitemap.xml/+server.roc answers /sitemap.xml, and its names drop the dot (Api.get_sitemap_xml). A page from the app the tests build:
import pf.Html
import ../../../Generated/Paths
## A post, by its slug.
view! = |{ params }|
<>
<h2>Post {params.slug}</h2>
<a href={Paths.blog_slug({ slug: "other" })}>The other one</a>
</>rocx also writes Paths: a string for each page without params, and for each page with them, a function that encodes them into the URL. Link through it, and a link to a missing page, or with the wrong params, fails to compile at your line (Paths.blog_slug({ slg: "x" }): Maybe slg should be slug?). Paths.all lists the pages without params.
## Written by rocx build from the app's routes/: a path for every page, so a link to a page that
## isn't there doesn't compile. Edit the routes, not this file.
import pf.Server
Paths := [].{
## /, from routes/+page.rocx
root : Str
root = "/"
## /blog, from routes/blog/+page.rocx
blog : Str
blog = "/blog"
## /blog/[slug], from routes/blog/[slug]/+page.rocx
blog_slug : { slug : Str } -> Str
blog_slug = |params| "/blog/${Server.encode_segment(params.slug)}"
## Every page with no params: what a static build writes.
all : List(Str)
all = ["/blog", "/"]
}Typed params. A handler's annotation may give a param a type other than Str: a number, Bool, or a union of tags written out ([Draft, Live]). A page says its own with a type in the file, Params : { id : I64 }, as its endpoints are under api/ and rocx never reads a page's types from another directory. The router reads the path's part as that type first; a part that doesn't read is no match, so /api/count/five is a 404 the handler never sees. The files of one directory must agree on the type (rocx build says where two differ), and its pages, layouts, Paths and Api take it too. This site's count of events is typed:
import pf.Server
import pf.Endpoint
import pf.Events
## GET /api/count/5, asked for its events (`accept: text/event-stream`): 1 to 5, each with its
## square, 300 ms apart. A loop: send, sleep, round again; if the page goes, `send!` says so, and
## `?` ends the loop. Its param is a number (`/api/count/five` is no route: 404).
events! : { request : Server.Request, params : { to : U64 }, context : c } => Try(Events({ count : U64, of : U64, square : U64 }), Endpoint.Refusal)
events! = |{ params, .. }| {
to = params.to
if to < 1 or to > 20 {
Err(BadRequest("count to a number from 1 to 20"))
} else {
Ok(
Events.stream(
|{ send!, sleep! }| {
var $count = 1
while $count <= to {
send!({ count: $count, of: to, square: $count * $count })?
sleep!(300)
$count = $count + 1
}
Ok({})
},
),
)
}
}This site's sidebar is built from Paths, each part's pages grouped under headings:
import ../Generated/Paths
…
Page : { path : Str, label : Str, blurb : Str }
Group : { name : Str, pages : List(Page) }
Section : { name : Str, home : Str, groups : List(Group) }
…
platform_docs : Section
platform_docs = {
name: "Platform",
home: Paths.platform_,
groups: [
{
name: "Overview",
pages: [
{ path: Paths.platform_, label: "Overview", blurb: "Two platforms, one app" },
{ path: Paths.platform_server, label: "The server", blurb: "Native Roc in a Rust host" },
…
],
},
{
name: "State",
pages: [
{ path: Paths.platform_database, label: "Database", blurb: "Postgres or SQLite: queries, transactions, migrations" },
{ path: Paths.platform_actors, label: "Actors", blurb: "State one message at a time, kept in the database" },
{ path: Paths.platform_kv, label: "Kv", blurb: "Values in memory by key, with a time to live" },
],
},Where no page is#
routes/+error.rocx is the app's error page. A browser asking for a path nothing answers gets it, inside the root layout, with a 404; other clients get a plain-text 404. A page that fails shows it too, unless an <Errored> inside catches the failure. Its status is the 4xx an endpoint refused a read with (NotFound makes the page a 404), or else 500. The error page's view! is given status and problem, why it failed, as text. Without one, an app gets a plain one. This site's lists the pages of the docs' part the path is in (try /nowhere or /platform/nowhere):
import pf.Html
import pf.Router
import ../Ui/Nav
import ../Generated/Paths
import ../Ui/PageCards
import ../Ui/PageHero
## What a path no page has shows (404): the pages of the part of the docs it is in, as cards, and
## the ways to the other parts and the front page. A page that failed (500) says why instead.
meta = {
title: "Not found",
description: "There is no page here.",
toc: [],
}
view! = |{ status, problem }| {
path = Router.location!({}).path
here = Nav.section_of(path)
others = Nav.sections.drop_if(|section| section.name == here.name)
<>
<PageHero eyebrow={status.to_str()} heading={if (status == 404) [<>{"Nothing at "}</>, <code>{path}</code>] else [<>This page failed</>]}>
{if (status == 404) "No page has that address." else problem} These are the pages of the {here.name} docs:
</PageHero>
<PageCards pages={Nav.pages_of(here)} />
<p>
Or another part: {...others.map_with_index(|section, i| <>{if (i == 0) "" else ", "}<a href={section.home}>the {section.name} docs</a></>)},
or the <a href={Paths.root}>front page</a>.
</p>
</>
}Endpoints: +server.roc#
A +server.roc (+server.rocx if it has markup) answers HTTP requests at its directory's path, with a handler per method: get!, post!, put!, patch! or delete!. A handler gets the request, the path's params, its middleware's context and, for a method with a body, the body as its annotated type. It answers Ok(result), sent as JSON with a 200, or Err(refusal), such as BadRequest(why) (400) or NotFound (404). A query that failed is Failed(why): why goes on the server's log with the request, and the client gets a plain 500 with nothing of it, since a database's error can name the app's tables and values. Annotated Try(Server.Response, Endpoint.Refusal), it answers with its own response: a redirect, a cookie, a file that isn't JSON. This one answers the form on this site's joining page and sets a cookie:
import pf.Server
import pf.Endpoint
import ../../../../Generated/Paths
## POST /api/members/join, from the joining page's form (`name=Ada`, read as `{ name : Str }`): the
## `member` cookie, and on to the members' page: an answer of its own (`Server.Response`, D-106).
post! : { request : Server.Request, params : {}, context : c, body : { name : Str } } => Try(Server.Response, Endpoint.Refusal)
post! = |{ body, .. }|
if body.name.trim().is_empty() {
Err(BadRequest("a member has a name"))
} else {
Ok(Server.with_cookie(Server.redirect(Paths.members), "member", body.name.trim()))
}- Bodies. JSON (
application/json) and forms (URL-encoded, ormultipart/form-datawith files) are read; a missing or unreadable field is a 400 that names it. Any other body, such as raw bytes, isn't: the handler takes{}as its body and reads the bytes fromrequest.body. - Checked bodies. Beside the handler,
post_body = Signup.form(a form of packages/forms) reads and checks the body, form or JSON, before the handler runs; the handler'sbodyis the rules' record. A body that fails is a422with the issues as JSON, and/openapi.jsondocuments it with the rules' schema. - Three more names.
events!answers a GET that asks for events (accept: text/event-stream) with a stream (events).channel!defines a channel pages subscribe to, with its hooksreceive!(what a page says),on_open!andon_close!(channels).respond!, given the request, params and context, answers every method the file doesn't name with its ownServer.Response: a package's handler, a JSON-RPC endpoint. - A package's endpoints are route files too. A package that answers requests offers handlers (
Auth.callback_route!,Stripe.webhook_route!,Push.subscribe_route!). The app puts each at the path it wants with a route file whoserespond!calls it, sorocx routeslists it and its folder's middleware guards it. A plugin adds tables, jobs and scripts to the server, never a route. Stripe's webhook, in an app that bills with packages/stripe:routes/stripe/webhook/+server.roc import stripe.Stripe import ../../../Billing respond! = |{ request, .. }| Stripe.webhook_route!(request, Billing.on_event!) - A path is a page or an endpoint. A page's endpoints (what it reads and what its forms post to) live under
routes/api/, at the page's path: the page at/membersreadsGET /api/members. One URL, one answer, so no cache mixes them up. A directory may still hold both: a browser's GET (accepting HTML) gets the page, anything else the endpoints, withVary: Accept;rocx lintwarns of it, and says where the endpoint goes (--pairs errorfails on it,--pairs offsays nothing). An unanswered method is a 405 listing the answered ones (Allow). - Typed at both ends. Each handler must be annotated: rocx copies the annotations into
Generated/Api.roc, which any module may import (a component, a job, an actor), and binds each handler inGenerated/Handlers.roc, on the server only (what rocx writes). - A form posted without JavaScript goes back to its page with a flash the page reads (forms): JSON would show as a bare page.
Talking to the server shows the rest, with this site's endpoints live.
Middleware: what runs, in what order#
Middleware runs around the answer to a request. Given the request, the context so far and next! (what comes after it), it can answer itself (a guard's redirect or 401), pass the request on with more context (who is signed in), or change the answer coming back (add a header). Guards, sessions, security headers and logs are middleware; a.then(b) runs a, then b.
Middleware(given, handed) :: { run : Server.Request, given, (Server.Request, handed => Server.Response) => Server.Response }.{
…
## A middleware, from what it does.
make : (Server.Request, given, (Server.Request, handed => Server.Response) => Server.Response) -> Middleware(given, handed)
…
## `first`, then `second`: `second` gets what `first` hands on.
then : Middleware(a, b), Middleware(b, c) -> Middleware(a, c)
…
## `guard` for the requests `asked` says, and the rest passed on as they are
…
when : (Server.Request -> Bool), Middleware(context, context) -> Middleware(context, context)
…
## A request that would change something (POST, PUT, PATCH, DELETE: a form, an endpoint's send,
## an action) sent by another site's page refused, with a 403. A page of another site
## can make a browser send one, with this site's cookies; a browser says which site's page did
## (`Origin`). A client that isn't a page (`curl`) sends none, and is let through.
same_origin : {} -> Middleware(context, context)
…
## Every answer with these headers too.
headers : List({ name : Str, value : Str }) -> Middleware(context, context)Middleware goes by folder. A +middleware.roc names the middleware around every page, endpoint and channel in its directory and below; nothing else runs any. The one in routes/ is the app's: it runs around every request, a path nothing answers included. This site's adds two headers to every answer:
import ../Middlewares
## Every request, given the facts the build measured: headers that keep the browser from guessing a
## file's type, and from telling other sites where it came from.
middleware = Middlewares.defaultBelow it, each runs inside the ones above, outermost first; what one hands on is the context of the next and of the handlers inside (get! = |{ context, .. }| …). The members' page and its endpoint, /members and /api/members, sit in a group, routes/(members)/, and share one guard; the joining page, routes/members/join/, has its own. Before any of them, a change sent by another site's page (POST, PUT, PATCH or DELETE) is refused, unless App.program says cross_site: Allowed. This site's middleware:
import pf.Middleware
import pf.Server
import Generated/Paths
## The site's middleware, named by directory (D-103): `default` runs around every request
## (routes/+middleware.roc); `member` around the members' page and its endpoint (the `(members)`
## group's), and `visitor` around the joining page (routes/members/join/), each after it.
Middlewares := [].{
## Around every request (one that would change something, sent by another site's page, the
## platform refuses first, 403): every answer tells the browser not to guess a file's type, and
## to send where it came from only to this site.
default : Middleware({ facts : Str }, { facts : Str })
default = Middleware.headers([
{ name: "x-content-type-options", value: "nosniff" },
{ name: "referrer-policy", value: "same-origin" },
])
## A member: someone whose `member` cookie names them, handed on as `context.member`. A browser
## that isn't is sent to join; anything else is refused (401).
member : Middleware({ facts : Str }, { facts : Str, member : Str })
member = Middleware.make(
|request, context, next!|
match Server.cookie(request, "member") {
Ok(name) =>
if name.is_empty() {
refuse(request)
} else {
next!(request, { facts: context.facts, member: name })
}
Err(Missing) => refuse(request)
},
)
## Not a member yet: the joining page. A member is sent on to the members' page.
visitor : Middleware({ facts : Str }, { facts : Str })
visitor = Middleware.make(
|request, context, next!|
match Server.cookie(request, "member") {
Ok(name) => if (name.is_empty()) next!(request, context) else Server.redirect(Paths.members)
Err(Missing) => next!(request, context)
},
)
}
refuse : Server.Request -> Server.Response
refuse = |request| if (Server.wants_html(request)) Server.redirect(Paths.members_join) else Server.refused(401, "members only: join at ${Paths.members_join}")import ../../Middlewares
## The members' page and its endpoint: a member's cookie, handed on as `context.member`; a browser
## that has none is sent to join. `(members)` is a group: it adds nothing to their paths.
middleware = Middlewares.memberimport pf.Html
import pf.Endpoint
import ../../../Generated/Api
import ../../../Generated/Paths
import ../../../Ui/Note
…
## Members only: its group's middleware (`Middlewares.member`, routes/(members)/+middleware.roc)
## runs before this page, as before its endpoint (`api/members/+server.roc`, in the same group), and
## hands on who the member is.
meta = {
…
## Who the member is: the page's endpoint (`GET /api/members`, for JSON), behind the same
## middleware, which read the cookie and handed on the name. The server answers it as it renders
## the page, and the page carries the answer.
member! : {} => Str
member! = |{}| Api.get_api_members({}).read!().member
view! = |_| {
member = member!({})
<>
<PageHero
eyebrow="Members"
title={"Welcome, ${member}"}import pf.Server
import pf.Endpoint
## GET /api/members, as JSON: who you are, behind the same middleware as the page (/members): its
## group's.
get! : { request : Server.Request, params : {}, context : { facts : Str, member : Str } } => Try({ member : Str }, Endpoint.Refusal)
get! = |{ context, .. }| Ok({ member: context.member })A request to /members goes through routes/+middleware.roc's middleware, then the group's Middlewares.member, then the page, and the answer goes back out through them. The page isn't given the context: it reads GET /api/members, which the server answers through the endpoint's route, behind the same middleware, so the handler gets the member's name. An endpoint a handler sends (Api.….send!(arg)) and an MCP tool made from an endpoint go that way too: what guards an endpoint guards every way to it. rocx routes lists every route and what runs around it, outermost first (--server lists the endpoints alone, --client the pages):
$ rocx routes site
METHOD PATH MIDDLEWARE (outermost first)
GET / Middlewares.default
GET /api/calls Middlewares.default
EVENTS /api/count/[to] Middlewares.default
GET /api/echo/[message] Middlewares.default
GET /api/facts Middlewares.default
GET /api/members Middlewares.default → Middlewares.member
POST /api/members/join Middlewares.default
POST /api/members/leave Middlewares.default
GET /api/planner Middlewares.default
POST /api/planner/move Middlewares.default
CHANNEL /api/platform/live/lobby Middlewares.default
GET /api/reader Middlewares.default
GET /api/shelf Middlewares.default
POST /api/shout Middlewares.default
GET /api/shout/[word] Middlewares.default
GET /calls Middlewares.default
GET /components Middlewares.default
GET /ecosystem Middlewares.default
GET /ecosystem/admin Middlewares.default
GET /ecosystem/ai Middlewares.default
GET /ecosystem/audio Middlewares.default
GET /ecosystem/auth Middlewares.default
GET /ecosystem/charts Middlewares.default
GET /ecosystem/chat Middlewares.default
GET /ecosystem/crypto Middlewares.default
GET /ecosystem/email Middlewares.default
GET /ecosystem/forms Middlewares.default
GET /ecosystem/guard Middlewares.default
GET /ecosystem/headless Middlewares.default
GET /ecosystem/intl Middlewares.default
GET /ecosystem/jobs Middlewares.default
GET /ecosystem/local Middlewares.default
GET /ecosystem/markdown Middlewares.default
GET /ecosystem/mcp Middlewares.default
GET /ecosystem/otel Middlewares.default
GET /ecosystem/posthog Middlewares.default
GET /ecosystem/presence Middlewares.default
GET /ecosystem/push Middlewares.default
GET /ecosystem/qr Middlewares.default
GET /ecosystem/slack Middlewares.default
GET /ecosystem/storage Middlewares.default
GET /ecosystem/stripe Middlewares.default
GET /ecosystem/testing Middlewares.default
GET /ecosystem/tools Middlewares.default
GET /ecosystem/vibrate Middlewares.default
GET /ecosystem/video Middlewares.default
GET /ecosystem/virtual Middlewares.default
GET /ecosystem/websocket Middlewares.default
GET /examples Middlewares.default
GET /examples/board Middlewares.default
GET /examples/checkboxes Middlewares.default
GET /examples/echo Middlewares.default
GET /examples/hello Middlewares.default
GET /examples/journal Middlewares.default
GET /examples/js-framework-benchmark Middlewares.default
GET /examples/notes Middlewares.default
GET /examples/plate Middlewares.default
GET /examples/pomodoro Middlewares.default
GET /examples/quiz Middlewares.default
GET /examples/rack Middlewares.default
GET /examples/sqlite-vs-turso Middlewares.default
GET /examples/tasks Middlewares.default
GET /examples/uptime Middlewares.default
GET /members Middlewares.default → Middlewares.member
GET /members/join Middlewares.default → Middlewares.visitor
* /openapi.html Middlewares.default
* /openapi.json Middlewares.default
GET /platform Middlewares.default
GET /platform/actors Middlewares.default
GET /platform/browser Middlewares.default
GET /platform/crypto Middlewares.default
GET /platform/database Middlewares.default
GET /platform/http Middlewares.default
GET /platform/kv Middlewares.default
GET /platform/live Middlewares.default
GET /platform/reference Middlewares.default
GET /platform/server Middlewares.default
GET /platform/settings Middlewares.default
GET /rocx Middlewares.default
GET /routing Middlewares.default
GET /safety Middlewares.default
GET /showcase Middlewares.default
GET /syntax Middlewares.default
GET /tooling Middlewares.default
* (anything else) Middlewares.default- The context is typed.
memberis aMiddleware({ facts : Str }, { facts : Str, member : Str }): it addsmemberto the context it is given. The members' endpoint can readcontext.member; outside the group, that wouldn't compile. - A new file is guarded by where it is. A page or endpoint added to the group runs behind its middleware with no line of its own. A route file can't name middleware:
rocx buildrefusesmiddleware = …in a page, an endpoint, a layout or the error page, and says which+middleware.rocto move it to. A+middleware.rocwith no page, endpoint or channel in its folder or below it guards nothing (a group emptied by a move):rocx buildwarns of it. - Only some requests.
Middleware.when(Server.changes, guard)runsguardonly for requests that change something, and lets reads by: a rate limit on a form's posts, say. - Middleware runs on the requests that reach the server; guard data in its endpoints. Every client reaches an endpoint through its middleware, so a guard there holds wherever the read comes from. A page's own middleware isn't counted on to run on every navigation: the browser fetches a page's document when it changes page, so a guard redirects before the page shows, but a change of the query alone, a static copy and a phone app ask only for the page's reads. A phone app draws its pages itself (D-160): a read that a guard redirects to one of the app's pages takes it there, as the server's render makes it the page's redirect, and a read it refuses (a 401) asks for the page's document, so the page's guard sends the app to sign in.
- Try it with
just dev. /members sends you to join; join, and it greets you by name. These pages aren't in the static copy of this site, which has no server.
Navigating without a reload#
A click on a link to another of the app's pages doesn't reload, as with Solid Router. The runtime fetches the new page's HTML document as a reload would: from the server, through its middleware, with reads answered and redirects followed (on a static copy, the file the build wrote). The app's wasm already holds every page's code, so it renders the new page from the document's answers and <NoHydration> parts, and asks for nothing else. Every link works this way, with no change to the app.
The old page stays until the document is in. Then the address is pushed to the history, the new page is made, and its <head> is updated (loaded stylesheets stay). The page scrolls to the top or to the link's #hash, focus goes where a reload would put it (an autofocus element, or the page's start), and a screen reader hears the new title. Back and forward render their entry's page the same way and restore its scroll. A document fetched in the last ten seconds is reused.
| Write | What it does |
|---|---|
<a href={Paths.blog_slug({ slug })}> | renders the page in place. Any plain link does: in markup, in Markdown, inside a <NoHydration> |
<a href={…} replace noscroll> | replaces the history entry instead of pushing one; keeps the scroll where it is |
rel="external", target, download, a modifier key | left to the browser: a reload, a new tab, a download |
navigate!(Paths.blog_slug({ slug })) | in a handler: goes to that page once the handler is done. navigate_with!(to, { replace, scroll }) takes Solid Router's options (import pf.Router exposing [navigate!, navigate_with!]) |
Router.is_routing!({}) | whether a navigation is on its way, tracked: a progress bar's class:on={…} |
Router.location!({}) | where the page is, { path, query }, tracked: a hole that reads it follows each navigation |
a[aria-current="page"], a[aria-current="true"] | every link to one of the app's pages says where the page is: page at its path (and its query, if it has one), true at a path under it (never /), kept right as you navigate. A link that writes its own aria-current is left alone. Style with CSS |
search = use_search_params!({}) | the query: search.get!("days") and search.all!() read it, tracked; search.set!([("days", "30")]), in a handler, merges into it ("" takes a name out) and changes it in place (import pf.Router exposing [use_search_params!]) |
<Navigate href={Paths.sign_in} /> | sends the visitor elsewhere as the page renders: a 303 from the server, or, in the browser, a navigation that replaces the history entry (import pf.Navigate) |
use_before_leave!(|leave| …) | in a component: asked before each navigation away; it may stop it (leave.prevent!()) and let it go later (leave.retry!(Bool.True)). Solid Router's useBeforeLeave (import pf.Router exposing [use_before_leave!]) |
<form action="/search"> | a GET form: navigates in place to its URL, with its fields as the query |
<html data-rocx-navigation="off"> | every link reloads the page instead; "explicit" navigates in place only for a link marked data-rocx-link |
data-rocx-reload | on a link, a form or an element around them: left to the browser, a load or a plain post (SvelteKit's data-sveltekit-reload); "off" takes it back for what is inside |
data-rocx-preload="off", "viewport" | on a link or an element around it (<html> for the whole app): never prefetch; or prefetch as the link comes into sight, as well as on hover, focus and touch |
<html data-rocx-transitions> | makes each navigation a View Transition, the browser's cross-fade, where the browser has them and the visitor hasn't asked for less motion. This site's bar and sidebar have a view-transition-name, so they stay put while the page changes |
- Layouts are kept. Each layout below the root one, and the page, is a level, made anew only when its file or its own params change: from one blog post to the next, the blog's layout keeps its sidebar's scroll, an open menu and its signals. A level that reads its location once, at the top of its body (
path = Router.location!({}).path), would show a stale location, so the runtime remakes it on every navigation and a dev build warns in the console. Read the location where you use it, in markup or a memo. A kept level's<NoHydration>parts come from the new document. - A change of the query alone happens in place. A link to
?days=30,search.set!ornavigate!("?days=30")fetches no document: the page and layouts stay, and what read the query reads it again. A read whose URL changed asks its endpoint (behind its middleware), showing its last value meanwhile. Back goes to the previous query. A<NoHydration>doesn't follow the query: the browser has no code for it. - The server decides, as on a reload. The document is a page's GET with
x-rocx-navigate: 1, so middleware that counts views can tell it from a reload. Guards refuse or redirect as usual, and a redirect lands at its address. The browser reloads instead when the target isn't one of the app's pages (a plugin's page, a file, a path no page has), when the answer isn't a document of this build (a text 401, a crash, a new deploy's page), or when the fetch fails. - A link is fetched before it is clicked. Hovering, focusing or touching a link prefetches its document (
x-rocx-navigate: preload), so the click asks nothing. A prefetch renders a page that may never be seen: middleware that counts views should skip those, and an app with costly pages can turn prefetching off. - Leaving unsaved work can ask first. A component holding unsaved work registers a listener with
use_before_leave!. Before each navigation away (a link,navigate!, a form's redirect, a query change, back and forward), it is told where to (to,from, and for back and forward how far,delta). It may stop the navigation, keeping the page and its address, or hold it while the app asks;leave.retry!(Bool.True)then lets it go, skipping the listeners (Bool.Falseasks them again). A listener decides from what the page has, without asking the server, and goes with its component. A real page load (another site, a reload, the tab closed) can't be held: when a listener would stop one, the browser asks the visitor itself. The tasks example's task page does this. - Page scripts run on a load only. A navigation doesn't run the new page's
<script>s. Script that sets up onrocx:readyshould also do so onrocx:navigated, a document event with the URL and how long the navigation took (this site's inspectors do). - What the old page started stops with it. Its effects' cleanups run, its timers and event streams stop, and its channels are left, unless the next page subscribes to one too.
What rocx writes#
Every build turns the routes into Roc modules under Generated/, and rocx generate writes them alone. You never edit them, but knowing them helps you read the compiler's reports:
| Module | What it holds |
|---|---|
ShowcasePage.roc, ApiShoutServer.roc, MembersMiddleware.roc… | each route file and +middleware.roc, as a module named after where it is, a group's name kept (routes/(members)/+middleware.roc is MembersMiddleware) |
Paths.roc | a path for every page (typed links) |
Api.roc | the app's contract: a function for each endpoint and channel, with its method, URL and types |
Handlers.roc | the server's only: each endpoint bound to its handler |
Routes.roc | the server's router: the answer to a request (below) |
Root.roc | the pages as one component, in their layouts: what the server renders and the browser hydrates and navigates |
App.roc | the server's program, which main.roc finishes with App.program |
Styles.roc | the app's stylesheet, from the components' scoped <style>s |
Roc names a module after its file, and +page isn't a valid name, so each route file becomes a module named after its path (routes/showcase/+page.rocx is ShowcasePage). rocx keeps the lines where they were: the module's first line goes on the blank line after the imports (or, with none, at the start of the first definition's line). Line N of the module is line N of the route file, so the compiler's reports point at your lines:
import pf.Html
import ../Demos/Birds
import ../Demos/Snake
import ../Demos/Timers
import ../Ui/Heading
import ../Ui/Callout
import ../Ui/Code
import Sources
import Paths
import ../Ui/Feature
import ../Ui/FeatureGrid
import ../Ui/Note
import ../Ui/PageHero
import ../Ui/Demo
ShowcasePage := [].{
meta = {
title: "Showcase",
description: "Snake, a flock of bouncing Roc birds and the browser's timers: components Roc runs frame by frame in your browser, compiled to WebAssembly, with sound from a handler.",
toc: [
{ id: "snake", label: "Snake" },
{ id: "flock", label: "A flock of Roc birds" },
{ id: "how", label: "How they work" },
{ id: "sound", label: "Sound, from a handler" },
…The router#
Generated/Routes.roc's respond! answers a request. It splits the path into parts and tries each route, fixed paths before params. A match answers with the page inside its layouts (for a browser's GET), the endpoint for the method, or a 405; no match, with the error page:
Routes := [].{
…
respond! = |request, context| {
segments = request.path.split_on("/").keep_if(|segment| !segment.is_empty()).map(Server.decode_segment)
method = if (request.method == "HEAD") "GET" else request.method
wants_html = (Server.header(request, "accept") ?? "").contains("text/html")
if (Endpoint.channel_asked(request) != "") {
Routes.channel!(segments, request, context)
…
} else if (segments == ["api", "facts"]) {
params = {}
if (method == "GET") {
Endpoint.respond!(Handlers.get_api_facts(params), request, context)
} else {
Endpoint.not_allowed(request, ["GET"])
}
…
} else if (segments == ["api", "shout"]) {
params = {}
if (method == "POST") {
Endpoint.respond!(Handlers.post_api_shout(params), request, context)
} else {
Endpoint.not_allowed(request, ["POST"])
}
…
} else if (segments == ["calls"]) {
if (method == "GET") {
Routes.page(200)
} else {
Endpoint.not_allowed(request, ["GET"])
}
…
} else {
…
if (wants_html) {
Routes.by_accept(Routes.page(404))
} else {
Routes.by_accept(Routes.text(404, "nothing at ${request.path}"))
}
}
}App.program answers every request with it, behind routes/+middleware.roc's middleware: every URL is a route file, a package's handlers and the OpenAPI document too. A route under a +middleware.roc is wrapped in Middleware.run!, one inside the other, outermost first, and the handler gets what the innermost passed on. The members page and its endpoint run behind their group's:
} else if (segments == ["api", "members"]) {
params = {}
if (method == "GET") {
Middleware.run!(MembersMiddleware.middleware, request, context, |passed, handed| Endpoint.respond!(Handlers.get_api_members(params), passed, handed))
} else {
Endpoint.not_allowed(request, ["GET"])
}
…
} else if (segments == ["members"]) {
if (method == "GET") {
Middleware.run!(MembersMiddleware.middleware, request, context, |_passed, _handed| Routes.page(200))
} else {
Endpoint.not_allowed(request, ["GET"])
}The OpenAPI document#
An app can serve an OpenAPI document (3.2) of its endpoints, for client generators or people exploring the API. It lists:
- each path and its params (a typed param with its type's schema);
- each method, with the doc comment above its handler. The comment's first sentence, without a method and path it may start with, is the summary Swagger UI and Scalar list the method by:
## POST /api/shout: what it is sent, shouted.gives What it is sent, shouted.; - the JSON Schemas of what each endpoint is sent and answers: the handler's types as the compiler has them. This site's
GET /api/shout/{word}answers{ word : Str, shouted : Str, bytes : U64 }, and its document says so.
Pages' endpoints are in it too. A body a form can send (a record of text, numbers, yes-or-no, choices and lists of them) is listed three ways: application/json, application/x-www-form-urlencoded and multipart/form-data, with one schema, except that a form may leave out a yes-or-no or a list, as it leaves out an unticked box. A body checked by rules (post_body) is listed the same three ways, with the rules' schema: what they require, and their lengths, patterns and ranges.
Turning it on
An app serves it from routes of its own: routes/openapi.json/+server.roc answers with the document, and routes/openapi.html/+server.roc with a page that shows it in Swagger UI or Scalar. The page reads openapi.json beside it, so keep the two side by side. Without them, neither is served.
import pf.OpenApi
import ../../Generated/Api
respond! = |{ request, .. }| OpenApi.document_route(request, Api.openapi)import pf.OpenApi
respond! = |{ request, .. }| OpenApi.page_route(request, Swagger)- They are routes like any other: their folder's middleware runs around them (put them in a guarded group to keep the document from strangers), and
rocx routeslists them. Under--dev, the server lists the page as it starts. - The page loads its viewer from jsDelivr, pinned to one version and checked against its hash, and tells it not to call home: no validator for Swagger UI; no telemetry, fonts, developer tools or agent for Scalar. Bundling a viewer instead would add 2 to 5 MB to every app's server.
This site serves both: its API, in Swagger UI, and the document.
Who makes it, and when
Neither platform makes it: rocx writes Roc that asks for it, the compiler works it out, and the server only sends it.
| When | What runs | What it does |
|---|---|---|
rocx build | rocx (rocx-cli/Routes.roc), as it writes the router | Writes Roc, knowing no types. Generated/Api.roc gets openapi: each path with its params, methods and comments, and for each endpoint a call that asks OpenApi for the schemas of its body and its answer. It also gets tags, every name in the app's code that could be a tag. |
roc build, the server's | the Roc compiler | Infers each endpoint's types and writes, for each, a parser for the format OpenApi.Schema, as it writes one for Json to read the endpoint's body. openapi is a constant, so the compiler works out its value as it compiles: the server's binary holds the document as text. |
GET /openapi.json | the server (native) | The route's OpenApi.document_route sends that text, behind its folder's middleware. |
The browser's build (wasm) has none of it: its Api is the same contract (each endpoint's method, URL and types) without the document. What rocx writes for this site, in part:
## The OpenAPI document of these endpoints, which an app's route file answers `GET /openapi.json`
…
## each path and its methods, with what their comments say, and the JSON Schemas of what each is
## sent and answers, from their types (`OpenApi`). `tags` is every name in the app's code that
## could be a tag: a tag union's schema has the ones that are its.
openapi : Str
openapi = {
tags = [
"A", "About", "Absent", "Access", "Account", "Actions", "Active", "Actor", "ActorErr", "ActorTimers",
…
]
OpenApi.document("site", [
…
OpenApi.path("/api/shout/{word}", ["word"], [
OpenApi.operation("get", "The word, shouted, and how many bytes it has.", "GET /api/shout/:word: the word, shouted, and how many bytes it has.", "", [OpenApi.answer(Api.get_api_shout_word({ word: "" }), tags)]),
]),
])
}A parser that writes
Roc has no reflection: no code can ask what a type is. But the parser the compiler writes for a type works with any format: it calls the format shape by shape (a record, its next field, a string, a number), handing a record's format its field names. OpenApi.Schema is a format that reads nothing: for each part, it writes that part's schema and gives back a value nothing looks at. OpenApi.body asks the compiler for the parser of what the endpoint is sent, for Schema, and runs it:
## The schema of what an endpoint is sent (its `body`), as JSON.
body : Endpoint(context, arg, result), List(Str) -> Str
where [arg.parser_for : Schema -> (State -> Try({ value : arg, rest : State }, Problem))]
body = |_, tags| {
Sent : arg
described(Sent.parser_for(Schema.Default)(start(tags)))
}
…
## A format that reads nothing: each `parse_*` writes the JSON Schema of the shape it is asked for,
## as `Json` writes that shape, and gives back a value of its type that nothing reads.
Schema := [Default].{
…
parse_str : Schema, State -> Try({ value : Str, rest : State }, Problem)
parse_str = |_, state| scalar(state, "{\"type\":\"string\"}", "")
…
parse_u64 : Schema, State -> Try({ value : U64, rest : State }, Problem)
parse_u64 = |_, state| scalar(state, "{\"type\":\"integer\",\"minimum\":0}", 0)For the answer of GET /api/shout/{word}, { word : Str, shouted : Str, bytes : U64 }, the parser and Schema go:
| The parser calls | Schema writes |
|---|---|
parse_record_start | {"type":"object","properties":{ |
parse_record_field, given the names bytes, shouted, word: it hands back bytes | "bytes": |
parse_u64, as bytes is a U64 | {"type":"integer","minimum":0} |
parse_record_field and parse_str, for shouted, then word | ,"shouted":{"type":"string"}, and word's |
parse_record_field, with no name left: it says Done | },"required":["bytes","shouted","word"]} |
A tag union is the one shape whose parser doesn't say what it holds: it asks the format for a tag's name, then reads that tag's payloads. So rocx gives the document tags, every name in the app's code (and its packages' and platforms') that could be a tag, and Schema offers each in turn. The parser turns down names not in the union; for the others it reads the payloads, and Schema writes their schemas. [Red, Rgb(U8, U8, U8)] is a string, "Red", or an object, { "Rgb": [r, g, b] }, as Json writes them.
- A GET with events (
events!) answerstext/event-streamtoo: each event's data is JSON, with its schema, and anendevent ends the stream. - A refusal is every method's default answer: its status, and why, as text.
- A type of your own (
Email := Str.{ parser_for : _ }) is described asJsonreads it. Write its parser for any format (encoding.parse_str), not for JSON alone, and the document can describe it too.
Not yet#
- A static copy has no guarded pages.
rocx build --staticwrites/, the pages without params, each--routeand every page they link to, but none behind a+middleware.rocother thanroutes/'s. - Nothing warns of a page and an endpoint at one path. They still answer, by
Accept. - One error page, the app's, at the root of
routes/:rocx buildrefuses a+error.rocxanywhere else. - No rest params (
[...path]). - The OpenAPI document calls every JSON field required, describes a type that holds itself (a tree) only so many levels deep, and has no
$refs. Its title is the app's directory's name. A tag union's tags come from the names in the app's code, until Roc's parsers say which tags a union has, as they say a record's fields.