Getting started/Quickstart: First Feature
Quickstart: First Feature
Build a real feature end-to-end with a module, Nock schema, typed form route, Crest view, and test.
On this page
This guide builds a tasks feature in a fresh Fletch application: a database table managed by Nock, typed queries, a validated HTML form route, a Crest view, and a module test.
1. Create the application
Scaffold a new project with the CLI:
fletch new myapp
cd myapp
To test against an unreleased local checkout of Fletch, pass --fletch-path /path/to/fletch to fletch new.
A default Fletch application compiles as pure Go with CGO_ENABLED=0 and requires zero Node tooling. Development runs against an embedded SQLite database at storage/app.db with auto_migrate: true. Production config in config/environments/production.yaml sets auto_migrate: false so schema changes run explicitly during deploys.
If a project needs JavaScript bundling or an import map, pass --js esbuild|importmap|vite and --pm npm|pnpm|bun when running fletch new. See Assets & Images for frontend pipeline options.
fletch new creates the modular monolith layout:
myapp/
main.go # calls bootstrap.App().Main(context.Background())
bootstrap/
app.go # wires config, database, and app.Mount(...)
assets.go # asset embedding and manifest wiring
storage.go # storage backend setup
config/ # base YAML and config/environments/*.yaml
modules/
home/ # starter vertical slice
ui/
layouts/
app.crest # shared HTML page layout
components/ # shared Crest primitives
partials/ # shared fragments (nav, header, flash)
database/
migrations/ # SQL migrations and snapshot.json
resources/ # source CSS and JS
public/ # static files served as-is
storage/ # local SQLite file (storage/app.db) and uploads
tests/ # cross-module integration tests
2. Scaffold the tasks module
Generate a vertical slice for tasks:
fletch make module tasks
This creates modules/tasks/ with module.go, routes.go, handlers.go, service.go, store.go, schema/schema.go, views/, jobs.go, events.go, policy.go, and module_test.go. Table definitions live in the modules/tasks/schema/ sub-package so any package of the module can import the generated code.
The command also mounts the module in bootstrap/app.go, next to the starter module:
if err := app.Mount(
home.New(db, "myapp"),
tasks.New(db),
); err != nil {
return nil, fmt.Errorf("mount modules: %w", err)
}
Any directory under modules/ that is left unmounted triggers diagnostic W0512 when you run fletch check.
3. Define the table schema
Replace the generated table in modules/tasks/schema/schema.go:
package schema
import "github.com/fletchhq/fletch/nock/schema"
var Tables = []*schema.TableDef{
schema.Table("tasks",
schema.Col("id").BigInt().PrimaryKey(),
schema.Col("title").Text().NotNull(),
schema.Col("done").Bool().NotNull().Default("false"),
schema.Timestamps(),
),
}
schema.Timestamps() adds created_at and updated_at columns.
4. Generate migrations and typed query code
Diff the schema declarations under modules/*/ against database/migrations/snapshot.json to write a timestamped SQL migration:
fletch db generate create_tasks
The generated file under database/migrations/ uses -- +fletch up and -- +fletch down sections so you can inspect or edit the SQL before applying it.
Apply the migration and generate the Go code:
fletch db migrate
fletch gen
With auto_migrate: true, the app also runs pending migrations when it starts, so fletch dev picks up new migrations on its own.
fletch gen writes three kinds of generated code:
modules/tasks/schema/schema_gen.gocontainingTasks(the table and its typed column descriptors),TasksRow,TasksNew, andTasksPatch.*_crest.gocompiled templates next to your.crestfiles.*_bind.gobinders for the input structs of your typed routes, such asmodules/tasks/handlers_bind.go.
Run fletch gen again after the next three steps, since they add a template and route inputs.
5. Query the database
The scaffold keeps queries in modules/tasks/store.go and exposes them through service.go. Replace store.go:
package tasks
import (
"context"
"github.com/fletchhq/fletch/nock"
"myapp/modules/tasks/schema"
)
type store struct {
db nock.DB
}
func (s store) list(ctx context.Context, limit int) ([]schema.TasksRow, error) {
return nock.All[schema.TasksRow](ctx, s.db,
nock.Select(schema.Tasks.AllColumns()...).
From(schema.Tasks).
OrderBy(schema.Tasks.ID.Desc()).
Limit(limit))
}
func (s store) create(ctx context.Context, title string) error {
_, err := nock.Exec(ctx, s.db,
nock.Insert(schema.Tasks).Values(schema.Tasks.Title.Set(title)))
return err
}
Then replace service.go:
package tasks
import (
"context"
"github.com/fletchhq/fletch/nock"
"myapp/modules/tasks/schema"
)
type Service struct {
store store
}
func NewService(db nock.DB) *Service {
return &Service{store: store{db: db}}
}
func (s *Service) List(ctx context.Context) ([]schema.TasksRow, error) {
return s.store.list(ctx, 100)
}
func (s *Service) Create(ctx context.Context, title string) error {
return s.store.create(ctx, title)
}
Column types are checked at compile time: passing a non-string to schema.Tasks.Title.Set(...) fails go build.
6. Wire typed page and form routes
The generated Register method in module.go calls m.routes(a). Keep that method and replace its body in modules/tasks/routes.go:
package tasks
import (
"github.com/fletchhq/fletch"
"github.com/fletchhq/fletch/router"
)
func (m *Module) routes(a *fletch.App) {
r := a.Router()
router.GetPage(r, "tasks.index", "/tasks", m.index)
router.PostForm(r, "tasks.create", "/tasks", m.create)
}
Both registrars take the router, a route name, a pattern, and a handler of type func(*router.Ctx, *Input) (*router.PageResult, error).
Define the input structs and handlers in modules/tasks/handlers.go. Embedding fletch.Public marks a route as intentionally unauthenticated (otherwise implement Authorize(ctx context.Context) error on the input struct). Embedding router.FormErrors tells the router to collect binding and validation errors onto the input struct instead of answering 400 before your handler runs.
package tasks
import (
"github.com/fletchhq/fletch"
"github.com/fletchhq/fletch/router"
"myapp/modules/tasks/schema"
"myapp/modules/tasks/views"
)
type ListTasksInput struct {
fletch.Public
}
type CreateTaskInput struct {
fletch.Public
router.FormErrors
Title string `form:"title,trim" validate:"required"`
}
func (m *Module) index(c *router.Ctx, _ *ListTasksInput) (*router.PageResult, error) {
rows, err := m.svc.List(c.Context())
if err != nil {
return nil, err
}
return router.Page(views.Index{Tasks: toItems(rows)}), nil
}
func (m *Module) create(c *router.Ctx, in *CreateTaskInput) (*router.PageResult, error) {
if !in.Valid() {
rows, err := m.svc.List(c.Context())
if err != nil {
return nil, err
}
return router.Page(views.Index{
Tasks: toItems(rows),
Title: in.Title,
TitleError: in.FieldError("title"),
}), nil
}
if err := m.svc.Create(c.Context(), in.Title); err != nil {
return nil, err
}
return router.SeeOther("/tasks"), nil
}
func toItems(rows []schema.TasksRow) []views.TaskItem {
items := make([]views.TaskItem, len(rows))
for i, r := range rows {
items[i] = views.TaskItem{ID: r.ID, Title: r.Title}
}
return items
}
When the input is not valid and create returns router.Page(...) without an explicit status code, the router responds with 422 Unprocessable Entity and Cache-Control: no-store. On success, router.SeeOther("/tasks") returns a 303 See Other redirect.
7. Render the Crest view
Define the view props in modules/tasks/views/index.go. The blank import of myapp/ui/layouts lets the template use <layouts.App>:
package views
import _ "myapp/ui/layouts"
type TaskItem struct {
ID int64
Title string
}
type Index struct {
Tasks []TaskItem
Title string
TitleError string
}
Then write modules/tasks/views/index.crest. The receiver is i, from the first letter of Index:
<layouts.App title="Tasks">
<h1>Tasks</h1>
<form method="post" action="/tasks">
<label for="title">New task</label>
<input id="title" name="title" type="text" value={i.Title} />
{if i.TitleError != ""}
<p class="error">{i.TitleError}</p>
{/if}
<button type="submit">Add task</button>
</form>
<ul>
{for _, t := range i.Tasks key t.ID}
<li>{t.Title}</li>
{/for}
</ul>
</layouts.App>
The new app does not install CSRF protection. Before you ship forms, register csrf.Element() in fletch.plugins.go, add auth.OriginProtection and fletch.CSRF middleware, and put <f:csrf /> inside each form. See Security.
Now run fletch gen to compile the template and write the binders for the two input structs. Re-run it whenever you edit .crest templates or route input structs outside fletch dev.
8. Write a module test
Replace modules/tasks/module_test.go. It migrates an in-memory SQLite database with the app’s migrations and drives the routes through testkit:
package tasks_test
import (
"os"
"strings"
"testing"
"github.com/fletchhq/fletch"
"github.com/fletchhq/fletch/nock/migrate"
"github.com/fletchhq/fletch/nock/sqlite"
"github.com/fletchhq/fletch/testkit"
"myapp/modules/tasks"
)
func newModule(t *testing.T) *tasks.Module {
t.Helper()
db := sqlite.Memory(t)
if _, err := migrate.New(db.Database, os.DirFS("../../database/migrations")).Up(t.Context()); err != nil {
t.Fatal(err)
}
return tasks.New(db)
}
func TestCreateTask(t *testing.T) {
m := newModule(t)
tk := testkit.NewFor(t, func(d testkit.Deps) (*fletch.App, error) {
app := fletch.New(d.Options()...)
return app, app.Mount(m)
})
tk.PostForm("/tasks", map[string]string{"title": ""}).RequireStatus(422)
tk.PostForm("/tasks", map[string]string{"title": "Write docs"}).RequireStatus(303)
if body := tk.Get("/tasks").RequireStatus(200).Text(); !strings.Contains(body, "Write docs") {
t.Fatalf("page = %q", body)
}
}
9. Verify and run locally
Run static analysis and the test suite:
fletch check
go test ./...
fletch check validates your application before runtime:
| Codes | What is checked |
|---|---|
W0101–W0104 |
Route definitions, duplicate paths, and handler signatures |
W0201 |
Authorization coverage (every route declares fletch.Public or Authorize) |
W0401 |
Missing or broken asset references |
W0510–W0515 |
Module imports, table ownership, mounted modules, schema drift, OpenAPI staleness, and invalid schema declarations |
Start the development server:
fletch dev
Your application runs at http://127.0.0.1:3000. The built-in dev dashboard starts on http://127.0.0.1:4000 with live request traces, database inspection, jobs, mail preview, and logs.