Roc Solid
Markup in Roc · pages on a native server · components in WebAssembly

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:

site/routes
+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
FileWhat it is
routes/+page.rocxthe page at /
routes/blog/+page.rocxthe page at /blog
routes/blog/[slug]/+page.rocxthe page at /blog/anything, given params.slug
+layout.rocxwraps every page in its directory and below it
routes/+error.rocxwhat a browser sees at a path nothing answers (404), and when a page fails
routes/api/blog/+server.rocthe 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.rocthe 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:

site/routes/showcase/+page.rocx
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" },
…

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:

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:

site/routes/+layout.rocx, in part
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:

test/e2e/routes/routes/blog/[slug]/+page.rocx
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.

What rocx writes for that app: Generated/Paths.roc
## 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:

site/routes/api/count/[to]/+server.roc
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:

site/Ui/Nav.roc, in part
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):

site/routes/+error.rocx
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:

site/routes/api/members/join/+server.roc
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()))
	}

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.

web/platform/Middleware.roc, in part
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:

site/routes/+middleware.roc
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.default

Below 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:

site/Middlewares.roc
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}")
site/routes/(members)/+middleware.roc
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.member
site/routes/(members)/members/+page.rocx, in part
import 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}"}
site/routes/(members)/api/members/+server.roc
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):

A terminal
$ 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

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.

WriteWhat 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 keyleft 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-reloadon 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

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:

ModuleWhat 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.roca path for every page (typed links)
Api.rocthe app's contract: a function for each endpoint and channel, with its method, URL and types
Handlers.rocthe server's only: each endpoint bound to its handler
Routes.rocthe server's router: the answer to a request (below)
Root.rocthe pages as one component, in their layouts: what the server renders and the browser hydrates and navigates
App.rocthe server's program, which main.roc finishes with App.program
Styles.rocthe 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:

site/Generated/ShowcasePage.roc
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:

site/Generated/Routes.roc, in part
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:

site/Generated/Routes.roc, in part
} 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:

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.

routes/openapi.json/+server.roc
import pf.OpenApi
import ../../Generated/Api

respond! = |{ request, .. }| OpenApi.document_route(request, Api.openapi)
routes/openapi.html/+server.roc
import pf.OpenApi

respond! = |{ request, .. }| OpenApi.page_route(request, Swagger)

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.

WhenWhat runsWhat 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:

site/Generated/Api.roc, 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:

web/platform/OpenApi.roc, in part
	## 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 callsSchema 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.

Not yet#