Skip to content
Unreleased: these pages follow the main branch. The latest release is v0.5.
Build pages in Svelte

Build pages in Svelte

Since v0.6.0

In a project of the svelte stack, the Go side is the web stack’s: routes, handlers, sessions, validation, translations and logins stay in Go. The pages are Svelte 5 components in TypeScript, which Inertia’s client renders in the browser with the props a handler sends. Each page’s props are a Go struct, and the TypeScript types the components use are generated from it, so the type check catches a renamed field or route before the browser does.

This guide adds a page to a project with posts: a list of the drafts, with a filter, a count in the header, and a test.

Before you start

  • Go 1.26 and Node.js 20.19 or 22.12 or later.
  • A project of the svelte stack with posts:
anetos new shop --stack=svelte
cd shop
go tool anetos make:crud Post title:string body:text published:bool
go run . migrate
go tool anetos dev   # http://localhost:8080

anetos dev runs the app and Vite, rebuilds the app when Go code changes, and updates the frontend’s types (go run . types). Open the app’s address: Vite runs on a free port of its own, which the app’s pages load their scripts from.

Steps

1. Know where things are

FileHolds
app/handlers/pages.gopage[P](component), which declares a page, and Shared, the props every page gets
app/handlers/posts.gomake:crud’s handlers, their pages and props
routes/The routes: web.go has the pages group, posts.go the posts’ routes
frontend/src/pages/The components: Home.svelte, Posts/Index.svelte… A page named Posts/Index in Go is pages/Posts/Index.svelte
frontend/src/Layout.svelteThe header, nav and footer around every page; components/NavLink.svelte, a link marked when it’s the current page
frontend/src/components/ui/The starter theme’s components, a file each, all exported by index.ts: PageHeader, Card, Field, Input, Button, Table, Pagination, and Title for the page’s title…
frontend/src/i18n.tsuseT() for the text of locales/, useFormat() for numbers and dates
frontend/src/types/Written by go run . types: pages.ts (the props), routes.ts (the routes)
frontend/src/routes.tsroute() for the pages: the routes, with the current locale’s prefix first

2. Declare the page in Go

A page is its component’s name and the Go type of its props. Add app/handlers/drafts.go:

// illustrative: app/handlers/drafts.go
package handlers

import (
	"anetos.dev/anetos/db"
	"anetos.dev/anetos/web"

	"shop/app/models"
)

// DraftsQuery is what the drafts page reads from the URL: ?q=, a part of
// the title.
type DraftsQuery struct {
	Q string `query:"q"`
}

// DraftsProps are the drafts page's props.
type DraftsProps struct {
	Q     string     `json:"q"`
	Posts []PostItem `json:"posts"`
}

var draftsPage = page[DraftsProps]("Posts/Drafts")

// Drafts lists the posts not published yet, newest first; with ?q=, those
// whose title contains it.
func (Posts) Drafts(c *web.Ctx, in DraftsQuery) (web.Responder, error) {
	q := db.Query[models.Post](c).Where(models.PostCols.Published.Eq(false)).
		OrderBy(models.PostCols.ID.Desc()).Limit(50)
	if in.Q != "" {
		q = q.Where(models.PostCols.Title.ContainsFold(in.Q))
	}
	rows, err := q.Get()
	if err != nil {
		return nil, err
	}
	posts := make([]PostItem, len(rows))
	for i, row := range rows {
		posts[i] = postItem(row)
	}
	return draftsPage.Responder(DraftsProps{Q: in.Q, Posts: posts}), nil
}

PostItem is make:crud’s: the fields of a post the pages get, so a new column never shows by accident. Route it in routes/posts.go, with a name:

// illustrative: routes/posts.go
r.Get("/drafts", web.H(h.Drafts)).Name("posts.drafts")

page adds the page to handlers.Pages, which setup lists: go run . types (which anetos dev runs) writes DraftsProps into frontend/src/types/pages.ts, and posts.drafts into routes.ts.

3. Write the component

Add frontend/src/pages/Posts/Drafts.svelte. It takes the props, with their type from Go:

<!-- illustrative: frontend/src/pages/Posts/Drafts.svelte -->
<script lang="ts">
  // Posts/Drafts lists the posts not published yet, filtered by title.
  import { Form, Link } from '@inertiajs/svelte'
  import { Button, Cluster, Empty, Input, PageHeader, Table, Title } from '../../components/ui'
  import { useT } from '../../i18n'
  import { route } from '../../routes'
  import type { DraftsProps } from '../../types/pages'

  let { q, posts }: DraftsProps = $props()
  const t = useT()
</script>

<Title text={t('posts.drafts.title')} />
<PageHeader title={t('posts.drafts.title')} />
<Form action={route('posts.drafts')} method="get" options={{ preserveState: true }}>
  <Cluster>
    <Input name="q" defaultValue={q} aria-label={t('posts.drafts.search')} placeholder={t('posts.drafts.search')} />
    <Button variant="secondary">{t('posts.drafts.filter')}</Button>
  </Cluster>
</Form>
{#if posts.length === 0}
  <Empty text={t('posts.drafts.none')} />
{:else}
  <Table>
    <tbody>
      {#each posts as post (post.id)}
        <tr>
          <td>
            <Link href={route('posts.show', { id: post.id })}>{post.title}</Link>
          </td>
        </tr>
      {/each}
    </tbody>
  </Table>
{/if}

Title sets the page’s title (Inertia’s Svelte client has no Head). route comes from src/routes.ts, which puts the page’s locale prefix first, so a link follows a change of locale.

  • The filter is Inertia’s <Form> with method="get": it visits /drafts?q=… without a page load, and preserveState keeps what was typed. The handler reads q from the URL (DraftsQuery), and ContainsFold matches it in any case on every database (Contains follows the database: PostgreSQL’s is case-sensitive).
  • The path is /drafts, not /posts/drafts: the layout’s NavLink marks a link as the current page on the paths under it too, so under /posts/ the Posts link would be marked as well.
  • Links name their routes: route('posts.show', { id: post.id }). A route renamed in Go, or a parameter left out, fails the type check. Link visits the page without reloading the app.
  • The text comes from locales/. Add the keys to locales/en/posts.yaml, under posts::
  drafts:
    title: "Drafts"
    search: "Title contains"
    filter: "Filter"
    none: "No drafts."
    nav: "Drafts ({count})"

Svelte escapes what {…} prints, so a title holding <script> shows as text. Don’t write user data with {@html} (Protect your app in the browser).

4. Share a prop with every page

The props of Shared in app/handlers/pages.go reach every page: the app’s name, the locale, the logged-in user, the flashed notice. Add the number of drafts, for the header:

// illustrative: app/handlers/pages.go, in Shared
	// Drafts is the number of posts not published yet.
	Drafts int64 `json:"drafts"`
// illustrative: app/handlers/pages.go, in SharedProps, before the return
	drafts, err := db.Query[models.Post](c).Where(models.PostCols.Published.Eq(false)).Count()
	if err != nil {
		return Shared{}, err
	}

and Drafts: drafts, in the Shared it returns (pages.go then imports anetos.dev/anetos/db and shop/app/models). That’s a query on every page: keep shared props cheap. A component reads them with usePage(); in frontend/src/Layout.svelte, which has const page = usePage():

<!-- illustrative: frontend/src/Layout.svelte, in the nav -->
<NavLink route="posts.drafts" label={t('posts.drafts.nav', { count: page.props.drafts })} />

The layout stays mounted as pages change; the count follows each visit. A number in a message that isn’t a plural one is written as given ({count} in a plural message is formatted for the locale): pass useFormat().number(n) for the locale’s digits.

5. Take input with a form

make:crud’s Posts/Form.svelte is the pattern for a form. Inertia’s <Form> posts to the route, and the handler’s input struct validates it before the handler runs (validate:"required|max:255"). An invalid form comes back to the page with errors, by field, and what was typed stays:

<!-- illustrative: from frontend/src/pages/Posts/Form.svelte -->
<InertiaForm
  action={item ? route('posts.update', { id: item.id }) : route('posts.create')}
  method={item ? 'put' : 'post'}
  transform={(data) => ({ ...data, published: data.published === '1' })}
>
  {#snippet children({ errors, processing })}
    <Field name="title" label={t('posts.fields.title')} error={errors.title}>
      <Input defaultValue={item?.title} />
    </Field>
    <!-- … -->
    <Button disabled={processing}>{t('posts.save')}</Button>
  {/snippet}
</InertiaForm>

The form’s values are text, so transform turns them into what the handler’s input wants: true or false for the checkbox (and numbers for number fields).

After saving, the handler flashes a message and redirects (c.Session().Flash("status", …), web.RedirectRoute("posts.show", row.ID)); the layout shows it from the shared notice. The messages of the rules are translated with the rest of the text (Validation).

6. Let only logged-in users in

go tool anetos make:auth adds registration, login, two-factor authentication and the account’s pages, in Svelte, and fills the shared user prop (usePage().props.user, null for a guest); then go run . migrate creates the accounts’ tables. To keep the posts for logged-in users, move their routes into its loggedIn group: remove Posts(pages) from routes/web.go, and in routes/auth.go:

// illustrative: routes/auth.go, after loggedIn := …
Posts(loggedIn) // the posts, for logged-in users only

To let guests read the posts and only logged-in users change them, split routes/posts.go in two, and call the second from routes/auth.go with loggedIn:

// illustrative: routes/posts.go
// Posts adds the pages anyone may see: routes/web.go calls it.
func Posts(r *web.Router) {
	var h handlers.Posts
	r.Get("/posts", web.H(h.Index)).Name("posts.index")
	r.Get("/drafts", web.H(h.Drafts)).Name("posts.drafts")
	r.Get("/posts/{id}", web.H(h.Show)).Name("posts.show")
}

// PostChanges adds the pages that change posts: routes/auth.go calls it
// with its loggedIn group.
func PostChanges(r *web.Router) {
	var h handlers.Posts
	r.Get("/posts/new", h.New).Name("posts.new")
	r.Post("/posts", web.H(h.Create)).Name("posts.create")
	r.Get("/posts/{id}/edit", web.H(h.Edit)).Name("posts.edit")
	r.Put("/posts/{id}", web.H(h.Update)).Name("posts.update")
	r.Delete("/posts/{id}", web.H(h.Delete)).Name("posts.delete")
}

A guest who opens /posts/new goes to the login page; a guest’s post, put or delete gets 401: the login redirect is for pages. Hide the buttons from guests with the shared user:

<!-- illustrative: frontend/src/pages/Posts/Index.svelte, with const shared = usePage() -->
{#if shared.props.user}
  <LinkButton href={route('posts.new')}>{t('posts.new')}</LinkButton>
{/if}

(The list’s own prop is named page: name usePage()’s result otherwise.)

Hiding a button isn’t enough: the route’s group is what keeps guests out.

7. Test it

The tests are Go, and need neither Node nor a build: AssertInertia checks the component, AssertInertiaProp a prop, by its path:

// illustrative: drafts_test.go
package main

import (
	"testing"

	"anetos.dev/anetos/anetostest"
	"anetos.dev/anetos/db"

	"shop/app/models"
)

func TestDrafts(t *testing.T) {
	app := anetostest.New(t, setup)
	for _, p := range []models.Post{
		{Title: "Alpha", Body: "a"},
		{Title: "Beta", Body: "b"},
		{Title: "Out", Body: "c", Published: true},
	} {
		if err := db.Create(app.Context(), &p); err != nil {
			t.Fatal(err)
		}
	}
	app.Get("/drafts").AssertOK().AssertInertia("Posts/Drafts").
		AssertInertiaProp("posts.0.title", "Beta").AssertInertiaProp("drafts", 2)
	app.Get("/drafts?q=Alp").AssertInertiaProp("posts.0.title", "Alpha").AssertInertiaProp("q", "Alp")
}

With the posts behind a login (step 6), log a user in first: ada := anetostest.Create(app, factories.Users) and anetostest.ActingAs(app, &ada). go tool anetos check runs the tests and the frontend’s build, whose svelte-check (on TypeScript 6) type-checks every component.

8. Build it

go tool anetos build   # bin/shop

It type-checks and builds the frontend into public/build, then the binary, which embeds it: one file to deploy (Deploy).

Complete example

anetos new --stack=svelte with make:auth and make:crud is the complete example: its pages, handlers and tests are the patterns above. examples/inertia, in React, shows more of Inertia’s props: deferred, merged and flashed.

How it works

The first visit gets the HTML of views/app.templ, holding the page’s component and props; Inertia’s client renders it inside the layout. Later links and forms are requests that answer the next page’s props as JSON, and the client swaps the component in place. The routes, the session, CSRF protection (an XSRF-TOKEN cookie the client sends back) and validation are the web stack’s. Pages in Vue, React or Svelte with Inertia covers the protocol: partial reloads, deferred props, asset versions.

Testing it

See step 7. The Go tests check what the handlers send; the type check catches a component that reads a prop or route that isn’t there. To check a page in a browser, run the app with go tool anetos dev.

Common problems

ProblemCauseFix
The type check says a prop or a page doesn’t existfrontend/src/types is older than the Go codego run . types (anetos dev does after each build)
inertia: the page "Posts/Drafts" isn't in inertia.WithPagesThe page was made with inertia.NewPage instead of pageDeclare it with page[P], which lists it
no page Posts/Drafts (frontend/src/pages/Posts/Drafts.svelte) in the browser’s consoleThe component’s file is missing or named differentlyThe file’s path under pages/ is the name in Go, with .svelte
A link in the layout still goes to the old locale’s page after a change of localeInertia’s Svelte Link keeps the href it was made withWrap a link that stays mounted in {#key href}, as NavLink.svelte does
A key shows instead of its text (posts.drafts.title)It isn’t in locales/en/Add it; the server sends the catalogs to the pages

Next steps