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_bootstrapCommands 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 auth | Register, 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 deploy | Dockerfile, bin/migrate, and fly.toml with --fly |
routes | Print the route table |
diff | Compare the app with what the current CLI generates |
migrate | Run pending migrations |
seed | Run database seeds |
build | Compile islands to JavaScript |
assets setup, assets build | Tailwind CSS setup and build |
dev | Dev 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 postgres | Add Pog and a data/repo.gleam that connects to PostgreSQL |
--db sqlite | Add Sqlight and a data/repo.gleam for SQLite |
| none | No 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 --apiThe 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,deleteweb/<singular>_views.gleam:index_view,show_view,form_viewweb/forms/<singular>_form.gleam: the form and params types,empty,from_<singular>,from_form_data,decodedomain/<singular>.gleam: the domain typedata/<singular>_repo.gleam:list,get,create,update,deletein raw SQLdata/migrations/NNN_create_<name>.sqltest/<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:
| Case | Status |
|---|---|
| created | 201, the record, and a Location header |
| updated | 200, the record |
| validation failed | 422, {"errors": {"title": "Title is required"}} |
| wrong field types | 400, with details of what was expected |
| unknown id | 404, {"error": "not found"} |
| deleted | 204 |
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 CASCADEand an index, so deleting a post deletes its comments - the form gets a select of posts, and
/comments/new?post_id=3preselects one; a post that doesn’t exist is a 422 - the repo gets
list_for_post(db, post_id), and acomment_listcomponent 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
| Type | Gleam | HTML input | PostgreSQL | SQLite |
|---|---|---|---|---|
string | String | text | TEXT | TEXT |
text | String | textarea | TEXT | TEXT |
int | Int | number | INTEGER | INTEGER |
float | Float | number | DOUBLE PRECISION | REAL |
bool | Bool | checkbox | BOOLEAN | INTEGER |
date | String | text | DATE | TEXT |
datetime | String | text | TIMESTAMPTZ | TEXT |
optional(T) | Option(T) | as T | nullable column | nullable 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 aboutWrites web/about_handler.gleam with an index handler and a test, and adds GET /about.
gen auth
refrakt gen authWrites 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 counterWrites 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 dashboardWrites 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_postsWrites 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 --flyWrites 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_URLand runbin/migratebefore a release; on Fly it is therelease_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 --statGenerates 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 routesReads 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.showmigrate
refrakt migrateThe 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 seedThe 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 buildCompiles 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 buildsetup 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 devSets 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