Installation
There are two ways in. create-basalt scaffolds a production-shaped app in one command and only writes the features you pick — nothing dead ships. Or you add individual @basaltkit/* packages to an app you already have: every package is ESM with types, follows the same plugin contract, and works on its own. This page covers both, the basalt CLI that generates code once you're inside a project, and how to update an app or add a feature later.
Requirements
| Requirement | Version | Why |
|---|---|---|
| Node.js | 22 or newer (engines: >=22) | The framework targets modern Node; CI runs the whole monorepo on 22 and 24 |
| Package manager | pnpm (recommended), npm, yarn or bun | Only --ui is pnpm-only — it scaffolds a pnpm workspace |
| Node 22.5+ | for node:sqlite | The zero-dependency *-sqlite stores (auth-sqlite, teams-sqlite, …) use Node's built-in SQLite |
| Node 22.6+ | for basalt dev without tsx | The dev runner falls back to node --watch --experimental-strip-types when tsx isn't installed |
| PostgreSQL / Redis | production only | Prisma-backed stores need Postgres or MySQL; BullMQ queues and the Redis cache driver need Redis |
Nothing beyond Node is required to start — the scaffold boots on in-memory stores. See Persistence & durable stores for the swap.
Scaffold a new app
Your package manager's create command downloads and runs the scaffolder on the spot — nothing to install first:
pnpm create basalt my-saas
# or
npm create basalt my-saas
# or
yarn create basalt my-saas
# or
bun create basalt my-saas
# or, with the global launcher (npm i -g @basaltkit/cli)
basalt new my-saasRun it with no name in a terminal and you get the interactive wizard instead. Pass flags (or -y) to skip every question.
The interactive wizard
The wizard runs only when you gave no name, stdin is a TTY, and you didn't pass --yes — so CI and piped runs always take the flag-driven path. It asks, in order:
- Project name — defaults to
my-saas, validated as an installable npm package name (lowercase, no spaces, max 214 characters, optional@scope/). - Choose a starting point — one of the presets below.
- Select features — only for the
custompreset; multi-select with tenancy and auth pre-ticked. - Package manager — pnpm / npm / yarn / bun, defaulting to the one that invoked the command.
- Install dependencies now? and Initialize a git repository? — both default to yes.
- A summary, then Create project? — answering no (or Ctrl+C) prints
Cancelled.and exits with code 130, writing nothing.
Presets
| Preset | Features |
|---|---|
| SaaS starter | tenancy + auth + billing + database + CLI |
| API only | auth + MCP — no tenancy, no UI |
| Full stack | everything, including the database and the web UI |
| Minimal | none — add them later |
| Custom | you pick from the feature list |
Scaffolder flags
| Flag | Default | What it does |
|---|---|---|
<name> (positional) | — | Project name and, unless --dir says otherwise, the target folder. update, add, doctor and info are reserved for the project commands |
--name=<name> | — | The name as a flag — how to create a project literally called update, add, doctor or info |
--dir=<path> | ./<name> | Destination folder |
--no-tenancy | tenancy on | Skip multi-tenancy (@basaltkit/tenancy, header + subdomain resolvers) |
--no-auth | auth on | Skip authentication (@basaltkit/auth, APP_SECRET, /auth/*, mfaRoutes()) |
--billing | off | Include subscriptions and plans (@basaltkit/subscriptions) |
--ui | off | Add a React + shadcn web/ frontend — see Web UI. Forces pnpm |
--no-cli | CLI on | Skip bin/basalt.ts, the basalt script, generators and prisma:sync (every app gets them by default) |
--mcp | off | Expose opted-in read-only routes as MCP tools at POST /mcp, plus a .mcp.json for AI dev tools — see MCP |
--prisma (--db) | off | Back the app with PostgreSQL through Prisma: prisma/schema.prisma, migrations, src/db.ts, the Prisma-backed stores and a boot-time check that the database is the migrated one — see PostgreSQL with --prisma |
--install / --no-install | on in a TTY, off in CI | Install dependencies at the end |
--git / --no-git | on in a TTY, off in CI | git init plus an initial commit |
--offline | off | Skip the npm registry lookup and use the dependency ranges bundled with this create-basalt release |
--pm=<manager> | auto-detected | Force pnpm | npm | yarn | bun |
-y, --yes | — | Accept all defaults, no prompts (also disables the wizard) |
-h, --help | — | Print usage and exit |
pnpm create basalt my-saas --billing --install --git # full stack, installed and committed
npm create basalt service-api --no-tenancy --no-auth # minimal API
pnpm create basalt agent-api --mcp -y # API + MCP tools, no prompts
pnpm create basalt my-saas --prisma --billing # PostgreSQL-backed from the first commitThe package manager is detected from npm_config_user_agent (the variable npm, pnpm, yarn and bun all set), falling back to npm. --install and --git are tri-state: an explicit flag always wins, and only when you pass neither does the environment decide — a TTY that isn't CI gets both, everything else gets neither, so automation never gets a surprise install.
New projects get the latest published version of every dependency: before writing files the scaffolder asks the registry (npm_config_registry, else registry.npmjs.org) for each package's latest and writes ^<latest>. @basaltkit/* always takes the latest release; third-party packages (TypeScript, Vitest, React, Vite, Tailwind, …) take it only on the major the templates are written for — a newer major keeps the bundled range and prints a Note:. When the registry can't be reached, the bundled ranges are used with a single Warning: line; the scaffold never fails because of it. --offline skips the lookup.
A third-party latest published inside pnpm's release-age window (minimumReleaseAge — pnpm 11 defaults it to one day) keeps the bundled range too: ^<latest> of a version published an hour ago can't be installed under that policy, while the bundled range lets pnpm pick the newest mature version itself. The age comes from one cheap HEAD <registry>/<name> per third-party package (its last-modified); when it can't be proven, the bundled range is kept and a Note: says so. The window follows pnpm_config_minimum_release_age / npm_config_minimum_release_age when set. @basaltkit/* is never checked — the generated pnpm-workspace.yaml excludes the scope from the policy.
--ui requires pnpm
The web/ frontend is a member of a pnpm workspace (pnpm-workspace.yaml), which npm, yarn and bun can't install or run. Ask for --ui with another manager and the scaffolder tells you it is switching to pnpm, then does.
What gets generated
Every project gets the same skeleton; the feature flags only change what's inside it:
| Path | Contents |
|---|---|
src/env.ts | defineEnv over PORT, HOST, LOG_LEVEL, NODE_ENV (+ APP_SECRET via secret({ minLength: 32 }) with auth), with { prefix: 'MY_SAAS' } — every variable is read as MY_SAAS_<NAME> first, falling back to the bare name (see --env-file never overrides exported variables) |
src/app.ts | buildApp() — config, logger, events, security headers + a global rate limit, then tenancy/auth/billing/MCP/CLI as selected. With tenancy + auth: teamsPlugin() + tenantMembershipPlugin() (authenticated requests for a tenant the user is not a member of get 403) and a dev-only seed adding registrants to the demo tenant |
src/routes.ts | GET / (a friendly index) and GET /health |
src/server.ts | Boots, resolves FASTIFY, listens, and shuts down on SIGINT/SIGTERM. pnpm start runs its compiled form (dist/src/server.js) on plain node with --env-file-if-exists=.env: the file fills in what is not exported, and sets no NODE_ENV, so production stays fail-closed |
src/dev.ts | The pnpm dev entry: loads .env when present (exported variables win), sets NODE_ENV=development unless already set, then loads server.ts |
tests/app.test.ts | A smoke test that boots the app and hits / and /health |
package.json | Scripts dev (tsx watch src/dev.ts), build (tsc -p tsconfig.build.json), start (node --env-file-if-exists=.env --enable-source-maps dist/src/server.js — build first; loads .env, and an unset NODE_ENV counts as production), engines.node >=22.9.0, start:dev (tsx src/server.ts, the server from source without a build), test, typecheck, basalt (tsx bin/basalt.ts by default, create-basalt --project with --no-cli, so pnpm basalt update works in every app) and, with --ui, dev:web. create-basalt is a devDependency. @basaltkit/* ranges are floored at each package's current version (^<major>.<minor>.<patch>) |
.basalt/project.json | The scaffold manifest: create-basalt version, options and a hash of every generated file — commit it; add and update use it to tell untouched template files from edited ones |
.env | Local development values — a copy of .env.example plus, with auth, a generated APP_SECRET. Git-ignored, mode 0600, never in the manifest; pnpm dev, pnpm basalt and pnpm start load it; it sets no NODE_ENV |
tsconfig.build.json, Dockerfile | The production path: pnpm build compiles src/ to dist/ (rootDir ., so src/server.ts → dist/src/server.js); the multi-stage Dockerfile — the same file basalt publish dockerfile writes — builds the app and runs it on plain node as the node user |
.env.example, .gitignore, .dockerignore, README.md, tsconfig.json, pnpm-workspace.yaml | Project scaffolding (.dockerignore keeps .env and keys out of image layers; .env.example uses the app-prefixed names and, with the README, explains the --env-file precedence pitfall; pnpm-workspace.yaml excludes @basaltkit/* and create-basalt from minimumReleaseAge and documents the pnpm 11 settings) |
prisma/schema.prisma, prisma.config.ts, src/db.ts, prisma/seed.ts | With --prisma: the schema (the models of every enabled Basalt domain plus your own), the Prisma 7 config carrying the connection URL, the client(s) the app uses, and the demo tenant seed |
bin/basalt.ts | By default (not with --no-cli): the CLI entrypoint wiring the generators and prisma:sync. It forwards update, add, doctor and info to create-basalt and runs upgrade (the codemods) and the make:* generators before importing the app, so they work while the app is broken mid-upgrade — and a generator needs no database, running or migrated; then it loads .env (exported variables win) and turns an invalid environment, an unreachable database or an unmigrated one into a readable fix instead of a stack trace |
.mcp.json | With --mcp: registers the dev-only basalt-ai-mcp bridge for MCP clients |
web/… | With --ui: the React + shadcn frontend, a pnpm workspace member |
Then the usual next steps:
cd my-saas
pnpm install
pnpm dev # http://localhost:3000 (health check at /health)
pnpm testFor a guided end-to-end run, see Getting Started.
PostgreSQL with --prisma
Without the flag the scaffold has no database at all. It boots on in-memory sources (MemoryUserSource, MemoryTenantSource, the default team and subscription stores): perfect for a first run, CI and tests, and gone on the next restart. Swapping one store at a time is described in Persistence & durable stores.
--prisma (spelled --db if you prefer) generates the database-backed shape instead:
| File | What it is |
|---|---|
prisma/schema.prisma | The reference models of every @basaltkit/*-prisma package the project uses — exactly what basalt prisma:sync merges — plus your own Project model |
prisma.config.ts | Prisma 7 keeps the connection URL here, not in the schema. It reads MY_SAAS_DATABASE_URL first and the bare DATABASE_URL only as a fallback — the same precedence as src/env.ts, so the CLI and the app can never mean two different databases |
src/db.ts | prisma (unscoped — the framework stores use it) and, with tenancy, db = prisma.$extends(tenancyExtension()), the client every request gets |
src/app.ts | prismaPlugin({ client: db, assertMigrated: true }) plus prismaTenantSource, prismaAuthStores, prismaTeamsStores and prismaSubscriptionsStores in place of the memory ones |
prisma/seed.ts | The demo tenant the header and subdomain resolvers expect |
MY_SAAS_DATABASE_URL becomes a required variable (src/env.ts), and .env.example ships it uncommented. The package scripts are db:migrate (prisma migrate dev), db:deploy (prisma migrate deploy), db:generate and db:seed (prisma db seed); postinstall runs prisma generate so pnpm typecheck has the client types right after install. The client is generated into generated/prisma — outside src/, so pnpm build never has to copy it — and src/db.ts imports it as #db/client.js through the package.json imports alias ("#db/*": "./generated/prisma/*"), which resolves the same from src/ (tsx, vitest) and from dist/src/ (node). @prisma/client-runtime-utils is a direct dependency because the generated runtime requires it by name, and pnpm-workspace.yaml approves the prisma / @prisma/engines build scripts (pnpm 11 fails an install on an unapproved one). See Prisma with pnpm.
pnpm create basalt my-saas --prisma
cd my-saas && pnpm install
# .env points MY_SAAS_DATABASE_URL at postgres://…@localhost:5432/my_saas — start PostgreSQL or edit it
pnpm db:migrate # creates the tables
pnpm db:seed # the demo tenant
pnpm devAfter a change to prisma/schema.prisma, pnpm db:migrate --name <change> writes the migration and applies it to the development database (Prisma creates and drops a temporary shadow database for that, so the database user needs CREATEDB); without --name it asks for one, so in a script always pass it. Then run pnpm db:generate: Prisma 7's migrate dev no longer regenerates the client (nor seeds). Production applies the committed migrations with pnpm db:deploy.
Migrations, never db push
The generated src/app.ts boots with assertMigrated: true, which refuses to start unless the database it reached has the _prisma_migrations table — written by prisma migrate dev / migrate deploy and not by prisma db push. That check is what turns a wrong DATABASE_URL (a shell that exported another project's, a typo in the database name) into a boot error naming the database and host, instead of a 500 on the first request that touches a missing table.
The generated tests/app.test.ts skips itself when no database is configured, so pnpm test stays green on a machine without PostgreSQL.
--env-file never overrides exported variables
src/env.ts validates process.env and nothing else. In development the scaffold loads .env for you: src/dev.ts (pnpm dev) and bin/basalt.ts (pnpm basalt, scaffolded by default) call process.loadEnvFile() on the project's .env when it exists, before the app is imported, and set NODE_ENV=development. pnpm start loads it too — node --env-file-if-exists=.env (Node 22.9+) on the compiled src/server.ts — but sets no NODE_ENV: unset, it counts as production, so the secrets are required. What the platform exports (Docker, systemd, @basaltkit/deploy) always wins. A new app already has a .env: the values of .env.example and, with auth, a generated APP_SECRET — git-ignored, so the secret never reaches the repository.
Loading .env works exactly like node --env-file=.env (or tsx --env-file=.env): Node only fills variables that are not already set — a value exported in your shell always wins. With generic names this bites quietly — in a terminal where another project exported DATABASE_URL or PORT, the app boots against that database or port and fails only on the first request that touches it.
The fix the scaffold applies: an app-specific prefix. src/env.ts passes prefix to defineEnv, derived from the project name (my-saas → MY_SAAS), and .env.example uses the prefixed names:
// src/env.ts — generated
export const env = defineEnv(
{
PORT: z.coerce.number().default(3000),
HOST: z.string().default('0.0.0.0'),
LOG_LEVEL: z.enum(LOG_LEVELS).default('info'),
NODE_ENV: z.enum(['development', 'production', 'test']).default('production'),
APP_SECRET: secret({ minLength: 32, devDefault: 'dev-only-insecure-secret-please-change-me' }),
},
{ prefix: 'MY_SAAS' },
)# .env.example — generated
MY_SAAS_PORT=3000
MY_SAAS_HOST=0.0.0.0
MY_SAAS_LOG_LEVEL=info
# NODE_ENV is never prefixed, and never set here: dev and basalt set development,
# start (which also loads this file) stays production
# MY_SAAS_APP_SECRET= # with authEach variable is read as MY_SAAS_<NAME> first and falls back to the bare <NAME>, so a deployment that already exports the generic names keeps booting while a stray PORT in your shell no longer wins. The shape's keys are untouched — the app still reads env.PORT. To drop the fallback and require the prefixed names only, write prefix: { value: 'MY_SAAS', fallback: false }. When a variable is missing the report names what was looked for — MY_SAAS_DATABASE_URL (or DATABASE_URL): Required. Full rules: Configuration → App-specific prefixes.
When a variable is invalid or missing, pnpm basalt <command> prints the variables from the report, where they were read from (your environment, and .env when it exists) and the fix — cp .env.example .env, fill them in, and for DATABASE_URL start PostgreSQL — and exits 1 without a stack trace (BASALT_DEBUG=1 or --debug shows it). pnpm basalt doctor checks the same variables without booting the app. The database gets the same treatment: when PostgreSQL does not answer (ECONNREFUSED, Prisma P1001, or an assertMigrated that could not query it) or the database is not migrated (PRISMA_NOT_MIGRATED), the message says what failed, which database the app used — postgres://host:port/name and the variable it came from, never the user or password — and the fix: start PostgreSQL (docker compose up -d, or your local service), check MY_SAAS_DATABASE_URL, run pnpm db:migrate. A database that refuses the app's role (permission denied, SQLSTATE 42501) or needs a baseline (P3005) is named as such, with the GRANT or the prisma migrate resolve to run — see Database operations. Any other boot error keeps its stack trace.
Two habits that still help:
- When in doubt,
env | grep DATABASE_URLbeforepnpm dev, or start with a clean slate:env -u DATABASE_URL pnpm dev. - Once a database is wired, log its target at boot (host and database name, never the password) so a wrong one is visible in the first line of output.
pnpm 11: release age and verifyDepsBeforeRun
Two pnpm 11 behaviours shape the generated pnpm-workspace.yaml:
minimumReleaseAgeExcludeis first-match-wins by package name. Two entries for the same package ('@types/node@22.20.4'and'@types/node@26.6.2') do not add up — only the first applies. Exclude several versions of one package with a single union entry, as the generated comment shows:yamlminimumReleaseAgeExclude: - '@basaltkit/*' - '@types/node@22.20.4 || 26.6.2'verifyDepsBeforeRundefaults toinstall. Before everypnpm <script>andpnpm exec, pnpm checks thatnode_modulesmatches the manifests of every workspace project (includingweb/with--ui); when it doesn't, it runspnpm installfirst — network and supply-chain checks included. Sopnpm basalt make:resource …is effectivelypnpm install && basalt …right after any dependency change. Two conscious ways out:bashnode_modules/.bin/tsx bin/basalt.ts make:resource Project # no pnpm, no pre-run checkor uncomment
verifyDepsBeforeRun: warninpnpm-workspace.yaml— pnpm then only warns, and runningpnpm installafter dependency changes is on you. The scaffold keeps pnpm's default and thebasaltscript astsx bin/basalt.ts.
Updating an app
Every app — scaffolded with or without the CLI (--no-cli), by any create-basalt release — can move to the latest dependency versions in one command:
pnpm basalt update --dry # the plan, nothing written
pnpm basalt update # asks, writes, installs, runs the codemods
npx create-basalt@latest update # the same, in an app without the basalt scriptIt applies the same policy as a new scaffold (it is the same registry code):
@basaltkit/*andcreate-basaltgo tolatest, across majors. Each framework major prints a link to the package's CHANGELOG and to the upgrade notes — read them before applying.- Third-party packages go to the newest release on the app's current major; a newer major is listed as
kept … pass --majorand only taken with--major. - A version younger than the release-age window (pnpm
minimumReleaseAge, read from the project'spnpm-workspace.yamlwhen set) is left for later, so the install can't refuse it. - When a framework release declares a peer range the app would not meet (say
zod ^5while zod is held on 4), the plan warns before anything is written. - When a framework release requires an
@basaltkit/*peer the app'spackage.jsondoes not list (@basaltkit/testing3 takes@basaltkit/mailer), the plan adds it at its latest version — independencieswhen a runtime dependency needs it, elsedevDependencies— or warns when it cannot. Optional peers are never added.
4 update(s):
package in current target kind
@basaltkit/core . ^1.5.0 → ^2.0.0 MAJOR
zod . ^4.6.5 → ^4.9.0 minor
react web/ ^19.3.0 → ^19.9.0 minor
zod web/ ^4.6.5 → ^4.9.0 minor
kept typescript ^7.0.2: 8.0.0 is a new major — pass --major to take it
Framework majors — read before applying:
@basaltkit/core 1.5.0 → 2.0.0: https://github.com/basaltkit/basalt/blob/main/packages/core/CHANGELOG.mdBoth package.json and web/package.json are edited in place — only the version strings change; key order, indentation and range style (^, ~, exact) stay, and ranges it does not manage (workspace:, tags, git, >=) are left alone. The lockfile is never touched by hand: the detected package manager (packageManager field, then the lockfile) installs, the installed @basaltkit/cli upgrade codemods run without booting the app, and the command ends with pnpm typecheck && pnpm test. If the install fails, the edits stay and the command prints how to revert them with git.
| Flag | What it does |
|---|---|
--dry | Prints the plan; writes nothing |
-y, --yes | Applies without asking — required when stdin is not a terminal (CI) |
--major | Lets third-party packages cross a major too |
--only=@basaltkit | Only the framework packages (and create-basalt) |
--no-install | Writes package.json, skips the install and the codemods |
--no-tooling | Leaves bin/basalt.ts, src/dev.ts, .env.example and the create-basalt devDependency alone |
--pm=<manager>, --cwd=<dir>, --no-color | Override the package manager / target directory; plain output (also NO_COLOR) |
--offline is refused — update needs the registry. Project tooling rides along: an app without the create-basalt devDependency gets it (plus a basalt script); a bin/basalt.ts generated by an earlier release is taught the project commands, .env loading, a pre-boot upgrade and make:*, and the readable env error; a src/dev.ts from create-basalt 1.9/1.10 learns to load .env; and the .env.example header stops saying "nothing loads this file". Each file is patched only when it is byte-for-byte a known template or the manifest records it untouched. A customised one is left alone and the exact snippet to paste is printed.
An app from before the production path is offered what it lacks, as part of the same plan: tsconfig.build.json, a build script, the Dockerfile (pnpm apps) and .dockerignore, and — with Prisma — @prisma/client-runtime-utils as a direct dependency. Files that exist are never touched, and an existing start script is never rewritten: moving it from tsx src/server.ts to the compiled server changes how the app is deployed, so the two script lines to paste are printed instead. A Prisma client still generated under src/generated gets the move instructions (schema output, the #db/* alias, the src/db.ts import, .gitignore) and no Dockerfile until it is moved — tsc does not copy the generated .js files.
Adding features later
Didn't pick --ui, --cli or --mcp at creation time? Add it now — no need to recreate the project:
pnpm basalt add ui --dry # what would be created, merged and skipped
pnpm basalt add ui # web/ exactly as --ui scaffolds it
pnpm basalt add cli # bin/basalt.ts + @basaltkit/cli, generator and prisma:sync
pnpm basalt add mcp # @basaltkit/mcp at POST /mcp + the dev-only ai-mcp bridge + .mcp.jsonadd adapts the templates to the project as it is now (its name, auth and tenancy from the dependencies) and plans every change before applying any:
- Existing files are never overwritten — they are skipped with a notice;
--forceoverwrites generated files. - Shared files are merged:
package.json(new dependencies in sorted position, scripts such asdev:web; an existing entry is never changed),pnpm-workspace.yaml(webadded topackages:),.gitignoreandREADME.md. - Your code (
src/app.ts,src/routes.ts) is regenerated only when.basalt/project.jsonproves it untouched, patched where the template's anchors are still unambiguous —fastifyPlugin,expressPluginandhonoPluginalike — and otherwise left alone, with the exact manual steps printed. add uineeds pnpm (web/is a workspace member) and changes no API code: the Vite dev server proxies/api, so there is no CORS to configure.- Dependencies are installed afterwards (
--no-installto skip);--offlineuses the ranges bundled with create-basalt instead of the registry.
A project created without --ui and then given add ui has the same files as one created with --ui — the create-basalt test suite asserts exactly that, and that both typecheck.
Checking a project: doctor and info
pnpm basalt doctor # read-only; exit 1 on errors, 0 on warnings only
pnpm basalt info # versions summary to paste into bug reportsdoctor checks Node against engines and Basalt's >=22.5.0; the package manager and lockfiles; installed versus declared versions, duplicated @basaltkit/* versions and unmet peer ranges; framework packages behind latest (--offline skips it); the auth secret (<PREFIX>_APP_SECRET, from the environment or .env, against the minLength in src/env.ts and the placeholder rules of secret()); every variable src/env.ts requires (declared without a default — DATABASE_URL with --prisma) that is set neither in the environment nor in .env, as an error with the fix; a missing .env next to a .env.example, as a warning; that the Prisma client is generated and migrations exist (whether they are applied needs a database — prisma migrate status); .mcp.json when @basaltkit/ai-mcp is installed; dev tooling declared as a runtime dependency; an outdated bin/basalt.ts or src/dev.ts; and, statically, the production path — a start that runs tsx while tsx is only a devDependency, no build script, a dist/src/server.js older than src/, a Prisma client generated under src/, and a missing @prisma/client-runtime-utils. doctor never builds or starts the app.
Choose an HTTP adapter
Routes are written once and run on any of three adapters — pick the one for your stack (see HTTP Adapters):
pnpm add @basaltkit/core @basaltkit/http @basaltkit/fastify fastify # Fastify
pnpm add @basaltkit/core @basaltkit/http @basaltkit/express express # Express
pnpm add @basaltkit/core @basaltkit/http @basaltkit/hono hono @hono/node-server # HonoThe scaffolder always writes Fastify; swapping later is a one-line change, because route() and the guards live in the neutral @basaltkit/http contract.
Add to an existing app
Basalt packages adopt incrementally. To add multi-tenancy to an app you already have, install just those pieces — it works the same on any adapter:
pnpm add @basaltkit/core @basaltkit/tenancyThe full catalogue is in the package reference, and Migrating from Express walks through adopting the framework a capability at a time.
Scaffold inside a project
With the CLI (the default, or after adding @basaltkit/cli + @basaltkit/generator yourself), pnpm basalt generates whole resource verticals:
pnpm basalt make:resource Project # in-memory — or Prisma-backed in a --prisma app
pnpm basalt make:resource Project --prisma # Prisma-backed + a schema.prisma model
pnpm basalt make:resource Project --sqlite # SQLite-backed + its table in src/db.ts
pnpm basalt make:resource Project --prisma --soft-delete # + a deletedAt column & restore
pnpm basalt make:service Project # just one artifactmake:resource emits a schema, repository, service, DI plugin, typed CRUD routes and a test into src/modules/<name>/, then wires the plugin and routes into src/app.ts for you. Models get createdAt + updatedAt automatically. --soft-delete adds a deletedAt column (so delete marks the row instead of removing it, and list/find skip soft-deleted rows), a restore() method, and a POST /projects/:id/restore route.
The generated code is secure by default. Every route requires an authenticated user (meta: { auth: true }), so the app refuses to boot until an auth plugin enforces it and anonymous callers get 401. When the project depends on @basaltkit/tenancy, the resource is tenant-owned: the repository scopes every read and write with requireTenantId() (no tenant → TENANT_REQUIRED, 400), and the Prisma model gets an indexed tenantId column (with --tenant=schema or --tenant=database, no column: the schema or database is the isolation). The generated test signs in, checks that anonymous calls get 401 and, for tenant-owned data, that one tenant cannot see another's rows. A short security note after generation says which of these applies. Row-level authorization (who may read or write which rows) is still up to you.
In an app with prisma/schema.prisma (scaffolded with --prisma) the resource is Prisma-backed without the flag: the repository is typed against the project's generated client (#db/client.js), the model is appended to prisma/schema.prisma — never twice — and the generator prints the db:migrate / db:generate line that creates the table; the test boots prismaPlugin with the client from src/db.ts and skips when no database URL is set. --no-prisma keeps the in-memory repository. The whole flow, and the SQLite alternative, is in Database.
| Generator flag | Applies to | What it does |
|---|---|---|
--prisma / --no-prisma | make:resource, make:repository, make:test | Prisma-backed repository plus its model — appended to prisma/schema.prisma when the project has one, otherwise written to src/modules/<name>/<name>.prisma to paste (also for --tenant=schema|database: it goes to the tenant schema). Default: on when prisma/schema.prisma exists |
--sqlite / --no-sqlite | make:resource, make:repository, make:plugin | SQLite-backed repository over node:sqlite, opened with database() from src/db.ts. make:resource appends its CREATE TABLE to the MIGRATIONS there, and creates that module (plus DATABASE_PATH in src/env.ts) when the project has none. Tenant isolation by tenant_id column only. Default: on when src/db.ts is that module. See SQLite |
--soft-delete | make:resource and the artifacts it builds | deletedAt column, restore(), restore route, filtered reads |
--dir=<path> | all make:* | Target root (default: the current directory) |
--force | all make:* | Overwrite existing files instead of refusing |
--no-register | make:resource | Skip the automatic wiring into src/app.ts |
--public | make:resource, make:routes, make:test | Routes without meta.auth, open to anonymous callers (alias --no-auth). Use only for a deliberately public resource |
--tenant / --no-tenant | make:resource, make:repository, make:test | Force tenant scoping on or off (default: on when package.json depends on @basaltkit/tenancy) |
--tenant=column|schema|database | make:resource, make:repository, make:test | How tenants are isolated: a tenantId column (default), or a schema/database per tenant — no tenantId column, still requireTenantId() on every access. Never guessed; see Generating tenant resources |
--crud / --no-crud | make:service | Force the CRUD service or the minimal one (default: CRUD when the sibling repository and schema are already in the target directory) |
Individual artifacts are available as make:schema, make:repository, make:service, make:plugin, make:routes and make:test.
Services that are not CRUD
A CRUD service delegates to a sibling repository and imports the sibling schema. Generated on its own, where those files do not exist, it would not compile (TS2307: Cannot find module './invoice.repository.js') — so make:service looks at the target directory first:
<name>.repository.tsand<name>.schema.tsalready there (aftermake:resource, or written by you) → the CRUD service, as before;- either one missing → a minimal service: the class, its
createTokeninjection token and a constructor with no dependencies, importing nothing but@basaltkit/core. It compiles as written and carries a TODO pointing atmake:resourcefor the CRUD vertical.
That is the shape for orchestration, domain rules, transactions, schedulers — the services a repository has nothing to do with.
pnpm basalt make:service Billing # minimal: no repository next to it
pnpm basalt make:service Invoice --crud # force the CRUD shape
pnpm basalt make:service Invoice --no-crud # force the minimal shapemake:resource is unaffected: the vertical always gets the CRUD service, because it generates the repository and the schema in the same batch.
One artifact at a time: the sibling warning
The service is the only artifact with a shape that stands on its own. The others are members of a vertical and import one another — the plugin needs the repository and the service, the routes need the service and the schema, the test needs the plugin and the routes, the repository needs the schema. Generating one of them alone still writes the file (the sibling may be the next thing you write by hand), but the generator now names what it refers to and cannot find:
Generated 1 file(s):
src/modules/invoice/invoice.plugin.ts
Warning: src/modules/invoice/invoice.plugin.ts imports 2 file(s) that do not exist yet:
src/modules/invoice/invoice.repository.ts
src/modules/invoice/invoice.service.ts
Generate the whole vertical with `basalt make:resource Invoice`, or write them yourself — until then this file does not compile.make:schema never warns (it imports nothing of the module) and make:resource never warns (it writes every one of them). Programmatically the same list is missingSiblings(kind, name, options, { baseDir }), and expectedSiblings(kind, names(name)) is the static per-kind table.
What is true of the whole project — rather than of one invocation — is configured where the commands are registered, including which Prisma client the generated repositories are typed against:
commandsPlugin(
generatorCommands({
prisma: true,
prismaClient: { import: '../../tenant-db.js', type: 'TenantDb' },
}),
)An application with a second client (schema-per-tenant, a read replica) needs that: against the default PrismaClient the generated repository either fails to compile or, worse, compiles against the wrong models. Flags still win in both directions — --no-prisma overrides prisma: true.
Built-in CLI commands
runCli always offers these, alongside anything a plugin registers:
| Command | What it does |
|---|---|
list (or no command) | Print every available command |
routes | The registered HTTP routes with the guards each declares (auth, can, rateLimit, tenant, …), read from the http:routes metadata bucket. --json for machine output; --unguarded --require=auth,can [--allow=<glob,…>] exits 1 on routes missing those guards — route meta only, see Route security review |
schedule:list | Scheduled tasks with their cron expressions and timezones |
dev | Run the app with watch/restart: src/dev.ts when present (what pnpm dev runs), else src/main.ts, src/server.ts, …. It starts even while the app cannot boot (a variable missing, the database down) and restarts the server on every save. The route table is basalt routes; --routes prints it here too, from a boot of the app that is shut down before the server starts (a session holds one app). --entry=<file>, --worker (-w) to start a queue worker alongside, --queue=<name>, --routes |
upgrade | Apply framework upgrade codemods. --dry to preview, --only=<id>, --dir=<path>. It does not touch the dependencies: that is basalt update |
update, add, doctor, info | Not runCli commands: bin/basalt.ts forwards them to create-basalt before booting the app — see Updating an app |
db:status | Not a runCli command either: bin/basalt.ts runs dbStatusCommand() from @basaltkit/prisma without booting the app (which refuses to start on an unmigrated database). Read-only; exits 1 when a migration is pending, failed or drifted. Pass shards or per-tenant databases to it in bin/basalt.ts — see db:status |
publish | Copy a stub group into the app (dockerfile — the multi-stage build + plain-node image the scaffold ships, with a .dockerignore that keeps .env and keys out of the image —, ci — install, typecheck, build, test —, editorconfig). Run with no id to list; --force to overwrite |
Registering queuePlugin adds queue:work, queue:stats, queue:retry and queue:jobs — see Queues & jobs.
basalt without pnpm: the global launcher
basalt is a script in the app's package.json, so the shell only finds it through the package manager: pnpm basalt <command>. Install the launcher once and type basalt <command> instead:
npm i -g @basaltkit/cli
cd my-saas/src/modules # anywhere inside the app
basalt ai:make "an invoices module per tenant"
basalt routesThe launcher runs no command itself. It finds the nearest package.json with a basalt script, from the current directory up, and runs that script with the app's own package manager: pnpm basalt …, npm run basalt -- …, yarn basalt … or bun run basalt …. The package manager comes from packageManager, else the lockfile; inside a workspace, the workspace's.
What runs is always the app's code, at the versions its lockfile pins. The global install only has to be there; its version never matters. The arguments and the exit code pass through unchanged, so pnpm basalt … and basalt … are the same command, in scripts and CI too. Outside an app, basalt says so and exits 1; basalt --version there prints the launcher's version.
One command is the launcher's own, inside an app too: basalt new <name> [flags] scaffolds an app. It runs create-basalt@latest with the same name and flags (pnpm dlx, else npx; --pm= picks the manager), so you always get the latest scaffolder, whatever version the launcher is.
Failure modes & troubleshooting
| Error | Exit code | When |
|---|---|---|
TargetNotEmptyError — "Target directory … already exists and is not empty" | 1 | The destination has files. Pick another name or --dir= |
Cancelled. (WizardCancelledError) | 130 | Ctrl+C, or answering no to "Create project?". Nothing is written |
FileExistsError — "Refusing to overwrite existing files" | 1 | A make:* target already exists. Re-run with --force |
Unknown command "…". Run "basalt list" to see what is available. | 1 | Typo (a close name is suggested: Did you mean …?), or the plugin that registers the command isn't in buildApp. basalt list <group> narrows the list (basalt list tenant) |
No entry file found. Looked for src/dev.ts, src/main.ts, … | 1 | basalt dev in a project with a different entrypoint — pass --entry=<file> |
Unknown command "update" (+ a create-basalt hint) | 1 | bin/basalt.ts predates the project commands — run npx create-basalt@latest update once; it patches an unmodified file |
No package.json in … / … does not look like a Basalt app | 1 | A project command outside an app — cd into it or pass --cwd=<dir>. To create a project called update: npm create basalt -- --name=update |
Not a terminal — nothing written. Re-run with --yes | 1 | update/add without --yes in CI or a pipe |
update resolves the latest versions from the npm registry, so it cannot run with --offline | 1 | Drop --offline; a mirror works through npm_config_registry |
The web/ frontend is a pnpm workspace member … this project uses npm | 1 | add ui on a non-pnpm project — switch it to pnpm first |
- The scaffolder ignored my flags — some package managers keep everything after the package name for themselves. Put the flags after
--:npm create basalt my-saas -- --billing --ui. pnpm and bun forward them directly. - "Skipping dependency install (CI/non-interactive)" — expected: without an explicit flag, only an interactive non-CI terminal installs. Pass
--install(and--git) to force it. --uisilently became pnpm — it has to; theweb/package is a pnpm workspace member. Start the frontend withpnpm dev:web(=pnpm --filter <name>-web dev, port 5180) whilepnpm devserves the API on 3000.- "Could not auto-wire src/app.ts" —
make:resourceonly edits anapp.tsthat still usesfastifyPlugin({ routes: [...] }). Add the generated plugin topluginsand the routes to the adapter yourself; the generated files are otherwise complete. The app cannot start — invalid environment variables(or a rawEnvValidationError … expected string, received undefinedfrom an older app) — a required variable is set neither in your shell nor in.env. Apps from create-basalt ≤ 1.10 did not load.envinpnpm dev/pnpm basaltat all: runnpx create-basalt@latest updateonce (it patches an unmodifiedbin/basalt.tsandsrc/dev.ts),cp .env.example .envif there is none, fill in what the message lists, and check withpnpm basalt doctor.The app cannot start — the database did not answer— PostgreSQL is not running, orMY_SAAS_DATABASE_URLpoints at the wrong host/port (the message shows which, without credentials). Start it (docker compose up -d, or your local service) or fix the URL in.env; on a fresh database runpnpm db:migrate.… the database is not migrated— runpnpm db:migrate(pnpm db:deployin production), or check the URL if it is not the database you meant.- The app connects to the wrong database / port — a variable exported in your shell beats
.env(as it beats--env-file). Set the app-prefixed names (MY_SAAS_PORT) the scaffold declares, not the generic ones. See--env-filenever overrides exported variables. pnpm basalt …starts with apnpm install(or fails offline) — pnpm 11'sverifyDepsBeforeRun. See pnpm 11: release age andverifyDepsBeforeRun.ERR_UNKNOWN_BUILTIN_MODULE: node:sqlite, or--experimental-strip-typesis rejected — you're on a Node older than 22.5 / 22.6. Upgrade Node, or installtsx(which the scaffold already does).
Where to next
- Getting Started — the guided run through the generated app.
- Configuration —
src/env.ts, secrets and the settings repository. - Core Concepts — plugins, the container and request context.
- Testing —
createTestAppand the fakes shipped indevDependencies. - Production — durable stores, Docker and the deploy checklist.