# Mortar
> A small website framework on Solid 2: bricks, collections and a live-preview admin.
Source: https://docs.mortar-kit.dev/docs/introduction
# Introduction
> What Mortar is, what it gives you, and what it leaves to you.
Mortar is a small website framework on [Solid 2](https://v2.solidjs.com). You describe your site in code, and Mortar renders it and gives you an admin to edit it with a live preview.
You define two things:
- **Bricks**: the sections your pages are built from, such as a hero, a feature grid or a block of Markdown. A brick is a Solid component plus a schema of the data it shows.
- **Collections**: sets of documents that share a schema, such as pages, posts or products. A document has typed fields and, if its collection has a body, an ordered list of bricks.
Mortar then gives you:
- ``, which renders a body: each entry is looked up by brick name and rendered with its data.
- Storage rules (`createContent`) over a small adapter you can swap: JSON files by default, in memory for tests, or anything else you write.
- ``, a schema-driven editor for every collection. Its preview is your real site, with your own bricks, layouts and styles, in an iframe.
> **Tip: You're reading a Mortar site**
>
> These docs are built with Mortar. Choose **Edit this site** at the top to open the admin. Your edits are kept in this browser tab only, and you can reset them at any time.
## What Mortar is not
Mortar is a framework, not a CMS. It ships no bricks, no collections, no routing and no hosting. Sign-in for the admin is an optional package, `@mortar-kit/auth`. Your app keeps its routes and layouts. Mortar renders the parts made of content, and the admin is a route you mount where you like.
## Packages
| Package | What it holds |
| --- | --- |
| `@mortar-kit/core` | Fields, bricks, collections, documents, storage rules, `PageView` and the content context |
| `@mortar-kit/core/server` | The JSON-file store (Node only, so `node:fs` never reaches a browser bundle) |
| `@mortar-kit/admin` | ``, `` and `` |
| `@mortar-kit/admin/preview` | ``, for the preview route |
| `@mortar-kit/admin/vite` | The `mortarKit()` Vite plugin, which picks the admin's theme |
| `@mortar-kit/auth` | Sign-in for the admin: Google and email methods, sessions, route guards (server only) |
| `@mortar-kit/theme-*` | Admin themes: `midnight`, `warm`, `soft` and `mono` |
Admin code never reaches your public pages' bundle: the admin is only imported by its own route.
Source: https://docs.mortar-kit.dev/docs/installation
# Installation
> Add Mortar to a Solid 2 app built with Vite.
Mortar runs in a Solid 2 app built with Vite and `@solidjs/vite-plugin` 3. If you're starting from scratch, set that up first, with SSR if you want pages rendered on the server.
## Install the packages
```sh
pnpm add @mortar-kit/core @mortar-kit/admin solid-js @solidjs/web @solidjs/router
```
Add a theme if you want one, for example:
```sh
pnpm add @mortar-kit/theme-midnight
```
Recent versions of pnpm refuse packages published less than a day ago (its `minimumReleaseAge` setting). To install a Mortar release the day it comes out, exclude the packages in `pnpm-workspace.yaml`:
```yaml
minimumReleaseAgeExclude:
- '@mortar-kit/*'
```
Every `@mortar-kit` package releases at the same version. Before upgrading, read the [changelog](https://docs.mortar-kit.dev/changelog.md): its **Upgrading** notes list what can stop a site from starting, such as a renamed environment variable.
## Configure Vite
Add `mortarKit()` next to the Solid plugin. It only chooses the admin's theme, so leave out `theme` for the default look.
```ts
// vite.config.ts
import { mortarKit } from '@mortar-kit/admin/vite';
import midnight from '@mortar-kit/theme-midnight';
import solid from '@solidjs/vite-plugin';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [
solid({ start: { renderMode: 'async' }, ssr: true, serverFunctions: true }),
mortarKit({ theme: midnight }),
],
});
```
> **Note: Through Vite only**
>
> Mortar's packages publish Solid JSX under the `solid` export condition and have no plain `import` entry. They're meant to be compiled by your app's Vite build with `@solidjs/vite-plugin`.
## TypeScript
Use Solid 2's JSX settings:
```json
{
"compilerOptions": {
"jsx": "preserve",
"jsxImportSource": "@solidjs/web",
"moduleResolution": "bundler"
}
}
```
Next, build a first page in the [quick start](https://docs.mortar-kit.dev/docs/quick-start.md).
Source: https://docs.mortar-kit.dev/docs/quick-start
# Quick start
> A brick, a collection, a page that renders it, and an admin to edit it.
This walk-through builds the smallest useful Mortar site: one brick, a `pages` collection, a route that renders a page, and the admin.
## 1. Define a brick
A brick is a component plus the schema of its data. The schema is built with `fields.*` helpers, and the component receives the data, already validated and with defaults filled in, as `props.data`.
```tsx
// src/bricks/hero.tsx
import { defineBrick, fields } from '@mortar-kit/core';
export const hero = defineBrick({
name: 'hero',
label: 'Hero',
schema: {
heading: fields.text({ label: 'Heading', required: true, default: 'Hello' }),
intro: fields.textarea({ label: 'Intro' }),
},
component: (props) => (
{props.data.heading}
{props.data.intro}
),
});
export const bricks = [hero];
```
> **Warning: Don't destructure props**
>
> Read `props.data.heading` where you use it. Destructuring props breaks Solid's reactivity, and the admin's live preview relies on it.
## 2. Declare a collection
Pages aren't built in: a site declares its own `pages` collection. With `body: true`, each page also has an ordered list of bricks.
```ts
// src/collections.ts
import { defineCollection, fields } from '@mortar-kit/core';
export const pages = defineCollection({
name: 'pages',
label: 'Pages',
fields: {
title: fields.text({ label: 'Title', required: true }),
},
body: true,
url: '/:slug',
home: 'home',
reservedSlugs: ['admin'],
});
export const collections = [pages];
```
## 3. Store content
`createContent` applies Mortar's rules over a store. On the server, use the JSON-file store, and let `createContentServer` turn it into functions the browser can call. Reads are open to everyone; writes need a signed-in editor once you add [sign-in](https://docs.mortar-kit.dev/docs/sign-in.md) (`auth: false` leaves them open while you try things out locally):
```ts
// src/server/mortar.ts
import { createContent } from '@mortar-kit/core';
import { createContentServer, createJsonFileStore } from '@mortar-kit/core/server';
import { bricks } from '../bricks/hero.tsx';
import { collections } from '../collections.ts';
export const content = createContent({ store: createJsonFileStore({ dir: 'content' }), collections, bricks });
export const server = createContentServer({ content, auth: false });
// src/server/content.ts
'use server';
import { server } from './mortar.ts';
export const list = server.list;
export const get = server.get;
export const save = server.save;
export const remove = server.remove;
export const move = server.move;
```
The other functions it makes (`listAssets`, `uploadAsset` and the rest) are for [assets](https://docs.mortar-kit.dev/docs/assets.md); see [Storage](https://docs.mortar-kit.dev/docs/storage.md#calling-it-from-the-browser) for the full list. A page is now a file such as `content/pages/home.json`.
Then build the browser side with `contentClient`: cached reads for your pages, fresh reads and writes for the admin:
```ts
// src/content.ts
import { contentClient } from '@mortar-kit/core';
import { query } from '@solidjs/router';
import { GET } from '@solidjs/web/server-functions';
import * as server from './server/content.ts';
export const { source, freshSource, content: adminContent } = contentClient(server, { read: GET, cache: query, onWrite: () => query.clear() });
```
## 4. Render a page
Provide the reads to your app with `ContentContext`:
```tsx
// src/App.tsx
import { ContentContext } from '@mortar-kit/core';
import { source } from './content.ts';
export default function App() {
return {/* your router */};
}
```
Then read a document with `useContent()` and render its body with ``:
```tsx
// src/routes/page.tsx
import { PageView, useContent } from '@mortar-kit/core';
import { createMemo, Show } from 'solid-js';
import { bricks } from '../bricks/hero.tsx';
import { pages } from '../collections.ts';
export function PageRoute(props: { slug: string }) {
const content = useContent();
const page = createMemo(() => content.get(pages, { slug: props.slug }));
return (
{(p) => }
);
}
```
## 5. Mount the admin
The admin is a route in your app. It needs reads and writes, and the URL of a preview route that renders ``:
```tsx
// src/routes/admin.tsx
import { Admin } from '@mortar-kit/admin';
export default function AdminRoute() {
return ;
}
// src/routes/admin-preview.tsx
import { PreviewPage } from '@mortar-kit/admin/preview';
export default function AdminPreview() {
return ;
}
```
`adminContent` and `freshSource` come from `contentClient`: the admin reads fresh, so it always shows what is saved, while your pages keep their cached reads. Load both routes lazily, so admin code stays out of your public pages' bundle.
> **Warning: Guard the admin**
>
> Anyone who can reach `/admin` and the save and delete functions can use them until you add sign-in. See [Sign-in](https://docs.mortar-kit.dev/docs/sign-in.md): `@mortar-kit/auth` guards the routes in middleware and each write in its server function.
Source: https://docs.mortar-kit.dev/docs/bricks
# Bricks
> The sections pages are built from, each a component plus a schema.
A brick is one kind of section: a component, and the schema of the data each use of it holds. A document's body is a list of **entries**, each `{ brick, id, data }`: the brick's name, a stable id, and that entry's data.
```json
{ "brick": "hero", "id": "a1b2", "data": { "heading": "Hello", "intro": "Welcome." } }
```
## Defining a brick
```tsx
import { defineBrick, fields } from '@mortar-kit/core';
import { For } from 'solid-js';
export const featureGrid = defineBrick({
name: 'feature-grid',
label: 'Feature grid',
schema: {
heading: fields.text({ label: 'Heading', default: 'Features' }),
items: fields.list({
label: 'Features',
max: 6,
of: fields.object({
label: 'Feature',
fields: { title: fields.text({ label: 'Title' }), text: fields.textarea({ label: 'Text' }) },
}),
}),
},
component: (props) => (
{props.data.heading}
{(item) =>
{item.title}
{item.text}
}
),
});
```
- `name` is what entries store, so treat it as permanent. Use lowercase letters, digits and dashes.
- `label` is what the admin shows. It defaults to `name`.
- `schema` drives validation, defaults and the admin's form. See [Fields](https://docs.mortar-kit.dev/docs/fields.md).
## What the component receives
`props.data` always has the schema's shape. Stored data is **normalized** before rendering: missing fields get their defaults, and values of the wrong type are replaced by the default. So data that is old or edited by hand can't crash a brick. A value of the right type that breaks a rule, such as an empty required text, is kept, so the preview shows what the editor typed.
Read `props.data.x` where you use it, and never destructure props. `PageView` updates the data in place as the editor types, and lists inside a brick keep their DOM.
## Unknown bricks
If a stored entry names a brick your code no longer defines, the site renders nothing for it and the admin shows a warning, so removing a brick never breaks a page. `PageView`'s `fallback` prop chooses what to render instead.
## Bricks that load data
A brick can declare `load(data, content)` to read other documents, such as the latest posts. See [Loading data](https://docs.mortar-kit.dev/docs/loading-data.md).
## Bricks with forms
A brick can declare `action` to handle its own form, such as a contact form, and render a ``. It works without JavaScript, and with it only the brick updates. See [Handling forms](https://docs.mortar-kit.dev/docs/forms.md).
## Interactive bricks
Public pages can ship no JavaScript at all (see [Pages without JavaScript](https://docs.mortar-kit.dev/docs/no-javascript.md)). A brick that needs the browser, such as a form that answers in place or a carousel, says so with `interactive: true`. On such a page only that brick hydrates (an island), and only pages that show it load any JavaScript. See [Islands](https://docs.mortar-kit.dev/docs/no-javascript.md#islands).
## `defineBrick` (function)
`import { defineBrick } from '@mortar-kit/core'`
```ts
function defineBrick>, L = undefined, R = undefined>(def: BrickDefinition): Brick
```
Registers a brick: a named component plus the schema of its data.
### Parameters
- `def: BrickDefinition`
### Returns
`Brick`
## `BrickProps` (interface)
`import { BrickProps } from '@mortar-kit/core'`
```ts
interface BrickProps
```
Props every brick component receives.
### Properties
- `data: D`: The brick's data: the right shape, with defaults filled in (see `Brick.normalize`).
- `loaded: L`: What the brick's `load` returned; undefined for a brick without one.
- `submission?: Submission`: The latest post of this entry's form (``) to its `action`:
pending, then what it returned or threw. Undefined until the form is
sent, and for a brick without an action.
Source: https://docs.mortar-kit.dev/docs/fields
# Fields
> The field helpers that describe the data of bricks and collections.
Schemas are built with `fields.*`. Each helper returns a [Valibot](https://valibot.dev) schema that validates the value, fills in a default when it's missing, and carries a description that the admin turns into a form input. The set is deliberately small.
Every helper takes a `label`, an optional `help` text shown under the input, and an optional `default`. A brick field can also be `private: true`: only the server reads it (say, where a form's messages go), so an [interactive brick](https://docs.mortar-kit.dev/docs/no-javascript.md#islands) leaves it out of what it sends to the browser. The admin and the brick's `action` still see the stored value.
| Helper | Stores | Options |
| --- | --- | --- |
| `fields.text` | a one-line string | `required`, `maxLength`, `placeholder` |
| `fields.textarea` | a multi-line string | `required`, `maxLength`, `placeholder` |
| `fields.number` | a finite number | `min`, `max`, `step` |
| `fields.boolean` | `true` or `false` | |
| `fields.select` | one of a fixed set of values | `options`: value → label; the first is the default |
| `fields.url` | an http(s) URL or a path such as `/about` | `required`, `placeholder` |
| `fields.image` | `{ src, alt, title, asset }`: an uploaded image or a URL | `required` |
| `fields.file` | `{ src, title, asset }`: an uploaded file (video, audio, PDF…) or a URL | `accept` (kinds, default all), `required` |
| `fields.date` | a date as `YYYY-MM-DD`, or `''` | `required` |
| `fields.list` | an ordered list of items | `of` (the item's field), `min`, `max` |
| `fields.object` | a group of named fields | `fields` |
| `fields.reference` | the **id** of a document in another collection | `collection`, `required` |
## Examples
```ts
import { fields } from '@mortar-kit/core';
const schema = {
title: fields.text({ label: 'Title', required: true, maxLength: 120 }),
price: fields.number({ label: 'Price', min: 0, step: 0.01 }),
align: fields.select({ label: 'Alignment', options: { left: 'Left', center: 'Centre' } }),
cover: fields.image({ label: 'Cover image' }),
trailer: fields.file({ label: 'Trailer', accept: ['video'] }),
published: fields.date({ label: 'Published', required: true, default: '2026-01-01' }),
category: fields.reference({ label: 'Category', collection: 'categories', required: true }),
links: fields.list({
label: 'Links',
of: fields.object({ label: 'Link', fields: { label: fields.text({ label: 'Label' }), href: fields.url({ label: 'URL' }) } }),
}),
};
```
## Notes
- **Links are checked.** `url`, `image` and `file` accept http(s) URLs, site paths (`/`, `#`, `?`) and `mailto:` or `tel:` links, and reject other schemes such as `javascript:`, because the values end up in `href` and `src`.
- **Uploads store a key, not a URL.** `asset` holds the uploaded file's key and `src` is filled in when content is read, so render `src` and moving files to another bucket keeps every link. See [Assets](https://docs.mortar-kit.dev/docs/assets.md).
- **Dates sort as strings.** `YYYY-MM-DD` is stored as written, so a collection can sort by it.
- **References store ids, not slugs.** Renaming a document keeps every link to it. Deleting a document that others reference is refused, and the admin shows where it is used.
- **Select values** must not look like integers (`'1'`, `'2'`): JavaScript reorders such keys. Use names like `c1`.
Types follow the schema: `InferFields` is the data's type, and bricks and collections infer it for you.
## `fields` (variable)
`import { fields } from '@mortar-kit/core'`
```ts
const fields: { text, textarea, number, boolean, select, url, image, file, list, object, date, reference }
```
Field helpers used to declare the schema of a brick or a collection.
### Members
- `text: (o: TextOptions) => Field`
- `textarea: (o: TextOptions) => Field`
- `number: (o: Common & { min?: number; max?: number; step?: number }) => Field`
- `boolean: (o: Common) => Field`
- `select: (o: Common & { options: O }) => Field`
- `url: (o: Common & { placeholder?: string; required?: boolean }) => Field`
- `image: (o: Common> & { required?: boolean }) => Field`
- `file: (o: Common> & { accept?: readonly AssetKind[]; required?: boolean }) => Field`
- `list: (o: Common & { of: Field; min?: number; max?: number }) => Field`
- `object: (o: Common> & { fields: F }) => Field>`
- `date: (o: Common & { required?: boolean }) => Field`
- `reference: (o: Common & { collection: string; required?: boolean }) => Field`
## `InferFields` (type)
`import { InferFields } from '@mortar-kit/core'`
```ts
type InferFields = { -readonly [K in keyof F]: v.InferOutput }
```
The data type described by a record of fields.
Source: https://docs.mortar-kit.dev/docs/collections
# Collections
> Sets of documents that share a schema, such as pages, posts and products.
A collection is a named set of documents with the same fields. Pages, posts, products and categories are all collections. Mortar ships none: your site declares what it needs.
```ts
import { defineCollection, fields } from '@mortar-kit/core';
export const posts = defineCollection({
name: 'posts',
label: 'Posts',
fields: {
title: fields.text({ label: 'Title', required: true }),
date: fields.date({ label: 'Published', required: true }),
excerpt: fields.textarea({ label: 'Excerpt' }),
},
body: true,
sort: { field: 'date', order: 'desc' },
});
```
| Option | Meaning |
| --- | --- |
| `name` | Stable identifier and storage folder. Lowercase, e.g. `posts` or `case-studies`. |
| `label` | The plural name the admin shows. Defaults to `name`. |
| `fields` | The fields every document has. |
| `body` | Whether documents also have a body of bricks. Default `false`. |
| `title` | The text field shown as a document's title in lists. Defaults to the first text field, then the slug. |
| `sort` | The default list order: a field (or `'slug'`) and `'asc'` or `'desc'`. Defaults to the title. |
| `orderable` | Whether editors put the documents in order by hand. Lists then follow that order. Default `false`. See [Manual order](#manual-order). |
| `reservedSlugs` | Slugs documents may not use, such as your own route segments next to `/:slug` (`admin`). |
| `canWrite` | Who may change its documents, given the user and the document. Checked with the content server's own rule (see [Sign-in](https://docs.mortar-kit.dev/docs/sign-in.md#who-may-change-what)). |
| `url` | Where a document lives on the site: a path with one `:slug` segment, e.g. `/posts/:slug`. See [URLs](#urls). |
| `home` | With `url`: the slug of the document at the pattern's prefix instead, e.g. `home` at `/` for `/:slug`. |
## Documents
A document is a plain object:
```ts
interface Doc {
id: string; // stable: references store it, and it never changes
slug: string; // the address, unique in the collection, e.g. 'hello-world'
position?: number; // its place in a manual order (orderable collections only)
fields: { ... }; // the collection's fields
entries?: PageEntry[]; // the body, when the collection has one
}
```
Slugs are lowercase letters and digits with single dashes between, up to 100 characters. Renaming a slug keeps the id, so links by reference still work.
Keys of `fields` that the schema doesn't describe are kept, so other code can store its own data alongside. Use `DocOf` for a typed document.
## URLs
Give a collection a `url` and its pattern drives everything that needs a document's address:
```ts
export const pages = defineCollection({ name: 'pages', fields, body: true, url: '/:slug', home: 'home', reservedSlugs: ['admin'] });
export const posts = defineCollection({ name: 'posts', fields, body: true, url: '/posts/:slug' });
```
- **Routes**: the pattern uses the router's `:slug` syntax, so routes take it as their path: `{ path: posts.url!, component: Post }`. Mortar still doesn't route; your app declares its routes.
- **Links**: `posts.urlOf(doc)` gives `/posts/hello`; `pages.urlOf({ slug: 'home' })` gives `/`.
- **Admin preview links**: ⌘/Ctrl-clicking a link in the preview opens the document it shows, matched by the patterns (`resolveUrl`); `` overrides it.
- **Sitemap**: `sitemap(content, collections, { origin })` returns the XML for every document with a URL. `include(collection, doc)` leaves some out, `extra` adds paths such as `/posts`, and `lastmod` gives each document a ``: a field's name (`'updated'`, a `fields.date`) or a function returning a date. `createMiddleware({ sitemap: { content, collections } })` serves it at `/sitemap.xml`.
- **Slugs**: a page at `/:slug` can't be called `posts` while posts live under `/posts/`. `createContent` refuses such slugs, so `reservedSlugs` only needs your own routes.
When patterns overlap, the more specific one wins (`/posts/:slug` over `/:slug`), as in routers.
## Manual order
Some sets are curated rather than sorted: photos, a timeline, project cards. Make the collection `orderable` and editors put its documents in order in the admin, by dragging a row of the document list or with its move up and down buttons.
```ts
export const projects = defineCollection({
name: 'projects',
label: 'Projects',
fields: { title: fields.text({ label: 'Title', required: true }), image: fields.image({ label: 'Image' }) },
orderable: true,
});
```
- Lists return documents in that order: `content.list(projects)` needs no `sort`. Pass a `sort` to order them another way for one list.
- New documents go to the end.
- The order is kept in each document's `position` (1, 2, 3…), next to its `id`, so it works with every store, the JSON files included, and shows up in git diffs. `createContent` manages it: saves keep the stored position (a stale editor can't undo a move), and `content.move(collection, id, index)` moves a document, rewriting only the documents whose position changes. Nobody types a position.
- Collections without `orderable` work as before, sorted by `sort`.
### Making an existing collection orderable
Nothing to migrate. Documents without a position come after those with one, in the collection's `sort` order, so a collection you make orderable keeps its current order. The first move, or the first save of a new document, gives every document a position in that order (one write per document, once). Files you add by hand without a position join the end the same way.
If your app wraps `Content` for the admin (as the example's server functions do), add `move` to the wrapper: without it the admin shows no reorder controls.
## Many collections, one admin
Pass them all to `` in the order its rail should list them, and to `createContent`, which checks that every reference field names a known collection.
```ts
export const collections = [pages, posts, products, categories] as const;
```
## `defineCollection` (function)
`import { defineCollection } from '@mortar-kit/core'`
```ts
function defineCollection>>(def: CollectionDefinition): Collection
```
Registers a collection.
### Parameters
- `def: CollectionDefinition`
### Returns
`Collection`
### Example
```ts
export const posts = defineCollection({
name: 'posts',
label: 'Posts',
fields: { title: fields.text({ label: 'Title', required: true }), date: fields.date({ label: 'Date' }) },
body: true,
sort: { field: 'date', order: 'desc' },
});
```
## `Doc` (interface)
`import { Doc } from '@mortar-kit/core'`
```ts
interface Doc>
```
One document of a collection.
### Properties
- `id: string`: Stable id: references store it, so it never changes (unlike the slug).
- `slug: string`: The document's address within its collection, e.g. `hello-world`. Unique per collection.
- `position?: number`: Where the document is in its collection's manual order (lower first),
when the collection is `orderable`. `createContent` sets it: on the
first save and on `move`; saves keep the stored one.
- `fields: F`: The collection's fields.
- `entries?: PageEntry[]`: Brick entries; always an array when the collection has a body.
Source: https://docs.mortar-kit.dev/docs/rendering-pages
# Rendering pages
> Read documents in your routes and render their bodies with PageView.
Mortar stays out of routing. Your routes decide which document to show, read it, and render it inside your own layout. Mortar renders the body.
## Provide the content
Wrap your app in `ContentContext` with a `ContentSource`: two functions that list and get documents, usually your server functions.
```tsx
import { ContentContext } from '@mortar-kit/core';
...
```
## Read a document
`useContent()` gives a typed reader: pass a collection object and you get documents with typed fields.
```tsx
import { PageView, useContent } from '@mortar-kit/core';
import { useParams } from '@solidjs/router';
import { createMemo, Show } from 'solid-js';
export default function PostRoute() {
const params = useParams<{ slug: string }>();
const content = useContent();
const post = createMemo(() => content.get(posts, { slug: params.slug }));
return (
}>
{(p) => (
{p().fields.title}
)}
);
}
```
Reads return promises. A memo holding a promise is pending until it lands, so put a `` boundary around your routes. On the server the page waits for it, so the HTML holds the content.
Lists work the same way:
```ts
const latest = createMemo(() => content.list(posts, { limit: 5 }));
const inCategory = createMemo(() => content.list(products, { where: { category: categoryId() } }));
```
`where` keeps documents whose `id`, `slug` or top-level field equals each value. `sort` overrides the collection's order, and `limit` takes 1 to 100. Lists leave out bodies.
## Layouts
Detail pages are your code: a post's title and date, a product's price. Keep them in layout components, so the admin's preview can render documents inside the same layouts (see [The admin](https://docs.mortar-kit.dev/docs/admin.md)).
## Missing documents
`get` returns `null` when there's no document. Render your own not-found view, and set the status with `httpStatus(404)` from `@solidjs/web` when rendering on the server.
## `PageView` (function)
`import { PageView } from '@mortar-kit/core'`
```ts
function PageView(props: PageViewProps): Element
```
Renders every entry with its brick's component. Bricks that load data read `ContentContext`.
### Parameters
- `props: PageViewProps`
### Returns
`Element`
## `useContent` (function)
`import { useContent } from '@mortar-kit/core'`
```ts
function useContent(): ContentReader
```
The content reader for the current component, from `ContentContext`.
Call it in a component body; read with it in a memo (under ``).
Throws if no source is provided.
### Returns
`ContentReader`
Source: https://docs.mortar-kit.dev/docs/loading-data
# Loading data
> Bricks that show other documents, such as the latest posts or a product grid.
Some bricks show more than their own data: the newest posts, the products in a category. Give such a brick a `load` function. It receives the brick's data and a typed reader, and what it returns reaches the component as `props.loaded`.
```tsx
export const latestPosts = defineBrick({
name: 'latest-posts',
label: 'Latest posts',
schema: {
heading: fields.text({ label: 'Heading', default: 'Latest posts' }),
limit: fields.number({ label: 'How many', min: 1, max: 12, default: 3 }),
},
load: (data, content) => content.list(posts, { limit: data.limit }),
component: (props) => (
),
});
```
Write `load` before `component`, so `props.loaded` gets its type.
## Where it runs
- **On the server**, when the page renders, so the content is in the HTML. Pages that ship no JavaScript work too.
- **In the admin preview**, in the browser. It reads saved content, and loads again after each save.
It reads from the `ContentContext` your app provides.
## What makes it load again
Read the `data` fields your loader depends on **before its first `await`**. Changing those fields loads again, and changing others doesn't. While a new load is in flight, the previous result stays on screen.
A source can also offer `track()`: `PageView` calls it before each load, where reads are tracked, so reading a signal there makes every loader run again when it changes. The admin preview does this after saves, and this site does it to swap in your edits.
> **Note: Return plain JSON**
>
> What `load` returns may be sent from the server to the browser with the page, so keep it plain data: no functions, class instances or promises inside.
## `ContentReader` (interface)
`import { ContentReader } from '@mortar-kit/core'`
```ts
interface ContentReader
```
Typed reads: pass a collection, get its documents with typed fields.
### Properties
- `list: (collection: Collection, options?: ListOptions) => Promise>[]>`: Documents of the collection, without their bodies.
- `get: (collection: Collection, ref: DocRef) => Promise> | null>`: One document of the collection, or null.
Source: https://docs.mortar-kit.dev/docs/forms
# Handling forms
> Give a brick an action: its form works without JavaScript, and with it only the brick updates.
A brick can handle its own form: a contact form, a newsletter sign-up, a quote request. Give it an `action`, render a `` in its component, and read the outcome from `props.submission`.
- **Without JavaScript** (Mortar's [pages without JavaScript](https://docs.mortar-kit.dev/docs/no-javascript.md)), the form is a plain post. The action runs on the server, and the browser comes back to the same page with the result, which the brick shows. A refresh doesn't post twice.
- **With JavaScript** (the admin, or an `interactive` brick, which hydrates on its own), the same form is sent in the background, and only that brick updates. The page doesn't reload.
The brick is the same either way. The example site (`examples/site`) has a working contact form at `/contact`.
## The brick
```tsx
import { ActionForm, defineBrick, fields } from '@mortar-kit/core';
import { Show } from 'solid-js';
type Result = { status: 'sent' } | { status: 'invalid'; values: Record } | { status: 'failed' };
export const contactForm = defineBrick({
name: 'contact-form',
label: 'Contact form',
interactive: true,
schema: {
heading: fields.text({ label: 'Heading', default: 'Get in touch' }),
to: fields.text({ label: 'Send to', help: "Empty: the site's inbox.", private: true }),
},
async action({ form, data, context }): Promise {
const name = String(form.get('name') ?? '').trim();
const email = String(form.get('email') ?? '').trim();
const message = String(form.get('message') ?? '').trim();
if (!name || !email.includes('@') || !message) return { status: 'invalid', values: { name, email, message } };
const to = data.to || context.inbox;
if (!context.mailer || !to) return { status: 'failed' };
await context.mailer.send({ to, replyTo: email, subject: `Contact form: ${name}`, text: message });
return { status: 'sent' };
},
component: (props) => (
{props.data.heading}
Thanks! We'll reply by email.
}>
),
});
```
- `action` gets the posted `form` (untrusted: check every value), the entry's `data`, the `request`, and the app's `context`. What it returns is the result: keep it plain JSON, and small, since without JavaScript it rides back in a cookie (about 4 kB).
- `props.submission` is the entry's latest post: `pending`, then `result`, or `error` if the action threw. It's undefined until the form is sent.
- Write `action` before `component`, so the result has its type.
- `interactive: true` makes the brick an island on public pages, so its form answers in place there too (see [Islands](https://docs.mortar-kit.dev/docs/no-javascript.md#islands)). `private: true` keeps the address out of what the island sends to the browser.
> **Note: The data comes from storage, not the form**
>
> A `` names its entry (collection, document and entry id), never its data. The server reads the entry and passes its stored `data` to the action, so a visitor can't change what the editor set. An editable "Send to" address is safe for that reason.
## Server-only services
The brick's module also reaches the browser (in the admin, and in a brick that hydrates), so an action doesn't import the mailer, a database or a secret. The app passes them in `context`, and declares their types by augmenting `ActionContext`:
```ts
declare module '@mortar-kit/core' {
interface ActionContext {
mailer?: Mailer;
inbox?: string;
}
}
```
## Wiring it up
Actions run through one server function in the app, which calls `content.runAction` with the reference and form the browser sent. That's the place for a per-client limit, since the form is public:
```ts
// src/server/content.ts
'use server';
export async function runBrickAction(ref: EntryRef, form: FormData | URLSearchParams): Promise {
const request = getRequestEvent()?.request;
if (overLimit(request)) throw new Error('Too many form posts.');
return respond(await content.runAction(ref, form, { request, context: { mailer, inbox } }), { revalidate: '' });
}
```
Then the app tells Mortar where forms post and how to read results back, with `BrickActionsContext`. With Solid's router, a form action over that server function does both. It posts plainly without JavaScript (the result comes back in a one-time cookie the router reads), and in the background with it:
```ts
// src/actions.ts
const post = formAction(runBrickAction, 'mortar-brick-action');
export const brickActions: BrickActions = {
action: (ref) => post.with(ref),
useSubmission: (ref) => {
const all = useSubmissions(post, (input) => sameEntry(input[0], ref()));
return () => {
const last = all.at(-1);
return last && { pending: last.result === undefined && last.error === undefined, result: last.result, error: last.error };
};
},
};
```
```tsx
// App.tsx: around the router
…
```
On a public page without the router, an interactive brick's form goes through `islandActions` instead, which calls the same server function in the background. See [Islands](https://docs.mortar-kit.dev/docs/no-javascript.md#islands).
Finally, pass the document to `PageView`, so each form can name its entry: ``. The admin preview does this itself. It doesn't send forms, so editors can click around in them.
> **Tip: Spam**
>
> The example adds a hidden honeypot field (a bot fills it in, and the action answers "sent" without sending) and a per-client limit with `createLimiter` in the server function. For a busy form, add a CAPTCHA and verify its token in the action.
## `ActionForm` (function)
`import { ActionForm } from '@mortar-kit/core'`
```ts
function ActionForm(props: ActionFormProps): Element
```
A form that posts to its brick's `action`. Use it in the component of a
brick that declares one. It's a plain `