Markdown Blog
elements man recipes/markdown-blogA blog with public read pages and admin-only write pages. Posts are stored as
markdown in the database. The public single-post page renders the markdown to
HTML inside the route handler and passes the HTML string to the template, which
writes it into the article body with raw(). Admin pages reuse the same data
through the same shared module, gated by isUserAdminOrThrow.
Four routes:
/blog: public list of published posts/blog/:slug: public single post, markdown rendered/admin/blog: admin list (every post including drafts) with edit links/admin/blog/:id: admin editor for one post;:id = "new"creates one
The shared module is at app/shared/services/posts.ts because four pages
consume it. Admin gating uses the helper from elements man recipes admin-roles.
Migration
Terminalelements create migration 'add posts' -tables=posts
app/migrations/<timestamp>-add-posts.migration.sql-- add posts -- Auto-update updatedAt on row changes. create or replace function touchUpdatedAt() returns trigger language plpgsql as $$ begin new.updatedAt = now(); return new; end; $$; create table posts ( id uuid primary key default uuidGenerateV7(), createdAt timestamptz not null default now(), updatedAt timestamptz not null default now(), title text not null, slug text not null unique, body text not null, publishedAt timestamptz ); create index postsPublishedAtIdx on posts (publishedAt desc nulls last); create trigger postsTouchUpdatedAt before update on posts for each row execute function touchUpdatedAt();
publishedAt is nullable. A null value means the post is a draft and the public
pages skip it. The unique constraint on slug keeps URLs unambiguous.
Markdown package
The recipe uses marked, which exposes a single parse(text) call that
returns HTML:
Terminalelements install marked
Posts module
app/shared/services/posts.tsimport { sql, ValidationError } from "@elements/app"; import { isUserAdminOrThrow } from "#app/shared/services/admin"; export interface Post { id: string; updatedAt: Date; title: string; slug: string; body: string; publishedAt: Date | null; } export interface PostInput { title: string; slug: string; body: string; publishedAt: Date | null; } export function listPublished(): Post[] { return sql<Post>(` select id, updatedAt, title, slug, body, publishedAt from posts where publishedAt is not null and publishedAt <= now() order by publishedAt desc `).all(); } export function getPublishedBySlug(slug: string): Post { return sql<Post>(` select id, updatedAt, title, slug, body, publishedAt from posts where slug = ${slug} and publishedAt is not null and publishedAt <= now() `).firstOrThrow("post not found"); } export function listAll(): Post[] { return sql<Post>(` select id, updatedAt, title, slug, body, publishedAt from posts order by updatedAt desc `).all(); } export function getById(id: string): Post { return sql<Post>(` select id, updatedAt, title, slug, body, publishedAt from posts where id = ${id} `).firstOrThrow("post not found"); } /** @rpc */ export function savePost(id: string | null, input: PostInput): Post { isUserAdminOrThrow(); if (input.title.trim().length === 0) { throw new ValidationError("title is required"); } if (!/^[a-z0-9-]+$/.test(input.slug)) { throw new ValidationError("slug must be lowercase letters, numbers, and dashes"); } if (id) { return sql<Post>(` update posts set title = ${input.title}, slug = ${input.slug}, body = ${input.body}, publishedAt = ${input.publishedAt} where id = ${id} returning id, updatedAt, title, slug, body, publishedAt `).firstOrThrow("post not found"); } return sql<Post>(` insert into posts ( title, slug, body, publishedAt ) values ( ${input.title}, ${input.slug}, ${input.body}, ${input.publishedAt} ) returning id, updatedAt, title, slug, body, publishedAt `).firstOrThrow(); } /** @rpc */ export function deletePost(id: string) { isUserAdminOrThrow(); sql(` delete from posts where id = ${id} `); }
Read helpers (listPublished, getPublishedBySlug, listAll, getById) are
regular functions called from route handlers, which run on the server. Write
functions (savePost, deletePost) are @rpc because the admin pages call
them from the browser, and they're gated with isUserAdminOrThrow at the top.
Public list
Terminalelements create page blog
app/pages/blog/index.tsimport { Request, Response } from "@elements/app"; import blog from "./template"; import { listPublished } from "#app/shared/services/posts"; export default function route(req: Request, res: Response) { return new blog({ posts: listPublished() }); }
app/pages/blog/template.ehtmlimport "./style.css"; import { Item, ItemGroup } from "@elements/ui/item"; import { Empty } from "@elements/ui/empty"; import { Post } from "#app/shared/services/posts"; <html class="page-blog" (posts: Post[])> <main class="page-shell"> <h1>blog</h1> <ItemGroup label="posts"> <Item e:for={p of posts} href={`/blog/${p.slug}`} title={p.title} description={p.publishedAt?.toLocaleDateString() ?? ""} /> </ItemGroup> <Empty e:if={posts.length === 0} title="no posts yet" /> </main> </html>
The public list shows only published posts (the read helper filters by
publishedAt is not null and publishedAt <= now()). No auth needed. Each post
is an Item with href, so the whole row is the link, and Empty stands in
for an empty list.
Public single post
Terminalelements create page blog-post
app/pages/blog-post/index.tsimport { Request, Response } from "@elements/app"; import { marked } from "marked"; import blogPost from "./template"; import { getPublishedBySlug } from "#app/shared/services/posts"; export default function route(req: Request, res: Response) { let post = getPublishedBySlug(req.params.slug); let html = marked.parse(post.body) as string; return new blogPost({ post, html }); }
The route loads the post by slug, runs marked.parse(post.body) to get an HTML
string, and passes both to the template. Rendering on the server puts the public
HTML in the first response, for search engines and for readers with JavaScript
off; a live editor renders in the browser instead
(elements man recipes render-markdown).
getPublishedBySlug throws NotFoundError (a safe 404) when no row matches.
marked.parse is sync by default and returns string; the cast pins the
return type, since the declared signature allows async modes this recipe
doesn't use.
app/pages/blog-post/template.ehtmlimport "./style.css"; import { raw } from "@elements/app"; import { Post } from "#app/shared/services/posts"; <html class="page-blog-post" ( post: Post, html: string, )> <main class="page-shell"> <article> <header> <h1>{post.title}</h1> <time>{post.publishedAt?.toLocaleDateString()}</time> </header> <div class="body">{raw(html)}</div> </article> </main> </html>
{html} on its own would HTML-escape the rendered markdown. {raw(html)}
opts out of escaping for this one binding so the markup renders as HTML; the
Notes below cover the trust boundary.
Admin list
Terminalelements create page admin-blog
app/pages/admin-blog/index.tsimport { Request, Response } from "@elements/app"; import adminBlog from "./template"; import { isUserAdminOrThrow } from "#app/shared/services/admin"; import { listAll } from "#app/shared/services/posts"; export default function route(req: Request, res: Response) { isUserAdminOrThrow(); return new adminBlog({ posts: listAll() }); }
app/pages/admin-blog/template.ehtmlimport "./style.css"; import { Button } from "@elements/ui/button"; import { Badge } from "@elements/ui/badge"; import { Table, TableHead, TableCell } from "@elements/ui/table"; import { Post } from "#app/shared/services/posts"; <html class="page-admin-blog" (posts: Post[])> <main class="page-shell"> <header class="row"> <h1>posts</h1> <Button href="/admin/blog/new" variant="primary">new post</Button> </header> <Table label="posts"> <table> <thead> <tr> <TableHead>title</TableHead> <TableHead>slug</TableHead> <TableHead>status</TableHead> <TableHead>updated</TableHead> <TableHead></TableHead> </tr> </thead> <tbody> <tr e:for={p of posts}> <TableCell>{p.title}</TableCell> <TableCell>{p.slug}</TableCell> <TableCell> <Badge variant={p.publishedAt ? "success" : "secondary"}> {p.publishedAt ? "published" : "draft"} </Badge> </TableCell> <TableCell>{p.updatedAt.toLocaleDateString()}</TableCell> <TableCell align="end"> <Button href={`/admin/blog/${p.id}`} size="sm">edit</Button> </TableCell> </tr> <tr e:if={posts.length === 0}> <TableCell colspan={5}>no posts yet. <a href="/admin/blog/new">create one</a>.</TableCell> </tr> </tbody> </table> </Table> </main> </html>
The admin list shows every post regardless of publishedAt, in a Table with
a Badge for the status. The "edit" button routes to /admin/blog/:id; "new
post" routes to /admin/blog/new, the same edit route with :id === "new".
Admin editor
Terminalelements create page edit-post
app/pages/edit-post/index.tsimport { Request, Response } from "@elements/app"; import editPost from "./template"; import { isUserAdminOrThrow } from "#app/shared/services/admin"; import { getById, Post } from "#app/shared/services/posts"; export default function route(req: Request, res: Response) { isUserAdminOrThrow(); let isNew = req.params.id === "new"; if (isNew) { let blank: Post = { id: "", updatedAt: new Date(), title: "", slug: "", body: "", publishedAt: null, }; return new editPost({ post: blank, isNew: true, }); } let post = getById(req.params.id); return new editPost({ post, isNew: false, }); }
app/pages/edit-post/template.ehtmlimport "./style.css"; import { ValidationError, redirect } from "@elements/app"; import { Field } from "@elements/ui/field"; import { Input } from "@elements/ui/input"; import { Textarea } from "@elements/ui/textarea"; import { Checkbox } from "@elements/ui/checkbox"; import { Alert } from "@elements/ui/alert"; import { Button } from "@elements/ui/button"; import { AlertDialog, AlertDialogFooter, AlertDialogCancel, AlertDialogAction, } from "@elements/ui/alert-dialog"; import { Post, PostInput, savePost, deletePost, } from "#app/shared/services/posts"; function emptyForm(post: Post): PostInput { return { title: post.title, slug: post.slug, body: post.body, publishedAt: post.publishedAt, }; } function onSave( postId: string, isNew: boolean, form: PostInput, error: { value: string }, ) { try { let saved = savePost(isNew ? null : postId, form); redirect(`/admin/blog/${saved.id}`); } catch (err: any) { if (err instanceof ValidationError) { error.value = err.message; return; } throw err; } } function onDelete(postId: string) { deletePost(postId); redirect("/admin/blog"); } function onTogglePublish(form: PostInput) { form.publishedAt = form.publishedAt === null ? new Date() : null; } <html class="page-edit-post" ( post: Post, isNew: boolean, private form: PostInput = emptyForm(post), private error: { value: string } = { value: "" }, )> <main class="page-shell is-form"> <header class="row"> <h1>{isNew ? "new post" : "edit post"}</h1> <Button href="/admin/blog" variant="link">back to list</Button> <AlertDialog e:if={!isNew} title="delete this post?" description="Its URL stops working."> <Button slot="trigger" variant="danger">delete</Button> <form onsubmit={() => onDelete(post.id)}> <AlertDialogFooter> <AlertDialogCancel>cancel</AlertDialogCancel> <AlertDialogAction variant="danger" type="submit">delete</AlertDialogAction> </AlertDialogFooter> </form> </AlertDialog> </header> <form class="stack" onsubmit={() => onSave(post.id, isNew, form, error)}> <Field label="title" required> <Input value={form.title} /> </Field> <Field label="slug" required> <Input value={form.slug} placeholder="my-post" /> </Field> <Field label="body (markdown)"> <Textarea value={form.body} rows={20} autosize={false} /> </Field> <Field orientation="horizontal" label="published"> <Checkbox checked={form.publishedAt !== null} onCheckedChange={() => onTogglePublish(form)} /> </Field> <Alert e:if={error.value} variant="danger" description={error.value} /> <Button type="submit" variant="primary">save</Button> </form> </main> </html>
emptyForm(post) copies the post's fields into a new PostInput so the form
binds to a separate object. Each field is a Field around an Input or
Textarea; required on the field marks the label and the control. The
published Checkbox toggles publishedAt between null (draft) and
new Date() (published now); for a scheduled publish, swap it for an
<Input type="datetime-local">. A server-side ValidationError shows as an
Alert.
On save, the RPC returns the saved post and the handler navigates to its
/admin/blog/:id URL, which reloads the form from the canonical row.
Delete is an AlertDialog in the header, outside the edit form. Its action is
the submit button of a form inside the alert, so onDelete runs from that
form's onsubmit once the user confirms; the click closes the dialog and the
handler navigates to the admin list.
Routes
Register all four routes in index.ts:
index.tsimport blog from "#app/pages/blog"; import blogPost from "#app/pages/blog-post"; import adminBlog from "#app/pages/admin-blog"; import editPost from "#app/pages/edit-post"; // ... app.route("/blog", blog); app.route("/blog/:slug", blogPost); app.route("/admin/blog", adminBlog); app.route("/admin/blog/:id", editPost);
Notes
- One RPC for create and update.
savePost(id, input)takesid: string | null.nullinserts; a real id updates. The template branches onisNewto decide which to pass. - Trust boundary at the renderer.
markedescapes HTML in the input by default, so its output is safe to pass toraw(). If you configuremarkedto allow raw HTML in markdown, sanitize the output withDOMPurify(or equivalent) beforeraw(). - Scheduled posts. Setting
publishedAtto a future timestamp keeps the post out of the public list until that time arrives. - Caching. Public read pages change rarely. Elements' ETag layer handles them: a repeat request for a published post revalidates instead of re-running the route.
- Tags or categories. Add a
tags text[]column toposts, awhere ${tag} = any(tags)filter in the public list, and aTagsInputin the editor.