Reference

CLI reference

Every refrakt command, what it writes, and what it changes in your project.

Running the CLI

The CLI is the refrakt_cli package, a dev-dependency of every project made by refrakt new. Run it from inside the project:

gleam run -m refrakt_cli -- <command>

# or, with an alias
alias refrakt='gleam run -m refrakt_cli --'
refrakt <command>

To create your first project, run it from a throwaway one:

gleam new refrakt_bootstrap && cd refrakt_bootstrap
gleam add --dev refrakt_cli
gleam run -m refrakt_cli -- new ../my_app --db sqlite
cd ../my_app && rm -rf ../refrakt_bootstrap

Commands that work on an existing project read the app name from gleam.toml and detect the database from its dependencies (pog for PostgreSQL, sqlight for SQLite). Everything a generator writes is run through gleam format.

Command
new <name>Create a project
gen resource <name> <fields...>Full CRUD resource, or a JSON API with --api
gen page <name>A page handler and route
gen authRegister, login, logout, sessions
gen island <name>A Lustre client-side island
gen live <name>A Lustre server component over WebSocket
gen migration <name>An empty SQL migration
gen deployDockerfile, bin/migrate, and fly.toml with --fly
routesPrint the route table
diffCompare the app with what the current CLI generates
migrateRun pending migrations
seedRun database seeds
buildCompile islands to JavaScript
assets setup, assets buildTailwind CSS setup and build
devDev server with live reload
help, version

new

refrakt new my_app
refrakt new my_app --db postgres
refrakt new my_app --db sqlite
refrakt new path/to/my_app    # the package is named my_app
Flag
--db postgresAdd Pog and a data/repo.gleam that connects to PostgreSQL
--db sqliteAdd Sqlight and a data/repo.gleam for SQLite
noneNo database

Writes the entry point, typed config (PORT, SECRET_KEY_BASE, APP_ENV), the shared Context, the router, a home handler, an error handler, the root layout, a flash component, CSS and JS in priv/static/, and tests. When APP_ENV is dev (the default), the router’s middleware turns a crash into a page showing the error, the stack trace and the request; in test and prod it logs the crash and returns a plain 500. Set APP_ENV=prod in production.

The middleware also blocks cross-site form submissions with refrakt/csrf: a POST, PUT or DELETE that a browser sends from another site gets a 403. It checks the Sec-Fetch-Site, Origin and Referer headers, so forms need no hidden token. Requests without those headers, such as curl or another server calling your JSON API, go through with their cookies removed.

At startup the app refuses to run with a SECRET_KEY_BASE shorter than 64 bytes, and in prod also when it is missing or still the generated development value.

gen resource

refrakt gen resource posts title:string body:text published:bool
refrakt gen resource products name:string price:float stock:int
refrakt gen resource comments body:text --belongs-to posts
refrakt gen resource posts title:string body:text --api

The name is plural. Types and files use the singular: Post, post_handler.gleam, post_repo.gleam.

It needs a project created with --db postgres or --db sqlite; in a project without a database it stops and writes nothing.

HTML mode writes:

  • web/<singular>_handler.gleam: index, show, new, create, edit, update, delete
  • web/<singular>_views.gleam: index_view, show_view, form_view
  • web/forms/<singular>_form.gleam: the form and params types, empty, from_<singular>, from_form_data, decode
  • domain/<singular>.gleam: the domain type
  • data/<singular>_repo.gleam: list, get, create, update, delete in raw SQL
  • data/migrations/NNN_create_<name>.sql
  • test/<app>/web/<singular>_handler_test.gleam

and adds seven routes to the router: GET /posts, GET /posts/new, POST /posts, GET /posts/:id, GET /posts/:id/edit, PUT /posts/:id, DELETE /posts/:id.

The index page is paginated, newest first: /posts?page=2 shows the second page of 20 (the per_page constant in the handler), with Previous and Next links and “Page 2 of N”. A missing or invalid page number means page 1.

--api writes a JSON handler, a params type, the domain type, the repo, the migration and tests, with no views or forms. It adds five routes under /api/: GET and POST /api/posts, and GET, PUT, DELETE /api/posts/:id. All five handlers are complete. create and update decode the JSON body, validate it with the same rules as the HTML form, and answer:

CaseStatus
created201, the record, and a Location header
updated200, the record
validation failed422, {"errors": {"title": "Title is required"}}
wrong field types400, with details of what was expected
unknown id404, {"error": "not found"}
deleted204

The index takes ?page= and ?per_page= (1 to 100) and wraps the records in an envelope:

{"data": [...], "page": 2, "per_page": 50, "total": 57, "total_pages": 2}

--belongs-to <parent> relates the resource to an existing one. For comments ... --belongs-to posts:

  • the migration adds post_id INTEGER NOT NULL REFERENCES posts(id) ON DELETE CASCADE and an index, so deleting a post deletes its comments
  • the form gets a select of posts, and /comments/new?post_id=3 preselects one; a post that doesn’t exist is a 422
  • the repo gets list_for_post(db, post_id), and a comment_list component shows a post’s comments on its page

Routes stay flat (/comments/:id). The parent resource must exist first, or the command stops and writes nothing.

Field types

TypeGleamHTML inputPostgreSQLSQLite
stringStringtextTEXTTEXT
textStringtextareaTEXTTEXT
intIntnumberINTEGERINTEGER
floatFloatnumberDOUBLE PRECISIONREAL
boolBoolcheckboxBOOLEANINTEGER
dateStringtextDATETEXT
datetimeStringtextTIMESTAMPTZTEXT
optional(T)Option(T)as Tnullable columnnullable column

string and text fields get a validate.required check in the form decoder. Number fields must parse, or the form answers 422.

Wrap a type in optional(...) for a field that may be empty, and quote it for the shell: 'price:optional(float)'. A blank input is stored as NULL and shown as “—”; in the JSON API it is null. An optional(bool) is a select with a blank, Yes and No, since a checkbox can’t say “not set”.

gen page

refrakt gen page about

Writes web/about_handler.gleam with an index handler and a test, and adds GET /about.

gen auth

refrakt gen auth

Writes the User domain type, password hashing in domain/auth.gleam, data/user_repo.gleam, a users migration, web/auth_handler.gleam, web/auth_views.gleam, web/forms/auth_form.gleam, web/middleware/auth.gleam and tests. Adds five routes: GET and POST /login, GET and POST /register, POST /logout. Like gen resource, it needs a project with a database.

Sessions live in web/session.gleam: a signed, expiring token in an HttpOnly, SameSite=Lax cookie that lasts seven days, marked Secure in production. Logging in with an unknown email takes as long as a wrong password, so response times don’t reveal which accounts exist. Protect a handler with the generated middleware:

pub fn create(req: Request, ctx: Context) -> Response {
  use _user <- auth.require_auth(req, ctx)
  // ...
}

Passwords are hashed with Argon2id (random salt per hash, constant-time verify) through the argus package, which the command adds to gleam.toml. Building argus needs a C compiler.

gen island

refrakt gen island counter

Writes web/islands/counter.gleam, a Lustre client-side app with init, update and view, and web/islands/counter_embed.gleam, whose render() and script_tag() put the island into a server-rendered view. Build the JavaScript with refrakt build.

gen live

refrakt gen live dashboard

Writes a Lustre server component in web/live/dashboard.gleam, its WebSocket module web/live/dashboard_socket.gleam, and web/dashboard_live_handler.gleam, the page that connects to it. Adds GET /dashboard. The component runs on the BEAM and sends DOM patches to the browser over the socket.

gen migration

refrakt gen migration add_email_to_posts

Writes an empty, numbered SQL file such as data/migrations/003_add_email_to_posts.sql. The number is the next one in the directory.

gen deploy

refrakt gen deploy
refrakt gen deploy --fly

Writes a two-stage Dockerfile (the Gleam image builds an Erlang shipment; a slim Erlang image runs it as a non-root user with APP_ENV=prod), a .dockerignore, a bin/migrate script that runs your migrations inside the image, and a GET /healthz route if the app has no health route yet. With --fly it also writes fly.toml.

  • SQLite: the database lives on a volume at /data, and the container applies pending migrations when it starts.
  • PostgreSQL: set DATABASE_URL and run bin/migrate before a release; on Fly it is the release_command.

Pass SECRET_KEY_BASE at runtime; the app refuses to start without it. Existing files are never overwritten. CI builds and runs this image for SQLite and PostgreSQL on every change.

diff

refrakt diff
refrakt diff src/blog/router.gleam
refrakt diff --stat

Generates what the installed refrakt_cli would write for your app into a temporary folder and shows a unified diff against your files, so after upgrading you can see which template improvements you don’t have yet. It replays the generators recorded in .refrakt/generated.toml (apps from before 0.7 are inferred from their files), never changes your app, and exits with 1 when generated files differ, so it also works in CI. The upgrade path is: bump the dependencies, run refrakt diff, and copy over what you want.

routes

refrakt routes

Reads router.gleam and prints method, path and handler:

GET     /posts              post_handler.index
GET     /posts/new          post_handler.new
POST    /posts              post_handler.create
GET     /posts/:id          post_handler.show

migrate

refrakt migrate

The first time, writes src/<app>/migrate.gleam, a module that connects to your database and calls refrakt/migrate. Then runs it with gleam run -m <app>/migrate. Pending .sql files in data/migrations/ are applied in order and recorded in a _migrations table. A file may hold several statements, and each file runs in one transaction: if any statement fails, the whole migration is rolled back, not recorded, and the error names the file. There are no down migrations.

seed

refrakt seed

The first time, writes src/<app>/seed.gleam for you to fill with sample data. Then runs it with gleam run -m <app>/seed.

build

refrakt build

Compiles the island modules in web/islands/ with gleam build --target javascript and copies the output to priv/static/js/islands/.

assets

refrakt assets setup
refrakt assets build

setup writes tailwind.config.js and assets/css/app.css (it needs npx, so Node.js). build runs the Tailwind CLI and writes a minified priv/static/css/app.css. Without them, the plain priv/static/css/app.css from refrakt new is used as is.

dev

refrakt dev

Sets APP_ENV=dev, runs the app, and watches src/ and priv/. On a change it rebuilds first: if the build fails, it prints the compiler error and the previous server keeps running. If it succeeds, it restarts the server and open pages reload by themselves. A change under priv/ reloads pages without a rebuild.

It uses fswatch when installed, inotifywait on Linux, and otherwise polls every 500ms; startup says which. Live reload runs on a separate port (REFRAKT_LIVE_RELOAD_PORT, default 35729) served by refrakt dev itself, and the script in the layout renders only in development, so production pages are unchanged.

help and version

refrakt help        # also --help, -h
refrakt version     # also --version, -v