Introduction
Docs Web Start here · 117 min to read this section

#Start here

#Introduction

Kreft is a small reactive framework with its own component language. You write a component in a .kreft file: declare your state, derived values and actions in plain words, then describe the page in a <view>. The framework also ships a full Node.js backend (routes, controllers, models, migrations, queues, mail) so one project can cover the whole stack.

Kreft was created by Mohamoud Hussen Abdi with Claude AI.

HTML
<!-- Counter.kreft -->
state count = 0
derive double = count * 2
action add() { count++ }

<view>
  <button @click={add}>{count} × 2 = {double}</button>
</view>

#What you get

PartWhat it gives you
The .kreft languagestate, derive, action, watch, props, events, slots, stores, a router with layouts and nested routes, forms with validation, animations.
The backendRoute, controllers, an Active Record Model, migrations, seeders, factories, jobs, mail, cache, file storage, policies, scheduling.
AuthenticationSign-in pages, password reset, email verification, two-factor codes, device sessions and API tokens, ready in every new project (leave them out with --no-auth).
Toolingkreft dev with hot reload that keeps state, DevTools, an error monitor, kreft build, TypeScript, Vite, and targets for every platform: Electron, Tauri, iOS/Android (Capacitor), HarmonyOS and PWA.
PlatformsThe web, desktop apps for macOS, Linux and Windows (Electron or Tauri), and phone apps for iOS, Android and HarmonyOS. TV apps are coming soon. See One codebase, every screen.
Security by defaultEscaped views, CSRF protection, hashed passwords, rate limits, hardened package installs. See Security overview.

#Where it runs

One project, many targets. The pages are the same .kreft files everywhere; only the shell around them changes.

TargetWhat it isBuild itDetails
WebThe normal website.kreft build—
PWAThe site as an installable app that works offline.kreft build --pwaMobile apps (iOS and Android)
Desktop — ElectronA desktop program for Windows, macOS and Linux (ships its own browser).kreft new app --electron, then kreft electron:buildDesktop apps with Electron
Desktop — TauriA desktop program with installers of a few MB (uses the system web view, needs Rust).kreft new app --tauri, then kreft tauri:buildDesktop apps with Tauri
Mobile — iOS and AndroidA real app for the App Store and Google Play (a Capacitor WebView).kreft new app --mobile, then kreft mobile:build --androidMobile apps (iOS and Android)
Mobile — HarmonyOSA small native ArkTS shell with a web view for Huawei phones and tablets.kreft new app --harmony, then kreft harmony:buildHarmonyOS apps
  • The backend never runs inside a desktop or phone app: it runs on your computer or a server, and the app reaches it with --api-url (or PUBLIC_API_URL in .env).
  • Combine flags for one project that targets several platforms, for example kreft new app --mobile --electron. --desktop is an alias for --electron.

#How the docs are organised

  1. Start here gets a project running.
  2. The Kreft language is everything in the browser.
  3. Backend is everything on the server.
  4. Tooling covers the command line, building and deploying, and Platforms covers desktop, phone and (soon) TV apps.
  5. Security and Reference are for checking details.

#Installation

#Requirements

You needWhy
Node.js 22.5 or newer (npm comes with it)Runs the kreft command, the dev server and the backend. 22.5 also gives you SQLite with nothing to install.
A terminalmacOS Terminal, Windows PowerShell, or any Linux shell.
A modern browserChrome, Edge, Firefox or Safari.
MySQL, PostgreSQL or RedisOnly if you choose them. SQLite needs nothing.

Check your Node version:

BASH
node --version      # v22.5.0 or higher

#Install the command

Always ask npm for the newest version with @latest. Pick one way.

1. Once, for every project (recommended). The kreft command then works in any folder (the package is called kreftjs):

BASH
npm install -g kreftjs@latest

2. Inside one project. The version is saved in the project's package.json, so everyone who clones the project, your server and your CI get the same one:

BASH
npm install -D kreftjs@latest
npx kreftjs dev

3. Without installing anything. npx downloads Kreft, runs it and forgets it. Good for trying it out:

BASH
npx kreftjs@latest new my-app

#Check that it works

BASH
kreft --version     # for example 0.0.48-beta
kreft about         # Kreft and Node.js versions, this project's settings and drivers
kreft list          # every command your version has

kreftjs is a longer name for the same command; both work.

#Set up your editor

BASH
kreft vscode

installs colors, snippets and Emmet for .kreft files in VS Code and the editors built on it (Antigravity, Cursor, Windsurf, VSCodium). Restart the editor afterwards.

Other editors have their own plugin, each with Emmet (ul>li*3 in <view>, m10 in <style>):

BASH
kreft editor sublime      # Sublime Text
kreft editor zed          # Zed
kreft editor jetbrains    # WebStorm, PhpStorm, IntelliJ IDEA, PyCharm, Android Studio ...
kreft editor vim          # Vim and Neovim

kreft editor alone lists them. Editor plugins has one part per editor: what you get, how to install it, and how to download the plugin as a file.

#Update

BASH
npm install -g kreftjs@latest      # the command (or: npm install -D kreftjs@latest inside a project)
cd my-app
kreft update --check       # what would change
kreft update --core        # refresh this app's kreftjs.js and type files (a backup is saved)

Every app has its own copy of the browser runtime, frontend/kreftjs.js. Updating the command does not touch it, so an existing app keeps its old version until you run kreft update --core inside it.

#With a bundler (ES module)

The package also ships the runtime as an ES module, kreftjs.mjs. Bundlers (Vite, esbuild, Rollup, webpack) and import in Node pick it by themselves; require('kreftjs') and <script src="kreftjs.js"> keep the classic file:

JS
import Kreftjs, { state, app, router } from 'kreftjs'   // named exports are the same as Kreftjs.state, Kreftjs.app…

It is the same runtime: it still sets window.Kreftjs, and when kreftjs.js was already loaded with a <script> tag it reuses that copy, so state is never split between two copies. The runtime is one file, so a bundler keeps all of it (about 47 kB gzipped); package.json marks it as having side effects (sideEffects) because it sets window.Kreftjs when it loads.

#Uninstall

BASH
npm rm -g kreftjs

#Working on Kreft itself

Run npm link inside the Kreft folder. The kreft command then runs that folder's code, and every edit shows at once. Undo it with npm unlink -g kreftjs.

#If something goes wrong

What you seeWhat to do
command not found: kreftjsnpm's global folder is not on your PATH. Run npm config get prefix, add its bin folder to PATH, and open a new terminal.
EACCES: permission denied while installingDo not use sudo. Install Node with nvm, or run npm config set prefix ~/.npm-global and add ~/.npm-global/bin to PATH.
SQLite needs Node.js 22.5 or newerUpdate Node.js. node --version must show 22.5.0 or higher.
A new project shows Missing APP_KEY or a database error on the first runRun kreft mobile:setup (or kreft mobile:dev, which does it): it creates .env and the key, links storage and migrates.
The phone shows an old version of your app after you rebuiltAn older build registered a service worker that keeps serving cached files. New builds remove it by themselves, but a phone that already has it may need the app's data cleared once (Android: App info → Storage → Clear data, or adb shell pm clear com.example.yourapp) or the app uninstalled and installed again.
kreft --version shows an old numberAnother copy comes first on your PATH. Run which -a kreftjs (Windows: where kreftjs) and remove the old one.
PowerShell says "running scripts is disabled" (Windows)Run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned, or use Command Prompt.
The browser shows a blank page or "Not found: /"Run kreft dev from the project's top folder (the one with frontend/ and backend/). The dev server serves frontend/.

Next: Your first app.

#Your first app

Create a project, move into it and start the development server:

BASH
kreft new my-app            # asks: JavaScript or TypeScript?
cd my-app
npm run dev

Pass --js or --ts to skip the question, and --db sqlite or --ui tailwind (also bootstrap, bulma, pico) to start with a database or a CSS library.

Options can be combined. For example, a Bootstrap app without login pages:

BASH
kreft new app-name --ui bootstrap --no-auth

More examples:

BASH
kreft new shop --db mysql --ts          # TypeScript, with a MySQL database
kreft new site --ui tailwind --no-auth  # Tailwind, no sign-in
kreft new desk --electron               # with desktop-app support
kreft new desk --tauri                  # desktop app with small installers (needs Rust)
kreft new phone --harmony               # HarmonyOS app (Huawei, needs DevEco Studio)

A new app comes with login, registration, password reset, email verification, a profile and an admin area. It asks whether you want them; pass --auth or --no-auth to skip the question. --no-auth starts a plain site: the welcome page, the docs, the error monitor and the tests (and the Todos example with --db), with no users table, sessions or sign-in pages.

Open the address the terminal shows (normally http://localhost:8000). If that port is busy, the next free one is used.

The new project already has a working login page. npm run dev creates the tables and a test user, test@example.com with the password password. Emails (verify, reset) are printed in the terminal until you set MAIL_URL.

#The smallest possible app

You can use Kreft without any project at all. An app is an HTML page plus .kreft files:

HTML
<!-- index.html -->
<div id="app"></div>
<script src="kreftjs.js"></script>
<script>
  Kreftjs.app('App.kreft').mount('#app')
</script>
HTML
<!-- App.kreft -->
state name = 'World'

<view>
  <h1>Hello {name}</h1>
  <input k-model="name">
</view>

#Project structure

kreft new creates two folders that never mix: frontend/ is what browsers receive, backend/ is the server and is never reachable over HTTP.

TEXT
my-app/
├── frontend/
│   ├── index.html          entry point
│   ├── App.kreft             root component and router container
│   ├── routes/web.kreft      page routes
│   ├── layouts/            app.kreft (signed in), guest.kreft (sign-in pages)
│   ├── pages/              one .kreft file per screen, auth/ for sign-in pages
│   ├── components/         reusable pieces
│   ├── ui.css              the design system
│   └── tests/              component tests
├── backend/
│   ├── config/             app.js, auth.js, database.js, redis.js, session.js
│   ├── app/
│   │   ├── Http/           Controllers, Middleware, Requests, Resources
│   │   ├── Models/         User, PersonalAccessToken
│   │   └── Auth/           session helpers
│   ├── database/           migrations, seeders, factories
│   └── routes/             api.js, auth.js, console.js
├── .env                    secrets and settings (never commit it)
├── package.json
└── kreftjs.config.json         CLI options

#Why the two folders matter

  • kreft dev and kreft build serve only frontend/. The backend/ folder, database files and .env have no web address.
  • On macOS and Linux kreft new gives backend/ and .env permissions that only the owner can read.
  • Files such as .env, *.db, *.pem, package.json and kreftjs.config.json are refused even if requested by name.

#Adding a CSS library

Any CSS library works. Add its <link> to index.html, or install it and import the file from a .kreft file; it becomes a <link> added once, and kreft build copies it (with its fonts and images) into dist/vendor/.

HTML
import 'bootstrap/dist/css/bootstrap.min.css'   // npm i bootstrap
import './theme.css'                            // your own file, next to this .kreft file

#npm packages in the browser

Install a package with kreft add, then import it in any .kreft file:

BASH
kreft add dayjs nanoid lodash
kreft add -D esbuild      # once per project: it prepares packages for the browser
HTML
import dayjs from 'dayjs'
import { nanoid } from 'nanoid'

state id = nanoid()

<view>
  <p>{dayjs().format('YYYY-MM-DD')}</p>
</view>

kreft dev serves each package as one browser-ready file and tells the browser where it is with an import map. Old-style packages (module.exports, such as lodash) work too.

#The Kreft language

#Components and the .kreft file

A .kreft file has three parts:

  1. The script: everything outside <view> and <style>. Each line starts with a keyword.
  2. <view>: the HTML of the component.
  3. <style> (optional): CSS. Add scoped so it applies only to this component.

#Keywords

KeywordExampleMeaning
statestate count = 0A value that can change. When it changes, the view updates.
derivederive double = count * 2A value calculated from other values. It updates by itself.
actionaction add(n) { count += n }A function you call from the view or from other actions.
whenwhen count > 10 { … }Runs the block each time the condition becomes true.
watchwatch count { … }Runs each time the value changes. Inside, value is the new value and old the previous one.
onon ready { … }Lifecycle: on start, on ready, on update, on show, on hide, on destroy.
propprop start = 0A value the parent passes in. The value after = is the default.
eventevent save, removeEvents this component sends to its parent with send('save', data).
useuse cartUse a shared store. use mouse = trackMouse() uses shared logic from a .js file.
share / receiveshare theme = 'dark'Give a value to everything inside this component / take a value a parent shared.
importimport Card from './Card.kreft'Use another component or a JavaScript module.
savedsaved todos = []Like state, but kept in the browser (localStorage).
loadload users = api.get('/api/users')Loads data and gives users.data, users.loading, users.error, users.reload().

Inside the script you use names directly: write count++, not this.count++.

#A complete example

HTML
<!-- TodoPage.kreft -->
state todos = []
state text = ''

derive remaining = todos.filter((t) => !t.done).length

action add() {
  if (!text.trim()) return
  todos.push({ id: Date.now(), text, done: false })
  text = ''
}

action clearDone() {
  todos = todos.filter((t) => !t.done)
}

when todos.length && remaining === 0 {
  bus.send('toast', 'All done!')
}

<view>
  <form @submit.prevent={add}>
    <input k-model="text" placeholder="New todo">
  </form>
  <label k-each="todo in todos" k-key="todo.id">
    <input type="checkbox" k-model="todo.done"> {todo.text}
  </label>
  <p>{remaining} left · <button @click={clearDone}>Clear done</button></p>
</view>

#Good to know

  • An action that uses await becomes async automatically.
  • A line that does not start with a keyword is normal JavaScript (let timer, const max = 10). Your actions can use it, but the view cannot. Use state, derive or action for anything the view needs.
  • Every Kreft function is available in the script: bus, store, signal, watch, tick, send, props, $route, $router.
  • Errors name the file and line, for example "state" needs a name, like: state count = 0 (Bad.kreft, line 3).

#Lifecycle

HookRuns
on startBefore the component is shown. Good for first data.
on readyThe component is on the screen.
on updateAfter the view changed.
on show / on hideA kept component comes back / is put away.
on destroyThe component is being removed. Clean up here.

#Templates and directives

#Showing values

HTML
<h1>Hello {name}</h1>
<p>{count} items · total {total.toFixed(2)}</p>
<p>{isAdmin ? 'Admin' : 'User'}</p>

Values are always escaped, so they are safe to show. To show a literal {, write \{.

#Attributes

HTML
<img src={user.photo} alt={user.name}>         <!-- the value as it is -->
<button disabled={count === 0}>Reset</button>   <!-- false removes the attribute -->
<div class="card {active ? 'on' : ''}">         <!-- build a text -->
<a href="/users/{user.id}">Profile</a>

:class and :style also accept objects: :class="{ done: todo.done }".

#Events

HTML
<button @click={add}>Add</button>
<button @click="add(5)">Add 5</button>
<input @input="search($event.target.value)">
<form @submit.prevent={save}>
<input @keyup.enter={send}>

Modifiers: .prevent .stop .self .once .capture .passive. Keys: .enter .esc .space .tab .up .down .ctrl .shift .alt .meta .exact.

#Directives

DirectiveWhat it does
k-if / k-elif / k-elseAdds or removes the element.
k-match="value" + k-case / k-default on its childrenShows the child whose k-case equals the value. See Choosing with k-match.
k-each="item in list" + k-key="item.id"Repeats the element. Also (item, i) in list, (value, key) in object, n in 10.
k-model="name"Two-way binding for input, textarea, select, checkbox and radio. Modifiers .trim .number .lazy.
k-showHides with CSS instead of removing.
k-text / k-htmlSets text, or HTML. k-html is cleaned of scripts and event handlers, but only bind HTML you trust.
k-ref="box"Gives you the element: state box = null receives it.
k-skipLeaves the element as it is (for code samples that contain { }).
k-onceDraws the element once and never updates it.
k-memo="[a, b]"Updates the element only when a or b changes.
k-animate="fade"Animates the element when it comes and goes.
<template k-if> / <template k-each>Groups elements without a wrapper.
<kreft-component :is="name">Shows a component chosen while the app runs.
<kreft-portal to="body">Renders content somewhere else (modals, toasts).

#Loops

HTML
<ul>
  {for user in users key user.id}
    <li>{user.name}</li>
  {empty}
    <li>No users yet</li>
  {/for}
</ul>
  • key user.id is optional; it lets Kreft keep and move the right rows.
  • {empty} is optional and shows when the list is empty.
  • {for (user, i) in users} gives the index, {for (value, key) in object} walks an object, {for n in 5} counts 1 to 5.
  • k-each on an element does the same: <li k-each="user in users" k-key="user.id">.

#Animations

HTML
<p k-if="open" k-animate="fade">Hello</p>
<div k-show="menu" k-animate="slide">…</div>

<ul>
  {for item in items key item.id animate slide}
    <li>{item.name}</li>
  {/for}
</ul>

k-animate works with k-if, k-show, loops, <kreft-component> and <kreft-view>. Ready-made: fade, slide, scale, pop.

Your own animation is CSS with these classes (replace name):

ClassWhen
name-inThe whole time it comes in (put the transition here).
name-in-fromThe first moment: where it comes from.
name-outThe whole time it goes out.
name-out-toWhere it goes to.
name-moveA list item moving to its new place.
CSS
.drop-in, .drop-out { transition: all .3s ease }
.drop-in-from { opacity: 0; transform: translateY(-30px) }
.drop-out-to  { opacity: 0; transform: translateX(60px) }
  • Kreft waits for the longest transition or animation before removing the element.
  • k-animate.after lets the old element leave before the new one comes in.
  • Nothing animates when the page first opens; add .first to animate then too.

#Faster views

Kreft already changes only the exact text or attribute that changed. For very large pages:

HTML
<footer k-once>Opened at {openedAt}</footer>

{for row in rows key row.id}
  <tr k-memo="[row.id === selected]" class={row.id === selected ? 'on' : ''}>…</tr>
{/for}

With k-memo, picking another row redraws two rows, not all of them.

#Your own directives

JS
app.directive('focus', {
  ready(el, binding) { el.focus() },
  update(el, binding) {},
  destroy(el, binding) {},
})
HTML
<input k-focus>
<div k-tooltip:top={message}></div>   <!-- binding.arg = 'top', binding.value = message -->

#Choosing with k-match

When one value decides what to show, k-match reads better than a chain of k-if / k-elif:

HTML
<div k-match="status">
  <b k-case="'ok'">Done</b>
  <i k-case="'wait', 'queued'">Waiting</i>
  <u k-default>Unknown</u>
</div>
  • The comparison is strict (===). Several values in one k-case (separated by commas) mean "one of these".
  • Only the first matching case shows. k-default shows when none match; put it last.
  • The children are turned into k-if / k-elif / k-else, so components, <template> and k-animate work on them as usual.

#Pipes

Pass a value through a pipe with | to format it, instead of calling helper functions in the view:

HTML
<p>{price | currency:'EUR'}</p>
<p>{createdAt | ago}</p>
<p>{title | capitalize | truncate:30}</p>
<a title={name | upper}>{tags | join:' · '}</a>
  • Arguments follow a colon (truncate:30, currency:'EUR') or sit in parentheses (number(2)). Pipes run left to right.
  • ||, |= and a | inside a string, a regular expression or brackets are not pipes.
  • Numbers, currency and dates follow the app's language (Kreftjs.locale).
PipeResult
upper lower capitalize trimText case and spaces.
truncate:nCuts text to n characters and adds ….
currency:'USD'$1,234.50, in the current language.
number:digits percent:digits1,234.5, 45% (0.45).
date:'short' timeshort, medium (default), long, full; or an Intl.DateTimeFormat options object.
ago3 hours ago, in 2 days. A date like 2026-11-05 15:39:58 from the Kreft database is read as UTC.
bytes1.5 KB.
jsonPretty-printed JSON, for debugging.
fallback:'n/a'The value, or the fallback when it is empty.
join:sep first last slice:a:b reverse sortBy:'key':'desc' countLists.

Your own pipe. Any function in the component works as a pipe, and wins over a built-in with the same name:

HTML
const wrap = (value, left = '«', right = '»') => left + value + right

<view><p>{name | wrap}</p> <p>{name | wrap:'[':']'}</p></view>

For the whole app: Kreftjs.pipe('shout', (value) => String(value).toUpperCase() + '!').

a | b used to be a bitwise OR. In a view it is now a pipe; write bit operations inside a function in the script.

#Props, events and slots

#Using a component

Register it once by its path, or import it where you need it:

JS
Kreftjs.app('App.kreft')
  .component('UserCard', 'components/UserCard.kreft')
  .mount('#app')
HTML
import UserCard from './UserCard.kreft'

<view>
  <user-card name="Alice Smith" age={30}></user-card>
</view>

In the view, write component names in kebab-case (<user-card>).

#Props: parent to child

HTML
<!-- UserCard.kreft -->
prop name
prop age = 0
prop admin = false

<view>
  <div class="card">{name} ({age}) <b k-if="admin">admin</b></div>
</view>
HTML
<user-card name="Alice Smith" age={30} admin></user-card>

The default's type decides how plain text attributes are read: age="30" becomes the number 30, and admin with no value becomes true. A child cannot change a prop; send an event instead.

#Typed props

Write the type the way TypeScript does. A wrong value, or a missing required prop, warns while you develop (in kreft dev and in a built app's console):

HTML
prop tone: 'info' | 'warn' = 'info'   // only these values; 'info' when not given
prop label: string                     // required: leaving it out warns
prop count?: number                    // optional
prop items: string[] = []
prop onSave: (id: number) => void
  • Checked: string number boolean null undefined object Date, T[], functions, literal values ('sm', 3, true) and unions of them. Your own type names (User), any and unknown are not checked.
  • A prop is required when it has no default, no ? and its type has no null / undefined.
  • number, boolean and string also decide how a plain attribute is read: count="5" becomes 5.

#Events: child to parent

HTML
<!-- TodoItem.kreft -->
prop todo
event remove

<view>
  <li>{todo.text} <button @click="send('remove', todo.id)">✕</button></li>
</view>
HTML
<!-- parent -->
action removeTodo(id) { todos = todos.filter((t) => t.id !== id) }

<view>
  <todo-item k-each="t in todos" k-key="t.id" todo={t} @remove={removeTodo}></todo-item>
</view>

#k-model on a component

HTML
<!-- Toggle.kreft -->
prop modelValue = false
event update:modelValue

<view>
  <button @click="send('update:modelValue', !modelValue)">{modelValue ? 'On' : 'Off'}</button>
</view>
HTML
<toggle k-model="darkMode"></toggle>

Named models: k-model:title="pageTitle" uses prop title and the event update:title.

#Slots

HTML
<!-- Card.kreft -->
prop items = []

<view>
  <div class="card">
    <header><slot name="header">Default title</slot></header>
    <slot></slot>
    <li k-each="item in items"><slot name="item" item={item}>{item}</slot></li>
  </div>
</view>
HTML
<card items={users}>
  <template k-slot:header>Users</template>
  <p>Body content</p>
  <template k-slot:item="{ item }"><b>{item.name}</b></template>
</card>

#Styles

  • <style> applies to the whole page.
  • <style scoped> applies only to this component.
  • .parent :deep(.child) reaches into child components from scoped CSS.
  • Attributes such as class that you put on a component tag land on its root element.

#Keep and wait

Keep puts a component away instead of removing it. Typed text, scroll position and state are all still there when it returns:

HTML
<kreft-component :is="tab" keep></kreft-component>
<kreft-view keep></kreft-view>
<kreft-view keep="5"></kreft-view>   <!-- keep at most 5; the one used longest ago goes -->
HTML
on show { timer.start() }   <!-- it came back (also the first time) -->
on hide { timer.stop() }    <!-- it was put away -->

Wait shows a placeholder until everything inside is ready (lazy components, every load, every on start that awaits):

HTML
<kreft-wait>
  <user-profile id={5}></user-profile>
  <p k-waiting>Loading…</p>
  <p k-failed="error">Could not load: {error.message}</p>
</kreft-wait>

#Sharing state

NeedUse
Parent to childprop
Child to parentevent + send(), or k-model
Many components, anywherestores: Kreftjs.store() + use
A parent to everything inside itshare / receive
"Something happened" messagesbus.send() / bus.on()

#Stores

Create a store once in your page's script:

JS
Kreftjs.store('cart', {
  items: [],
  get count() { return this.items.length },
  get total() { return this.items.reduce((s, p) => s + p.price, 0) },
  add(product) { this.items.push(product) },
})

Use it in any .kreft file. Every component sees the same data:

HTML
use cart

<view>
  <span>Cart: {cart.count} · {cart.total}</span>
  <button @click="cart.add(product)">Add</button>
</view>

Every store also has $patch (change several values at once), $reset() (back to the start) and $watch(fn) (runs on every change and stops by itself when the component goes away).

#Shared logic

Logic that many components need goes in a .js file as a function. It can use Kreftjs.state, Kreftjs.watch, Kreftjs.onDestroy and the rest:

JS
// logic/mouse.js
export function trackMouse() {
  const pos = Kreftjs.state({ x: 0, y: 0 })
  const move = (e) => { pos.x = e.clientX; pos.y = e.clientY }
  window.addEventListener('pointermove', move)
  Kreftjs.onDestroy(() => window.removeEventListener('pointermove', move))
  return pos
}
HTML
import { trackMouse } from '../logic/mouse.js'
use mouse = trackMouse()

<view><p>{mouse.x}, {mouse.y}</p></view>

#Share and receive

HTML
<!-- Layout.kreft -->
state settings = { theme: 'dark', lang: 'so' }
share settings = settings

<!-- any component inside it, however deep -->
receive settings

<view><p>Theme: {settings.theme}</p></view>

Share a state object and every receiver updates when it changes. Kreftjs.app(…).share('key', value) shares with the whole app.

#Event bus

HTML
<!-- sending -->
action save() { bus.send('toast', 'Saved!') }

<!-- listening -->
state message = ''
on ready { bus.on('toast', (text) => (message = text)) }

Listeners added in on start or on ready are removed automatically when the component goes away. Others stay until you call bus.off('toast', fn).

#Saving data in the browser

Write saved instead of state and the value is kept in localStorage. It survives reloads and closing the browser.

HTML
saved todos = []
saved theme = 'light'
saved token = '' as 'auth.token'    <!-- choose the storage key yourself -->
  • Every change is saved by itself, including deep ones: todos.push(…), todo.done = true.
  • The default key is <Component>.<name>, for example Home.todos. Use as '…' to share one value between components.
  • A change made in another tab of the same site shows up in this tab too.

A store keeps its plain values when you add saved:

JS
Kreftjs.store('cart', { items: [] }, { saved: true })            // or { saved: ['items'] } for some fields

From JavaScript:

JS
const theme = Kreftjs.saved('theme', 'light')    // a signal: theme.value = 'dark' is saved
Kreftjs.storage.set('user', { name: 'Alice Smith' })
Kreftjs.storage.get('user')
Kreftjs.storage.remove('user')
Kreftjs.storage.clear()                          // removes only what Kreft saved

#Router and layouts

#Defining routes

JS
const router = Kreftjs.router({
  routes: [
    { path: '/', component: 'pages/Home.kreft', meta: { title: 'Home' } },
    { path: '/users/:id', name: 'user', component: 'pages/User.kreft', props: true },
    { path: '/posts/:slug?', component: 'pages/Posts.kreft' },
    { path: '/old', redirect: '/' },
    { path: '/admin', component: 'pages/Admin.kreft', guard: () => isAdmin() || '/login' },
    { path: '*', component: 'pages/NotFound.kreft' },
  ],
})

Kreftjs.app('App.kreft').use(router).mount('#app')
HTML
<!-- App.kreft -->
<view>
  <nav>
    <kreft-link to="/">Home</kreft-link>
    <kreft-link to="/users/{user.id}">Profile</kreft-link>
  </nav>
  <kreft-view></kreft-view>
</view>

With props: true, the :id parameter arrives as a prop:

HTML
<!-- pages/User.kreft -->
prop id
derive user = users.find(id)
action back() { $router.back() }
FeatureHow
Current route$route.path, $route.params.id, $route.query.tab, $route.meta
Navigate$router.go('/users/5?tab=info'), $router.replace(to), $router.back()
Active linkThe kreft-link-active and kreft-link-exact classes
Page titlemeta: { title: '…' }
Check before every pagerouter.before((to, from) => …). Return false to stop, or a path to go elsewhere.
Check one routeguard: (to, from) => …
After every pagerouter.after((to, from) => …)

Each page file is loaded the first time someone opens it.

#Route files

New projects keep their pages in frontend/routes/web.kreft, and index.html only points to it:

JS
Kreftjs.router({
  routes: ['routes/web.kreft', 'routes/shop.kreft'],
  layout: 'app',
  errors: 'errors',
  middleware: {
    auth: (to) => (auth.user ? true : '/login?redirect=' + encodeURIComponent(to.fullPath)),
    guest: () => (auth.user ? '/dashboard' : true),
  },
})
JS
// routes/web.kreft
Route.view('/', 'pages/Home.kreft').name('home').title('Home')
Route.view('/posts/:id', 'pages/Post.kreft')

Route.middleware('auth').group(() => {
  Route.view('/dashboard', 'pages/Dashboard.kreft').middleware('verified')
})

Route.layout('guest').middleware('guest').group(() => {
  Route.view('/login', 'pages/auth/Login.kreft').title('Log in')
})

Route.prefix('/account').name('account.').middleware('auth').group(() => {
  Route.view('/settings', 'pages/account/Settings.kreft').children(() => {
    Route.view('', 'pages/account/General.kreft')       // /account/settings
    Route.view('mail', 'pages/account/Mail.kreft')      // /account/settings/mail
  })
})

Route.redirect('/home', '/')
Route.fallback('pages/NotFound.kreft')
On a routeWhat it does
.name('home')$router.go({ name: 'home' })
.title('Home')The page title.
.layout('guest'), .layout('none')Another layout, or none.
.middleware('auth', 'role:editor')Runs these before the page.
.meta({ … })Anything else, in $route.meta.
.children(() => …)Nested pages, shown in the page's own <kreft-view>.

#File-based routing

Like Next.js and Nuxt, the pages in frontend/pages/ can be routes by their file names, with no route file to write. Turn it on with 'pages/' in the router's routes:

JS
Kreftjs.router({ routes: ['routes/web.kreft', 'pages/'] })   // routes written by hand come first and win
FileAddress
pages/index.kreft/
pages/About.kreft/about (PascalCase becomes kebab-case: ForgotPassword.kreft → /forgot-password)
pages/posts/index.kreft/posts
pages/posts/[slug].kreft/posts/:slug (the page gets the prop slug)
pages/users/[[id]].kreft/users/:id? (optional)
pages/docs/[...path].kreft/docs/* (everything below /docs); pages/[...missing].kreft catches every unknown address
pages/(admin)/Reports.kreft/reports (a folder in brackets groups pages without adding to the address)
pages/_Card.kreftnot a page (a name starting with _ is a part)

A page says the rest of its route in its first lines:

HTML
<!-- pages/(admin)/Reports.kreft -->
title 'Reports'
middleware auth, admin
layout app

<view>…</view>

kreft dev reads the folder on each request (/__kreft/pages.json), so a new file is a new page at once; kreft build writes the list into app.js, and kreft sitemap lists every page without a :param and without a middleware. Pages are drawn on the server like any other (Pages drawn on the server). Static addresses come before dynamic ones, and the catch-all last.

#Layouts

A layout is the frame around your pages: bar, menu, footer. Put it in layouts/ and use <slot> where the page goes.

HTML
<!-- layouts/app.kreft -->
state menuOpen = false

<view>
  <header>…</header>
  <main><slot></slot></main>
</view>
WhereWhat you write
Every pageKreftjs.router({ layout: 'app', routes })
One route and its children{ path: '/admin', component: …, layout: 'admin' }
Inside a page filelayout admin on its own line
No layoutlayout: false on the route, or layout none in the page

When more than one applies, the route wins, then the page file, then the router. Going between two pages that use the same layout keeps the layout on screen, with its state.

A page can also fill other places in its layout:

HTML
<!-- in the layout -->
<kreft-yield name="actions">shown when the page has no such section</kreft-yield>

<!-- in the page -->
<kreft-section name="actions">
  <button class="primary" @click="save()">Save</button>
</kreft-section>

#Error pages

Each HTTP error can have its own page in errors/. Turn them on with errors: 'errors' in the router. New projects already have the folder (kreft make:errors adds it to an older one):

TEXT
errors/401.kreft 402.kreft 403.kreft 404.kreft 419.kreft 429.kreft 500.kreft 503.kreft
errors/error.kreft      any other status
errors/minimal.kreft    the shared frame

An unknown address shows errors/404.kreft; a page that cannot load shows errors/500.kreft. From any .kreft file, abort(404) (also $router.abort() and Kreftjs.abort()) shows the matching page:

HTML
prop id
load post = api.get('/api/posts/' + id)
watch post.error { if (post.error && post.error.status === 404) abort(404) }

#Clean URLs

By default the router uses URLs without # (/users/5). Two things make that work:

  1. A <base href="/"> tag in index.html (use <base href="/demo/"> if the app lives in a folder).
  2. The server must send index.html for every page path, so reloading /users/5 is not a 404. npm run dev does this for you.

If you cannot change the server, use mode: 'hash'; URLs then look like /#/users/5.

#Fetching data

The global api client is available in every .kreft file, and Kreftjs.api in plain JavaScript:

JS
const users = await api.get('/api/users', { query: { page: 2 } })
const user  = await api.post('/api/users', { name: 'Alice Smith' })
await api.put('/api/users/1', user)
await api.patch('/api/users/1', { status: 'active' })
await api.delete('/api/users/1')

#Loading data: load

load declares a reactive resource. It handles the loading state, the error, and fetches again when the values it reads change:

HTML
<!-- pages/Posts.kreft -->
state query = ''
state page = 1

load posts = api.get('/api/posts', { query: { q: query || undefined, page } })

<view>
  <input type="search" k-model.lazy="query" placeholder="Search posts…">

  <p k-if="posts.loading">Loading posts…</p>
  <div k-elif="posts.error">
    Failed to load: {posts.error.message}
    <button @click={posts.reload}>Try again</button>
  </div>
  <div k-else>
    {for post in posts.data || [] key post.id}
      <article><h3>{post.title}</h3><p>{post.body}</p></article>
    {empty}
      <p>No posts found for "{query}".</p>
    {/for}
  </div>

  <button @click={() => page++}>Next page ({page})</button>
</view>
PropertyMeaning
posts.dataThe result (null until loaded).
posts.loadingtrue while a request is running.
posts.loadedtrue once the first answer arrived.
posts.errorThe error, or null.
posts.reload()Fetch again now.

#Tables

For tables served by kreft dev --db or the automatic table API, table(name) gives ready-made calls:

HTML
const posts = table('posts')

load list = posts.all({ q: search, _sort: '-created_at', _limit: 10 })

action createPost() {
  const created = await posts.create({ title: 'New article' })
  list.data = [created, ...list.data]
}

Methods: all(query), find(id), count(query), create(data), update(id, data) (PUT), patch(id, data), remove(id).

#Errors

A failed request throws an ApiError with status, message, data and errors (validation messages). Network problems and timeouts have status 0.

HTML
state errors = {}

action save() {
  try {
    await api.post('/api/users', form)
  } catch (e) {
    errors = e.errors || {}      // { email: ['The email has already been taken.'] }
  }
}

#Settings

JS
Kreftjs.api.setup({
  base: '/api',                               // then api.get('users') is /api/users
  token: () => Kreftjs.storage.get('token'),      // sent as Authorization: Bearer …
  headers: { 'Accept-Language': 'en' },
  timeout: 10000,
})

Kreftjs.api.onError((e) => { if (e.status === 401) location.href = '/login' })

const github = Kreftjs.api.create({ base: 'https://api.github.com' })    // a second client

Options for one request: query, headers, timeout, signal (to cancel) and full: true (returns { data, status, headers }).

Requests to your own backend also send X-XSRF-TOKEN from the XSRF-TOKEN cookie (and X-CSRF-TOKEN from <meta name="csrf-token">), plus X-Requested-With.

#A practice API

BASH
kreft dev --api db.json              # a REST API at /api, made from a JSON file
kreft dev --api db.json --delay 500  # answer slowly, to see loading states

It gives GET and POST on /api/posts, GET, PUT, PATCH and DELETE on /api/posts/1, search with ?q=text, filters with ?field=value, and standard paging and sorting.

#Forms and validation

Give a form its rules in declarative style. A form with mistakes is never sent:

HTML
state post = form({ title: '', email: '' }, { title: 'required|min:3|max:120', email: 'required|email' })

action save() {
  const created = await post.$submit((values) => api.post('/api/posts', values))
  if (created) post.$reset()
}

<view>
  <form @submit.prevent={save}>
    <input k-model="post.title">
    <p k-if="post.$error('title')" class="error">{post.$error('title')}</p>
    <button disabled={post.$busy}>Save</button>
  </form>
</view>
On the formWhat it is
post.title, post.emailThe values, for k-model.
post.$error('title')The first message for a field, or ''.
post.$errorsEvery message: { title: ['…'] }.
post.$valid, post.$busyNo mistakes / sending right now.
post.$submit(send)Checks, then calls send(values). A 422 from the server fills the same errors. Gives false when it did not send.
post.$check(), post.$reset(values?), post.$setErrors(e)Check now / start again / show errors from elsewhere.

Errors appear after the first submit, then follow your typing.

Without a form, validate(values, rules) gives {} or { field: ['…'] }. Custom messages go in the third argument: form(values, rules, { messages: { 'title.required': 'Write a title.' } }).

The same rule names work on the server in req.validate() (see Controllers and requests), so one set of rules can describe both sides.

#Passwords

not_common_password refuses a password that is among the most used ones (password, 12345678, qwertyuiop …), one character repeated (aaaaaaaa), a plain run (12345678, abcdefgh), or the same as the email address. A new app uses it next to min:8 when people register, reset or change a password, in the pages and in the controllers:

JS
password: 'required|min:8|confirmed|not_common_password'

It is a short list that runs offline, with no service called, so it catches the worst choices and nothing more. For longer ones, raise min (a passphrase of four words beats a short mix of symbols). Change the message in lang/en/validation.json (not_common_password).

#Internationalization and RTL

Kreft translates text and flips direction for right-to-left languages such as Arabic, Hebrew, Persian and Urdu.

#Translations

Put translation files in a lang/ folder: lang/ or frontend/lang/ in your project (backend/lang/ and resources/lang/ are read too). Use lang/en.json for plain strings, or lang/en/messages.json for grouped keys. In any view:

HTML
<h1>{$t('messages.welcome', { name: user.name })}</h1>
<p>{$choice('messages.apples', count)}</p>

A message uses :name for values. For plurals, separate the forms with |: {0} No apples|{1} One apple|[2,*] :count apples. Under the hood, categories use the browser's Intl.PluralRules for the current locale.

Change the language with Kreftjs.locale('ar'). The page's <html lang> and dir update, and every view re-renders. Kreftjs.fallbackLocale('en') sets the fallback, Kreftjs.locales() lists loaded languages, and Kreftjs.translations('so', { … }) registers more text from code.

#Direction

dir is set for you from the locale, and you can also bind it by hand:

HTML
<view dir={isArabic ? 'rtl' : 'ltr'}>…</view>

#Write CSS that flips by itself

Use CSS logical properties instead of left/right:

AvoidUse
margin-left / margin-rightmargin-inline-start / margin-inline-end
padding-left / padding-rightpadding-inline-start / padding-inline-end
left: 0 / right: 0inset-inline-start: 0 / inset-inline-end: 0
text-align: left / righttext-align: start / end
border-left / border-rightborder-inline-start / border-inline-end
CSS
.sidebar {
  position: fixed;
  inset-inline-start: 0;           /* left in LTR, right in RTL */
  padding-inline-start: 24px;
  border-inline-end: 1px solid var(--border);
}

[dir="rtl"] .back-arrow { transform: scaleX(-1); }    /* flip an icon */

On the server, request language comes from ?lang=, the lang cookie or Accept-Language, and backend messages live in backend/lang/<locale>/.

#Using Kreft from JavaScript

You can write components as plain objects. The rules match the .kreft language: values are state, getters are derived values, functions are actions.

JS
Kreftjs.app({
  count: 0,
  get double() { return this.count * 2 },
  add() { this.count++ },
  template: `<button @click={add}>{count} × 2 = {double}</button>`,
}).mount('#app')
JavaScriptSame as in .kreft
Kreftjs.state({ … })state + derive + action together, for code outside components.
Kreftjs.signal(0)One value, read and written with .value.
Kreftjs.derived(() => …)derive
Kreftjs.watch(source, (value, old) => …)watch
Kreftjs.effect(() => …)Runs again whenever what it reads changes.
Kreftjs.tick()Wait until the page has updated.

Kreftjs.render(view, data) turns a view and data into an HTML string, with every directive working and every value escaped. Use it for emails and print views:

JS
Kreftjs.render(`<ul><li k-each="u in users">{u}</li></ul>`, { users: ['Alex', 'Alice'] })
// <ul><li>Alex</li><li>Alice</li></ul>

#Server templates

Blade and similar engines use {{ }}; Kreft uses { }, so they do not clash. Put kreftjs.js and your .kreft files in your public folder and mount as usual.

#Backend

#Routing

A project made with kreft new has a Node.js backend. kreft dev and kreft serve load backend/routes/api.js by themselves, every address in it starts with /api, and kreft dev picks up each change you save. The backend folder never reaches the browser.

JS
// routes/api.js
const { Route } = require('kreftjs/server')
const PostController = require('../app/Http/Controllers/PostController')

Route.get('/hello', (req) => ({ hello: req.input('name', 'world') }))      // GET /api/hello

Route.apiResource('posts', PostController)    // index, store, show, update, destroy
Route.get('/posts/{post}/comments', [PostController, 'comments']).name('posts.comments')

Route.middleware('auth').group(() => {
  Route.delete('/posts/{post}', [PostController, 'destroy'])
})

Route.prefix('admin').middleware(['auth', 'admin']).group(() => { … })
  • Parameters are written {post}, or {post?} when optional.
  • A route can have a name (.name('…')), a pattern (.whereNumber('id')) and middleware (.middleware('auth')).
  • kreft route:list prints every route with its name, controller and middleware.

#Namespaces

PHP-style namespaces are supported for controllers, models and relations:

JS
const { Route, use, namespace } = require('kreftjs/server')

const User = use('App\\Models\\User')
const { DashboardController, UserController } = namespace('App\\Http\\Controllers\\Admin')

Route.namespace('Admin').group(() => {
  Route.get('/users', 'UserController@index')
  Route.apiResource('users', 'UserController')
})

#Controllers and requests

A controller method gets the request first, then the route's parameters. What it returns is sent as JSON; returning nothing answers 204.

JS
const { response, abort } = require('kreftjs/server')
const Post = require('../../Models/Post')

class PostController {
  async index(req) {
    return Post.with('author').where('published', true).latest().paginate(15, req.integer('page', 1))
  }

  async store(req) {
    const data = await req.validate({
      title: 'required|max:200|unique:posts,title',
      author_id: 'required|exists:authors,id',
    })
    return response(await Post.create(data), 201)
  }

  async show(req, id) { return Post.findOrFail(id) }               // 404 when missing
  async destroy(req, id) { await (await Post.findOrFail(id)).delete() }
}

module.exports = PostController

Generate one with kreft make:controller PostController --api (also --model Post, --route=api, --auth).

#The request

CallGives
req.input('name', default), req.all(), req.only('a', 'b'), req.except(…), req.has(…), req.filled(…)Values from the body and the query.
req.boolean('x'), req.integer('page', 1), req.string('q')A value in the right type.
await req.validate(rules, messages, names)The same rules as form(), plus unique:table,column and exists:table,column. Returns only the checked fields, or answers 422. messages are your own texts ({ 'title.unique': 'That title is already used.' }, or { unique: '…' } for every field); names are nicer field names ({ email: 'e-mail address' }).
req.params, req.query, req.body, req.header('x'), req.bearerToken(), req.ip(), req.userThe rest.
req.file('avatar').store('avatars')Saves an upload with a random name.
response(data, 201), response(data).header('X', 'y'), abort(403, 'message')Answers.
response.stream('/path/video.mp4', { type, download, headers })Sends a file with byte ranges. See Video and audio files.

#Video and audio files

To serve a video or audio file, return response.stream(path) instead of reading the file yourself:

JS
const path = require('path')

Route.get('/videos/:name', (req) =>
  response.stream(path.join(__dirname, '../storage/videos', path.basename(req.params.name))))

Route.get('/podcast/:id/download', (req) =>
  response.stream('/var/media/episode.mp3', { download: true }))   // saved as a file instead of played
  • Seeking works. The server answers Range requests with 206 Partial Content, so a player can jump to any minute without downloading the rest, and Safari, which refuses to play video without ranges, plays it. A range that does not fit the file gets 416.
  • Only the needed bytes are read, and reading stops when the viewer leaves or seeks elsewhere.
  • Caching is built in. The answer carries ETag and Last-Modified, so an unchanged file is answered with 304. HEAD requests get the headers only.
  • A missing file is a plain 404, not a crash.
  • Options: type (the media type; guessed from the extension for mp4, webm, mov, mp3, m4a, ogg, wav, flac, m3u8, mpd, vtt …), download: true (adds Content-Disposition: attachment), and headers (extra headers).

kreft dev and kreft serve also send the static media files of your app (.mp4, .webm, .mp3, HLS playlists …) with ranges, so a <video src="/intro.mp4" controls> seeks without any code.

#Form requests, resources and policies

For bigger endpoints, move rules and authorization out of the controller:

JS
// app/Http/Requests/StorePostRequest.js
const { FormRequest } = require('kreftjs/server')

class StorePostRequest extends FormRequest {
  authorize(req) { return req.user != null }           // false answers 403
  rules() { return { title: 'required|max:200', body: 'required' } }
  messages() { return { 'title.required': 'Give the post a title.' } }
}

module.exports = StorePostRequest
JS
const data = await StorePostRequest.validate(req)                // in a controller
return PostResource.collection(await Post.paginate(15))          // { data, meta }
await req.authorize('update', post)                              // app/Policies/PostPolicy.js

Generate them with kreft make:request, kreft make:resource and kreft make:policy.

#Passing data from controllers to pages

A page receives data from the API with load (see Fetching data). Return plain objects, collections or paginator results from controllers; hidden model fields (static hidden) are never included.

#Server actions

Like Next.js server actions, a page can call a function of your backend directly, with no route or fetch to write. Put them in backend/app/Actions/ (kreft make:action Posts):

JS
// backend/app/Actions/Posts.js
const { action } = require('kreftjs/server')
exports.create = action({ rules: { title: 'required|max:120' } }, async (input, { user }) => Post.create({ ...input, user_id: user.id }))
exports.latest = action({ public: true }, async () => Post.latest().limit(5).get())
exports.remove = action({ authorize: (user) => user.is_admin }, async ({ id }) => { await Post.destroy(id) })
JS
// in a page
const post = await Kreftjs.actions.posts.create({ title })   // or Kreftjs.action('posts/create')({ title })
await form.$submit(Kreftjs.actions.posts.create)             // a 422 fills the form's errors

Each action is a POST /api/_actions/<file>/<name> route (kreft route:list shows them) and goes through the same middleware as your other routes. Only functions wrapped in action() can be called; an action needs a signed-in user (auth) unless it says public: true; with rules it gets only the checked fields (422 otherwise); authorize(user, input) returning false gives 403; prototype keys are removed from the input.

#Models and the database

Models are Active Record classes, like Eloquent:

JS
// app/Models/Post.js
const { Model, Str } = require('kreftjs/server')

class Post extends Model {
  static fillable = ['title', 'body', 'user_id']        // what create() and update() may fill
  static hidden = []                                    // never sent as JSON
  static casts = { published: 'boolean', meta: 'json' }
  static softDeletes = true                             // delete() fills deleted_at

  user() { return this.belongsTo(require('./User')) }
  comments() { return this.hasMany(require('./Comment')) }
  tags() { return this.belongsToMany(require('./Tag')) }

  static scopePublished(q) { q.where('published', true) }
  static async creating(post) { post.slug ??= Str.slug(post.title) }
}

module.exports = Post

Always set static fillable. Without it a model lets create() and update() set every column except id, so Post.create(req.all()) would save { "is_admin": true } from a visitor. The controllers made by kreft make:controller --model read only the fillable columns (req.only(...Model.fillable)) and stop with an error until you set it. Kreft prints a warning when a model without fillable is given a privilege-looking column (is_admin, role, permissions …).

The table is the plural of the class name (Post is posts); set static table = '…' for another one.

#Querying

JS
await Post.all()
await Post.find(5)                       // or findOrFail(5): 404 when missing
await Post.where('published', true).orderByDesc('id').limit(10).get()
await Post.where('views', '>', 100).orWhere('pinned', true).count()
await Post.query().published().with('user', 'comments.author').withCount('comments').paginate(15, page)
await Post.query().whereHas('comments', (q) => q.where('approved', true)).get()

const post = await Post.create({ title: 'Hi' })     // fills created_at and updated_at
await post.update({ title: 'Hello' })
await post.delete()

await post.comments().create({ body: 'Nice' })
await post.tags().sync([1, 2, 3])                   // also attach(), detach(), toggle()

Relations: hasOne, hasMany, belongsTo, belongsToMany (with pivot), hasManyThrough. Soft deleted rows come back with withTrashed() and return with restore().

Without a model:

JS
await DB.table('orders').join('users', 'users.id', '=', 'orders.user_id').groupBy('status').get()
await DB.select('SELECT * FROM posts WHERE id = ?', [5])
await DB.transaction(async () => { await Order.create({ … }); await Stock.decrement(…) })   // all or nothing

#Databases

The database comes from DATABASE_URL in .env:

ENV
DATABASE_URL=sqlite:backend/database/app.db                  # built into Node.js, nothing to install
DATABASE_URL=mysql://user:pass@localhost:3306/shop           # npm i mysql2
DATABASE_URL=postgres://user:pass@localhost:5432/shop        # npm i pg

The same migrations and models work on all three.

#Migrations, seeders and factories

A migration describes a table in JavaScript; the same file works on SQLite, MySQL and PostgreSQL:

JS
// database/migrations/2026_10_29_120000_create_posts_table.js
module.exports = {
  up(schema) {
    schema.create('posts', (table) => {
      table.id()
      table.foreignId('author_id').constrained().cascadeOnDelete()
      table.string('title', 200).unique()
      table.text('body').nullable()
      table.boolean('published').default(false)
      table.json('meta').nullable()
      table.timestamps()
    })
  },
  down(schema) {
    schema.dropIfExists('posts')
  },
}

Column types include id, string, text, integer, bigInteger, decimal, float, boolean, date, dateTime, timestamp, timestamps, json, foreignId. Plain .sql files in database/migrations also work (they run once each, in name order).

A seeder fills starting data:

JS
// database/seeders/DatabaseSeeder.js
const { Seeder } = require('kreftjs/server')
const Post = require('../../app/Models/Post')

class DatabaseSeeder extends Seeder {
  async run() {
    await Post.create({ title: 'Hello', author_id: 1 })
    await this.call(require('./CommentSeeder'))
  }
}

module.exports = DatabaseSeeder

Factories make fake data for seeders and tests:

JS
await User.factory().count(10).has(Post.factory().count(3), 'posts').create()

#Commands

CommandWhat it does
kreft migrateRuns the new migrations (kreft dev does this by itself).
kreft migrate:rollbackUndoes the last batch (--step 2 for the last two).
kreft migrate:fresh --seedDrops every table, migrates again, then seeds.
kreft migrate:statusWhich migrations ran.
kreft db:seedRuns DatabaseSeeder (--class PostSeeder for another).
kreft make:model Post -mfscA model plus migration (-m), factory (-f), seeder (-s), controller (-c), page (-p), route (-r).
kreft make:migration create_posts_tableadd_x_to_posts_table makes a schema.table one.
kreft make:seeder, kreft make:middlewareThe files, in the right folders.

#Authentication

New projects come with every sign-in screen and the backend behind it:

PageAddressWhat it does
pages/auth/Login.kreft/loginLog in with email and password.
pages/auth/Register.kreft/registerMake an account and get an email to verify the address.
pages/auth/ForgotPassword.kreft/forgot-passwordEmail a link to choose a new password.
pages/auth/ResetPassword.kreft/reset-password/:tokenThe link from that email.
pages/auth/VerifyEmail.kreft/verify-email"Check your email", and the link from it opens /verify-email/:id/:hash.
pages/auth/ConfirmPassword.kreft/confirm-passwordType the password again before something serious.
pages/Dashboard.kreft, pages/Profile.kreft/dashboard, /profileThe first page after logging in; account settings.

#How a login works

  • A login puts a token in an HttpOnly cookie. Page scripts cannot read it, so a script injected into a page cannot steal it. Only a hash of the token is stored in the database.
  • Every change (POST, PUT, PATCH, DELETE) also needs the X-XSRF-TOKEN header to match the XSRF-TOKEN cookie. Kreftjs.api does this for you.
  • A script or an app that sends device_name when it logs in gets an API token (Authorization: Bearer 5|…) instead.
  • Passwords are hashed with scrypt. Reset links expire after 60 minutes and sign the user out everywhere.
  • Session ids change on every login, so a session cannot be planted in a browser beforehand.

On the server:

JS
Route.middleware(['auth', 'verified']).group(() => {
  Route.get('/orders', [OrderController, 'index'])               // req.user is the user
})

Route.delete('/account', …).middleware(['auth', 'password.confirm'])   // asks for the password again (423)

Helpers you can use anywhere in the backend:

JS
const { Hash, Str, Url, Mail, Crypt } = require('kreftjs/server')

Hash.make('secret')                      // store this, never the password
Hash.check('secret', user.password)      // true or false
Str.random(40)                           // a random token
Url.signed('/verify-email/5/abc', 60)    // a link that works for 60 minutes, unchanged
await Mail.send({ to, subject, text })   // printed in the terminal until MAIL_URL is set

#Protections in the sign-in routes

  • Visitors get throttle:6,1: six tries a minute per address.
  • Each account also locks after LOGIN_MAX_FAILURES (10) wrong passwords in LOGIN_WINDOW_SECONDS (15 minutes), whatever address the tries come from. After that, even the right password gets 429 until the window ends.
  • Two-factor codes are counted per account too: TWO_FACTOR_MAX_FAILURES (8) wrong codes lock it, and starting a new login does not reset the count.
  • "Forgot your password?" answers the same whether or not the address has an account.
  • Changing the email address needs a password confirmation from the last 3 hours (answer 423), because the address is what password reset trusts.

#Two-factor, devices and API tokens

  • Two-factor: authenticator-app codes (TOTP) plus recovery codes. Each recovery code works once.
  • Devices: /profile lists the signed-in browsers, and any of them can be logged out.
  • API tokens: create them in /profile with the permissions read, create, update, delete. A token can only use the HTTP methods its permissions allow, on every route (GET needs read, POST needs create, PUT/PATCH need update, DELETE needs delete). Only browser sessions and * tokens can manage tokens, the password and the account.

#Admin users

An admin is a user whose is_admin column is true. The test user is one; give the rights to others on the Users page, or with kreft make:admin you@example.com. Use Route.middleware(['auth', 'admin']) for admin-only routes.

#Middleware

Middleware runs before the controller and can stop the request or change the answer:

JS
// app/Http/Middleware/EnsureIsAdmin.js     ('ensure-is-admin' in a route, or 'ensure-is-admin:editor')
const { abort } = require('kreftjs/server')

class EnsureIsAdmin {
  async handle(req, next, role = 'admin') {
    if (!req.user || req.user.role !== role) abort(403)
    const response = await next(req)               // the controller runs here
    return response.header('X-Checked', 'yes')
  }
}

module.exports = EnsureIsAdmin

A name in a route finds its file in app/Http/Middleware: 'auth' is Authenticate.js, 'ensure-is-admin' is EnsureIsAdmin.js.

#Built in

MiddlewareWhat it does
throttle:60,1Rate limiting: 60 requests a minute per visitor and route, then 429.
csrfChecks the CSRF token on POST, PUT, PATCH and DELETE (419 when wrong).
can:ability,modelPolicy checks through Gate.authorize().
auth, guest, verified, password.confirmThe sign-in set from app/Http/Middleware.

For every route, list middleware in app/Http/Kernel.js:

JS
module.exports = {
  middleware: ['throttle:120,1'],
}

Exempt a route with .withoutMiddleware('csrf'), or new VerifyCsrfToken({ except: ['webhooks/*'] }).

#Queues, mail, cache and files

Each tool has its own folder in backend/app/ and a kreftjs make: command:

JS
await dispatch(new SendWelcome(user))                   // app/Jobs: runs in the background (tries, backoff, failed())
await event(new OrderShipped(order))                    // app/Listeners
await Mail.to(user).send(new WelcomeMail(user))         // app/Mail: subject, text, html or markdown({ … })
await user.notify(new InvoicePaid(invoice))             // app/Notifications: 'mail', 'database' and 'broadcast' channels
await Cache.remember('stats', 600, () => loadStats())   // database, file, memory or redis (CACHE_STORE)
const path = await req.file('avatar').store('avatars')  // uploads; Storage.url(path) is /storage/avatars/…

#Jobs

Job.dispatch(...) returns an object you can chain (delay(seconds), onQueue(name), chain([...])) and then await:

JS
await SendWelcome.dispatch(user)
await SendWelcome.dispatch(user).delay(60).onQueue('mail')
await SendWelcome.dispatchIf(user.wantsMail, user)

A job class says how it should be run. Everything is optional:

JS
// backend/app/Jobs/ImportCsv.js   (kreft make:job ImportCsv)
const { Job, RateLimited, WithoutOverlapping } = require('kreftjs/server')

class ImportCsv extends Job {
  static tries = 5                 // tries in all (0 = no limit; then give retryUntil())
  static backoff = 'exponential'   // or 10, or [10, 60, 300]: seconds before the next try
  static timeout = 120             // seconds one try may take
  static maxExceptions = 3         // errors allowed (a release() is not an error)
  static queue = 'imports'         // a named queue
  static unique = true             // not queued again while one with the same uniqueId() waits

  constructor(file) { super(); this.file = file }
  uniqueId() { return this.file.id }
  retryUntil() { return new Date(Date.now() + 3600_000) }
  middleware() {
    return [new RateLimited('imports', { max: 30, per: 60 }), new WithoutOverlapping(`file:${this.file.id}`)]
  }

  async handle() {
    if (this.attempts() > 1) Log.info('trying again')
    if (await busy()) return this.release(30)    // back on the queue in 30 seconds
    if (broken(this.file)) return this.fail('The file is not a CSV.')   // no more tries
  }
  failed(error) { /* after the last try */ }
}

Job middleware: RateLimited(key, { max, per }) lets at most max jobs with that key run every per seconds (the others wait for the next window); WithoutOverlapping(key) never runs two with the same key at once; ThrottlesExceptions(10, 600) makes a job wait 10 minutes after 10 errors in a row; Skip.when(fn) removes it without running. A plain function (job, next) => … is middleware too.

#Chains and batches

JS
const { Bus } = require('kreftjs/server')

// one after the other; when one fails, the rest is dropped and the catch job runs (with this.chainError)
await Bus.chain([new FetchFeed(url), new ParseFeed(url), new NotifyFollowers(url)]).catch(new FeedBroke(url)).dispatch()

// in parallel, with progress and callbacks
const batch = await Bus.batch(rows.map((r) => new ImportRow(r)))
  .name('import users')
  .then(new ImportDone(admin))       // every job succeeded
  .catch(new ImportFailed(admin))    // the first failure (this.failedJobId)
  .finally(new CleanUp())            // all done, either way
  .allowFailures()                   // keep going after a failure (otherwise the batch is cancelled)
  .dispatch()

const b = await Bus.findBatch(batch.id)
b.progress()   // 0–100      b.processedJobs()   b.failedJobs   b.finished()   await b.cancel()   await b.add([more])

Inside a batched job, await this.batch() is its batch. Callbacks are jobs, never functions: a function cannot be stored and run by another process. Batches are kept in the job_batches table (new apps have it; older ones: kreft queue:batches-table, then kreft migrate).

#Workers

Queued jobs, listeners, mail, notifications and broadcasts run in the background. kreft dev and kreft serve work through the high, default and low queues every second (QUEUE_NAMES, or QUEUE_WORKER=off when a separate worker does it). Choose the driver with QUEUE_CONNECTION: database (the jobs table), redis, memory (this process only, for tests) or sync (at once).

BASH
kreft queue:work --queue=high,default      # takes queues in this order; Ctrl+C or SIGTERM finishes the current job first
kreft queue:work --max-jobs=500 --max-time=3600 --memory=256 --sleep=3   # stop after a while (a process manager starts it again)
kreft queue:restart                        # every worker stops after its current job (after a deploy)
kreft queue:failed                         # kreft queue:retry <id|all>, queue:forget <id>, queue:flush, queue:prune-failed --hours=48
kreft queue:monitor high,default --max=100 # how many wait; exit code 1 above --max (for an alert)
kreft queue:batches                        # kreft queue:retry-batch <id>, queue:prune-batches --hours=24

A job whose worker died while it ran is taken again after QUEUE_RETRY_AFTER seconds (90 by default; keep it above your longest timeout). With Redis, waiting, delayed and reserved jobs are kept apart, so a crash never loses one.

Hooks for logs and metrics: Queue.before(fn), Queue.after(fn), Queue.failing(fn), or Queue.on('retrying' | 'released' | 'queued', fn).

#Testing jobs and events

JS
Queue.fake()
await placeOrder()
Queue.assertPushed(SendInvoice, (job) => job.order.id === 1)
Queue.assertPushedOn('high', ChargeCard)
Bus.assertChained([FetchFeed, ParseFeed])
Bus.assertBatched((b) => b.jobs.length === 3)
Queue.restore()

Event.fake()                          // or Event.fake([OrderShipped]): only those
await shipOrder()
Event.assertDispatched(OrderShipped, (e) => e.order.id === 1)
Event.restore()

#Events and listeners

Listeners in app/Listeners find their event themselves (static event = 'OrderShipped'). A listener with static queue = true (or a queue name) runs on the queue, retries like a job (tries, backoff, timeout), can say shouldQueue(event) and gets failed(event, error). A class with subscribe(events) in app/Listeners is a subscriber. Event.listen('user.*', fn) listens to every event whose name starts with user.; Event.once, Event.until (the first answer) and Event.off are there too.

#Uploads

req.file('avatar').store('avatars') saves with a random name and never trusts the original one. Only known plain-data extensions (images, PDF, text, office files, audio, video, archives) keep their extension; anything else is stored as .bin. Use file.isImage() to also check the file's real header, not only its name.

Files on the public disk are served from /storage/… as downloads of plain data, so an uploaded .html or .svg can never run scripts on your site.

#Scheduling

JS
// backend/routes/console.js
Schedule.call(async () => { await Post.onlyTrashed().forceDelete() }).daily().name('clean-trash')
Schedule.job(new SendDailyReport()).weekdays().at('08:00')
Schedule.command('send:report Daily').hourly()

kreft dev and kreft serve check the schedule every minute. Set SCHEDULER=off to run it from cron with kreft schedule:run; kreft schedule:list shows what is planned.

#Redis

Kreft includes its own Redis client (RESP2 over TCP or TLS) with no extra package. It works with Redis, Valkey and hosted Redis services.

ENV
CACHE_STORE=redis
QUEUE_CONNECTION=redis
REDIS_URL=rediss://default:secret@host:6379/0      # or REDIS_HOST, REDIS_PORT, REDIS_USERNAME, REDIS_PASSWORD, REDIS_DB
REDIS_PREFIX=kreft_
BASH
kreftjs redis:ping        # PONG (1ms) — 127.0.0.1:6379/0

Redis also gives you atomic locks (Cache.lock('report', 30)) and publish/subscribe.

#Real-time: broadcasting and channels

Send events from the server to the browsers that are open, as they happen. Kreft has its own WebSocket server (no package to install) with Server-Sent Events as fallback, private and presence channels, whispers, and a client in the runtime that reconnects by itself.

JS
// backend/app/Events/OrderShipped.js   (kreft make:event OrderShipped --broadcast)
const { PrivateChannel } = require('kreftjs/server')
class OrderShipped {
  constructor(order) { this.order = order }
  broadcastOn() { return [new PrivateChannel(`orders.${this.order.id}`)] }
  broadcastAs() { return 'order.shipped' }               // optional: the name in the browser (default: the class name)
  broadcastWith() { return { id: this.order.id, at: this.order.shipped_at } }   // optional (default: its public fields)
}

await event(new OrderShipped(order))                     // listeners run, and the browsers on the channel get it
await broadcast(new OrderShipped(order)).toOthers(req)   // everyone except the browser that sent this request
await Broadcast.to('news').emit('headline', { title })   // without an event class
JS
// in the browser (any component or page)
Kreftjs.private(`orders.${id}`).listen('order.shipped', (e) => { order.status = 'shipped' })
Kreftjs.channel('news').listen('headline', (e) => headlines.unshift(e))

#Who may listen: routes/channels.js

Public channels are open to anyone. A channel whose name starts with private- or presence- needs permission, decided in backend/routes/channels.js:

JS
const { Broadcast } = require('kreftjs/server')

Broadcast.channel('orders.{id}', async (user, id) => (await Order.find(id))?.user_id === user.id)
Broadcast.channel('App.Models.User.{id}', (user, id) => String(user.id) === id)
Broadcast.channel('chat.{room}', (user, room) => ({ id: user.id, name: user.name }))   // presence: what the others see
Broadcast.channel('projects.{id}', require('../app/Broadcasting/ProjectChannel'))       // a class with join(user, id)

Before joining, the browser asks POST /api/broadcasting/auth. That route goes through your auth middleware (the session cookie with its XSRF header, or an API token) and then the callback. The answer is a token made with APP_KEY for that one socket and that one channel, so it can't be reused on another connection or for another channel, and member data can't be changed after it was signed. Change the middleware in app/Http/Kernel.js (broadcasting: { middleware: ['auth'] }). kreft channel:list lists the channels; kreft make:channel Project makes a channel class.

#Presence channels and whispers

JS
const room = Kreftjs.presence('chat.lobby')
  .here((members) => { online = members })          // everyone here when you join
  .joining((member) => online.push(member))
  .leaving((member) => online = online.filter((m) => m.id !== member.id))
room.members.value                                  // reactive list of who is here

room.whisper('typing', { name: me.name })           // to the others, without going through your code
room.listenForWhisper('typing', (e) => typing = e.name)
Kreftjs.leaveChannel('chat.lobby')

A user with several tabs counts once. On the server, await Broadcast.members('presence-chat.lobby') lists who is there.

#Notifications in the browser

Add 'broadcast' to via(); the browser gets toBroadcast(user) (or toArray) on the user's private channel:

JS
class InvoicePaid extends Notification {
  via() { return ['database', 'broadcast'] }
  toBroadcast(user) { return { amount: this.invoice.amount } }
}
Kreftjs.private(`App.Models.User.${me.id}`).notification((n) => toast(n.type + ': ' + n.amount))

#The client

The connection opens on the first channel. It reconnects by itself (backoff with jitter, and as soon as the network is back), joins every channel again with fresh tokens, checks with a ping that the connection is alive, and falls back to Server-Sent Events when a WebSocket can't get through. Kreftjs.api sends X-Socket-ID, so toOthers(req) works with no extra code. Inside a component, listen() stops when the component goes away.

JS
Kreftjs.echo.state.value                       // 'connecting' | 'connected' | 'reconnecting' | 'offline'
Kreftjs.echo.setup({ path: '/broadcasting', authEndpoint: '/api/broadcasting/auth', transports: ['websocket', 'sse'] })
const other = Kreftjs.realtime({ host: 'realtime.example.com' })   // a second connection with its own settings

#Several processes or servers

BROADCAST_CONNECTION=memory (the default) is right for one server process. With several processes (a queue worker, a cluster, several servers behind a load balancer), set BROADCAST_CONNECTION=redis: every process sends and receives through Redis pub/sub, and presence members are kept in Redis, so a broadcast from kreft queue:work reaches browsers connected to the web server. A process that stops is dropped from the member lists within 30 seconds. log writes broadcasts to the log, and null drops them.

#Limits and security

Setting (.env)DefaultWhat
BROADCAST_PATH/broadcasting<path>/ws (WebSocket), <path>/sse (fallback)
BROADCAST_MAX_MESSAGE_KB16one message from a browser
BROADCAST_MAX_PAYLOAD_KB256one event from the server
BROADCAST_MAX_CONNECTIONS10000open sockets in one process
BROADCAST_MAX_CONNECTIONS_PER_IP100open sockets from one address
BROADCAST_MAX_CHANNELS100channels one socket may join
BROADCAST_MAX_MESSAGES / BROADCAST_RATE_WINDOW_SEC100 / 10messages a socket may send in that window (then it is closed)
BROADCAST_MAX_FRAMES1000frames of any kind (pings, fragments) a socket may send in that window
BROADCAST_MAX_FRAGMENTS128frames one message may be split into
BROADCAST_MAX_BUFFER_KB1024unsent data (messages, pongs) before a socket that does not read is dropped
BROADCAST_ALLOWED_ORIGINSother sites allowed to connect (https://app.example.com)

Every private and presence subscription is checked on the server. A browser from another site can't connect (its Origin must be this site, APP_URL, KREFT_ALLOWED_ORIGINS or BROADCAST_ALLOWED_ORIGINS), and kreft dev refuses other host names (DNS rebinding). Frames must be masked and text must be UTF-8. Compression is not offered (no compression bombs), and a socket that reads too slowly is dropped instead of filling memory. Banned addresses (SHIELD=true) can't open one. The SSE fallback only accepts application/json messages to a secret socket id, so a form on another site can't send one.

Tests: Broadcast.fake(), then Broadcast.assertBroadcast(OrderShipped), Broadcast.assertBroadcastOn('private-orders.1'), Broadcast.assertNothingBroadcast().

On your own Node server: require('kreftjs/server').Realtime.attach(httpServer), and send Realtime.handleHttp(req, res, path) the requests of the SSE fallback.

#Configuration

Settings come from .env, backend/config/*.js and defaults, through one helper:

JS
const { config } = require('kreftjs/server')

config('app.name', 'My app')
config('database.default', 'sqlite')
config.has('redis.connections.default')
config.set('app.debug', false)

Files in backend/config/: app.js, auth.js, database.js, redis.js, session.js. See Environment variables for what .env controls.

#Sessions and inactivity

Two layers log out a user who walks away:

ENV
SESSION_LIFETIME=120            # minutes of inactivity before the server drops the session
PUBLIC_SESSION_TIMEOUT=15       # minutes before the page itself sends the user to /login
PUBLIC_SESSION_WARNING=2        # minutes of warning before that
AUTH_TOKEN_DAYS=30              # a token unused for this many days stops working

PUBLIC_ values are copied into the browser (Kreftjs.env); never put secrets in them.

#Behind a proxy

The visitor's address comes from the connection. Behind nginx, Cloudflare or a load balancer, list your proxies:

ENV
TRUSTED_PROXIES=10.0.0.1          # or *
TRUSTED_PROXY_HOPS=1              # with *: how many proxies stand in front

X-Forwarded-For is read from the right, so the visitor cannot choose their own address.

#Testing

Backend code is tested with Node's own test runner and an in-memory SQLite database, so tests are fast and never touch your real data.

JSON
{
  "scripts": { "test": "node --test \"tests/**/*.test.js\"" }
}
JS
// tests/models/post.test.js
const test = require('node:test')
const assert = require('node:assert/strict')
const { createSchema, setConnection } = require('kreftjs/server')
const { connect } = require('kreft/bin/db.js')
const Post = require('../../backend/app/Models/Post')

test.before(async () => {
  const db = await connect('sqlite::memory:')       // a new empty database for this test file
  setConnection(db)
  await createSchema(db).create('posts', (table) => {
    table.id()
    table.string('title')
    table.timestamps()
  })
})

test('a post can be created and found', async () => {
  const post = await Post.create({ title: 'Hello' })
  assert.equal((await Post.find(post.id)).title, 'Hello')
})

To test a whole project's tables, run its real migrations instead of building the schema by hand: migrator.migrate(db, 'backend/database/migrations').

Component pages for the browser live in frontend/tests/ and are opened with kreft dev.

#Tooling

#Command line

Run kreft list to see every command your installed version has, and kreft help for the options of the main ones.

#The main commands

CommandWhat it does
kreft new my-appMakes a project (--js, --ts, --db sqlite, --ui tailwind, --no-auth, --mobile for iOS and Android, --electron or --tauri for a desktop app, --harmony for HarmonyOS, --vite, --redis).
kreft devDevelopment server with hot reload (--port, --host, --db, --api, --server, --backend, --seed, --no-hot, --gc).
kreft buildCompiles the app into plain files in dist/ (--out, --base, --prerender).
kreft serve [dist]Runs a built app for real users. Answers everyone, serves only the tables you list.
kreft updateUpdates npm packages and refreshes kreftjs.js (--core, --npm, --latest, --check).
kreft add <package>A safer npm install. See Packages.
kreft about, kreft env, kreft log, kreft tinkerVersions and folders, environment, logs, a console with your models (await User.count()).
kreft down --secret=x / kreft upMaintenance mode: visitors get 503, and /x lets you in.
kreft vscodeInstalls colors, snippets, folding and Emmet for .kreft files in VS Code, Antigravity, Cursor, Windsurf and VSCodium.
kreft editor <name>The same for sublime, zed, jetbrains (WebStorm, PhpStorm, IDEA...) and vim (Vim, Neovim).
kreft editor <name> --download [folder]Writes the plugin as one file instead of installing it: Editor plugins.
kreft electron:dev, kreft electron:buildA desktop window, and installers: Desktop apps.
kreft tauri:dev, kreft tauri:buildThe same with Tauri: Desktop apps with Tauri.
kreft harmony:build, kreft harmony:openA HarmonyOS project and DevEco Studio: HarmonyOS apps.
kreft mobile:init, mobile:build, mobile:open, mobile:deviOS and Android apps with Capacitor: Mobile apps.
kreft mobile:ui, mobile:icons, mobile:splashThe phone UI kit, the app icon and the splash screen: The phone UI kit.
kreft make:home --mobile / --desktopAn app-style home page: Home pages made for apps.
kreft build --pwaAlso writes a manifest and a service worker (an installable site that works offline).
kreft build --no-splitKeeps every page in app.js. Without it, each page of pages/ is its own file (pages/Users.js?v=…), loaded the first time it is visited, and app.js keeps only the shell, layouts and shared components (about half the size in a new app). Pages drawn on the server load their file the same way.
kreft build --no-deployWrites dist/ only. Without it, a project with a backend also gets deploy/: the whole app ready to upload (Deploying the backend).
kreft build --with-docsKeeps docs/, the Kreft manual that kreft new puts in an app. Without it the build leaves the manual out (it is for development; kreft dev serves it at /docs) and the built app has no /docs route.

#Generators and database

GroupCommands
make:model, controller, page, routes, migration, seeder, factory, middleware, request, resource, policy, rule, job, event, listener, mail, notification, observer, command, lang, errors, admin, electron, tauri, harmony, mobile, home, vite
migratemigrate, :rollback, :fresh, :refresh, :reset, :status, :file, :undo
db:db:seed, db:wipe
queue:work, start, stop, pause, resume, restart, status, failed, retry, flush, clear, table
schedule:run, work, list
Othersroute:list, cache:clear, storage:link, key:generate, event:list, log:clear

kreft dev --seed seeds a brand-new database the first time. kreft key:generate writes a 256-bit APP_KEY into .env (--show prints it instead).

#Development server safety

  • kreft dev answers only this computer (127.0.0.1) and only requests whose Host is a local name (localhost, 127.0.0.1, ::1, *.localhost). This stops DNS-rebinding attacks, where a web page tries to reach your dev server through its own domain name.
  • To reach it through a tunnel or another name, set KREFT_ALLOWED_HOSTS=my-tunnel.example. To share it on your network, use --host 0.0.0.0.
  • Requests that change data in --api or --db mode are refused when they come from another web site (a browser Origin that is not local).
  • Moving or deleting the project folder. The operating system cannot refuse a delete, so the server says so after it happens: if the project folder is deleted or moved to the Trash while kreft dev or kreft serve runs, it stops at once with a message. Any kreftjs command started from a deleted folder or one in the Trash refuses to run. Stop the server with Ctrl+C before you move or delete a project.

#Developer tools

Everything here comes with Kreft. Nothing else to install.

Hot reload. While kreft dev runs, save a .kreft file and only that component is swapped; its state stays. A .css file is reloaded without a page refresh, and an error shows an overlay with the file and line.

Kreft DevTools. The S button in the corner (or Alt+Shift+D) opens a panel. In the phone app the button is hidden so it never covers the bottom bar; to show it there run localStorage.setItem('kreft:devtools-button', 'on') in the app's console:

TabShows
ComponentsThe live tree. Pick one to see props, state and derived values, and change state right there.
StoresEvery store's values, which you can change, and $reset().
RouteThe current route and every route, with a button to go there.
TimelineStore actions and bus messages as they happen.

The button and the panel only exist under kreft dev; built apps never include them.

Types. kreftjs.d.ts describes everything in Kreft, so TypeScript and your editor know it. kreft new copies it into new projects, and kreft update --core refreshes it.

#Error monitor

In development, an uncaught error on the server shows an interactive page instead of a bare message:

  • A stack explorer that hides vendor frames and highlights yours.
  • A source preview around the failing line.
  • A suggestion engine for common mistakes (a method typo on a model, reading a property of undefined, a missing table that needs kreft migrate).
  • The request: method, URL, route and query values, body, headers and client address. Passwords, tokens, cookies and CSRF values are masked.
  • Copy the error as Markdown for an issue, or as JSON.

The page is only shown when APP_ENV is not production and APP_DEBUG is true. In production the same error answers a plain Server error. with no stack or file names.

Frontend errors use the same design through errors/ErrorMonitor.kreft; pass it a caught exception:

HTML
import ErrorMonitor from 'errors/ErrorMonitor.kreft'
state caught = null

<view>
  <error-monitor k-if="caught" error={caught} status={500} title={caught.name} message={caught.message}></error-monitor>
</view>

#Editor plugins

Kreft has a plugin for each editor (this page online: kreftjs.com/docs). Every one gives .kreft files colors, snippets and Emmet: type ul>li.item*3 in <view>, or m10, df, bgc in <style>, and expand it.

EditorInstallDownload as a fileSource
VS Code, Antigravity, Cursor, Windsurf, VSCodiumkreft editor vscodekreft-vscode-<version>.vsixeditors/vscode
Sublime Textkreft editor sublimeKreft.sublime-packageeditors/sublime
Zedkreft editor zedkreft-zed-<version>.zipeditors/zed
WebStorm, PhpStorm, IntelliJ IDEA, PyCharm, Android Studiokreft editor jetbrainskreft-jetbrains-<version>.jareditors/jetbrains
Vim, Neovimkreft editor vimkreft-vim.zipeditors/vim

kreft editor all installs every one. kreft editor alone prints the list.

#Download a plugin

Add --download and the plugin is not installed: it is written as one file, in the form the editor installs by itself. Use it to share the plugin with your team, to keep it, or to set up a computer that has no Kreft.

BASH
kreft editor vscode --download            # kreft-vscode-<version>.vsix in this folder
kreft editor jetbrains --download ~/Downloads
kreft editor all --download plugins       # the five files in ./plugins

Without a Kreft project, npx does the same:

BASH
npx kreftjs@beta editor sublime --download

The command prints the file and how to install it. The same steps are below.

#VS Code, Antigravity, Cursor, Windsurf

BASH
kreft editor vscode

It installs the extension in every one of these editors it finds, and sets the project's .vscode/settings.json. Restart the editor. (kreft vscode is the same command.)

From a file: kreft editor vscode --download, then in the editor open Extensions > the ... menu > Install from VSIX... and pick kreft-vscode-<version>.vsix. Or from a terminal:

BASH
code --install-extension kreft-vscode-2.4.0.vsix

You get: colors for <view>, <style> and <script>, Format Document, snippets (kreftjs, state, action, for, kreft-wait...), folding, and Emmet. If you have your own emmet.includeLanguages setting, the extension asks once and adds "kreftjs": "html" to it. To expand with Tab, set "emmet.triggerExpansionOnTab": true.

#Sublime Text

BASH
kreft editor sublime

It copies the package to Packages/Kreft. Reopen your .kreft files.

From a file: kreft editor sublime --download, then Preferences > Browse Packages..., go one folder up, and put Kreft.sublime-package in Installed Packages. Do not rename the file: its name is the package's name.

For Emmet, install the Emmet package: Command Palette > Package Control: Install Package > Emmet. It needs no setting.

#Zed

BASH
kreft editor zed

It puts the extension in ~/.kreft/editors/zed. In Zed, open the command palette, run zed: install dev extension and pick that folder. Zed compiles the extension, so Rust must be installed.

From a file: kreft editor zed --download, unzip it, and pick the kreft-zed folder in the same command.

Emmet needs no other extension and no setting: the Kreft extension starts the Emmet language server itself (Zed downloads it the first time). To turn it off:

JSON
"languages": { "Kreft": { "language_servers": ["!kreft-emmet"] } }

#JetBrains IDEs

For WebStorm, PhpStorm, IntelliJ IDEA, PyCharm, RubyMine, GoLand, Rider and Android Studio, 2022.3 or newer.

BASH
kreft editor jetbrains

It builds the plugin and puts it in every JetBrains IDE it finds. Restart the IDE.

From a file: kreft editor jetbrains --download, then Settings > Plugins > the gear > Install Plugin from Disk... and pick kreft-jetbrains-<version>.jar.

A .kreft file opens as HTML, so the markup, the CSS in <style> and the JavaScript in <script> are colored and completed, and Emmet expands with Tab. The snippets are live templates: Settings > Editor > Live Templates > Kreft. Emmet for CSS needs an IDE with web support (WebStorm, PhpStorm, IDEA Ultimate, PyCharm Professional); Kreft-only syntax such as state x = 0 is shown as plain text.

#Vim and Neovim

BASH
kreft editor vim

It copies the plugin to pack/kreft/start/kreft in your Vim and Neovim folders.

From a file: kreft editor vim --download, then unzip kreft-vim.zip into ~/.vim/pack/kreft/start/ (Neovim: ~/.config/nvim/pack/kreft/start/).

For Emmet, install emmet-vim and press Ctrl+y then , after an abbreviation. In Neovim (0.11 or newer) you can use the Emmet language server instead (npm i -g @olrtg/emmet-language-server):

LUA
vim.lsp.config('emmet_language_server', {
  cmd = { 'emmet-language-server', '--stdio' },
  filetypes = { 'html', 'css', 'kreft' },
  init_options = { includeLanguages = { kreft = 'html' } },
})
vim.lsp.enable('emmet_language_server')

#Another editor

An editor that takes TextMate grammars can use editors/vscode/syntaxes/kreftjs.tmLanguage.json. For Emmet, tell the editor to treat .kreft files as HTML: that is all the plugins above do.

#Build and deploy

kreft build compiles your app ahead of time:

BASH
npm run build      # or: kreft build
npm run preview    # check the result: kreft dev dist
FileWhat it is
index.htmlYour page, now loading the files below.
kreftjs.jsThe framework.
app.jsEvery .kreft file, already compiled.
app.cssAll <style> blocks; scoped ones already scoped.
main.jsThe inline <script> code from index.html.
deps/, vendor/The npm packages and CSS your .kreft files import, minified.

What you get:

  • A faster first load. The browser downloads one app.js and compiles nothing.
  • A strict Content-Security-Policy works. Every expression becomes a real function, so the built app never uses eval or new Function.
  • Errors before you deploy. A mistake in any .kreft file stops the build and names the file and line.

Options: kreft build ./site --out public builds another folder, and --base / changes <base href>. --no-htaccess skips the .htaccess file described below. If esbuild is installed (kreft add -D esbuild), kreftjs.js is minified in the output (about 44 kB gzipped instead of 69 kB); --no-minify copies it as it is.

#Upload to a host

Static hosting: Hostinger, cPanel, any Apache host. Upload what is inside dist/ (not the dist folder itself) to the folder the website is served from, normally public_html. In Hostinger's hPanel: Files → File Manager → public_html → Upload, or use FTP. Do not use the "framework" or "Node.js app" importers for this: they look for a package.json and say Unsupported framework or invalid project structure, because dist/ holds only finished files.

kreft build also writes dist/.htaccess:

APACHE
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}/index.html !-f
RewriteCond %{REQUEST_URI} !^/api/
RewriteCond %{REQUEST_URI} !\.[A-Za-z0-9]+$
RewriteRule . /index.html [L]

Apache only knows the files on disk, so without these rules /docs or any other clean address gives a 404 when someone opens or reloads it. With them, every page address (no file extension, not under /api/) that is not a real file, or a folder with its own index.html, opens index.html and the router takes over. A missing file such as app.js, or an /api/ address, stays a plain 404, so code that asks for data never receives the page's HTML. Upload the file too (it starts with a dot, so some file managers hide it; turn on "show hidden files"). If the site lives in a folder, build with --base /folder/ and the rules follow it. An .htaccess you keep in public/ is used as it is. kreft build also puts a short hash into the address of each script and style sheet (app.js?v=28a965f6), and the .htaccess tells the host never to keep index.html. Hosts cache .js and .css for days, so without the hash visitors would keep running the old runtime and old pages after you upload a new build. A relative base (--base ./, used by the desktop build) gets no file.

A Node.js plan or a VPS. Upload the whole project (without node_modules), not dist/. Add Kreft to its dependencies with npm install kreftjs@latest, build with npm run build, and start the server with npm run serve (it reads the PORT your host sets). The generated start script runs the development server, so do not use it in production.

On a VPS, keep it running with PM2 and put nginx in front of it for your domain and HTTPS:

BASH
npm install && npm run build
npm i -g pm2
pm2 start "npm run serve" --name my-app && pm2 save
NGINX
server {
    server_name example.com;
    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Then sudo certbot --nginx -d example.com adds HTTPS. Set APP_ENV=production and a real APP_KEY in .env first, and read the Production checklist.

#Publish the website (kreftjs.com)

The Kreft website is the demo/ app plus the docs/ manual. Three commands make it, and a fourth puts it online:

BASH
npm install kreftjs@latest     # in a project that uses Kreft; in this repository, plain: npm install
npm run build                  # writes the finished site to dist/kreftjs-com

Then upload what is inside dist/kreftjs-com (not the folder itself, and including the hidden .htaccess) to the folder kreftjs.com is served from, normally public_html (see Upload to a host). Open https://kreftjs.com and reload a page such as /docs to check that the clean addresses work.

npm run build runs kreft build demo --out dist/kreftjs-com --base / --include docs. --base / makes every path start at the site's root, and --include docs copies the manual in. To look at the result before you upload it, run npm run preview.

Releasing a new version of the package. This is done by the maintainer, before the site is built, so the site and the package agree:

BASH
npm test                       # the regression tests must pass
npm version 0.0.48-beta --no-git-tag-version --ignore-scripts  # choose a fresh version for the next release
npm pack --dry-run             # review the package contents
npm publish --tag beta --access public  # runs tests first; needs npm authentication
npm run build                  # then upload dist/kreftjs-com as above

Check that people get it with npm view kreftjs version and a fresh npm install -g kreftjs@latest.

Trying a version before everyone gets it. Publish it under another tag. latest and beta stay on the old version, so nobody gets it by accident:

BASH
npm publish --tag mobile-test --access public     # npm asks you to approve in the browser
npm install -g kreftjs@mobile-test                  # you, on any computer
kreft --version                                     # shows the new number
npm dist-tag add kreftjs@0.0.48-beta beta           # when it is good: the tag everyone uses moves

package.json sets public access, the official npm registry and the beta tag for prereleases. Use npm run publish:beta (or explicitly pass --tag beta) to publish a prerelease; moving latest is a separate maintainer decision. Unscoped packages such as kreftjs are public. Organization packages require an explicitly chosen name such as @your-org/kreftjs and access to that organization. A version number can be published only once, so the next try is the next number. To test the folder you are in without publishing anything, run npm link (undo with npm unlink -g kreftjs). kreft --version after npm install -g reads the globally installed package, not the repository.

#Ready HTML for every page: --prerender

BASH
npm i -D jsdom                              # once per project
kreft build --prerender                       # every route without :params
kreft build --prerender /users/1,/users/2     # and these addresses too

Each page is opened in a simulated browser, its data loaded, and the result saved as dist/<page>/index.html, so visitors and search engines get finished HTML.

The tags a page sets with .seo({...}) or meta (description, canonical, Open Graph, Twitter, hreflang, JSON-LD, lang and dir) are saved in the page's HTML too, so link previews and crawlers that don't run JavaScript see them. A canonical written in index.html is kept for the home page only. A page where the app shows its error page is skipped.

Pages that come from your data (/posts/:slug) need their addresses: kreft build --prerender --urls urls.js. The file is urls.json (a list), urls.txt (one address per line), or urls.js (a list, or an async function that returns it).

#SEO for pages from your database: backend/routes/seo.js

A page whose content comes from a table can't be known at build time. List what the server should put in <head> for an address:

JS
// backend/routes/seo.js
const Post = require('../app/Models/Post')

module.exports = {
  '/': { title: 'My shop', description: 'Everything for the home' },
  '/posts/:slug': async ({ slug }) => {
    const post = await Post.where('slug', slug).first()
    if (!post) return null                  // a real 404, with noindex
    return {
      title: post.title,
      description: post.excerpt,
      og: { image: post.image },
      schema: { '@type': 'Article', headline: post.title },
      alternates: { en: `https://example.com/posts/${slug}`, ar: `https://example.com/ar/posts/${slug}` },
    }
  },
  // the addresses of your data pages, for `kreft sitemap`: '/path' or { path, lastmod }
  urls: async () => (await Post.all()).map((p) => ({ path: '/posts/' + p.slug, lastmod: p.updated_at })),
}

kreft dev and kreft serve answer a page request with index.html plus the tags of the first matching address (:param and a trailing /* work). Set APP_URL and each page also gets its canonical. An address that isn't listed is the normal page. The browser keeps these tags until the first navigation, then the router's own tags take over.

#Pages drawn on the server

Like Next.js and Nuxt, kreft dev and kreft serve can answer every page request with the page already drawn: the visitor sees the content at once, search engines and link previews see it without running JavaScript, and the browser then takes the page over.

BASH
KREFT_SSR=all           # every visitor (new apps: in .env)
KREFT_SSR=bots          # crawlers and link previews only (the default for older apps)
KREFT_SSR=off           # never

How it works:

  • No extra package. Kreft draws the page with its own small server DOM, in a fresh sandbox for every page, so nothing (stores, the signed-in user, caches) passes from one visitor to another. KREFT_SSR_ENGINE=jsdom uses jsdom instead (npm i -D jsdom).
  • The data is loaded on the server. Your pages don't change: load posts = api.get('/api/posts') runs on the server while the page is drawn. The answers go into the page (<script type="application/json" id="kreft-data">), and the browser's first api.get of the same address uses them instead of asking again. In the browser the page shows the same thing at once, with no second request.
  • Signed-in visitors get their own page. A visitor is signed in when the request has the session cookie (kreft_session, or SESSION_COOKIE), another login cookie you name in KREFT_SSR_COOKIES (comma-separated), or an Authorization header; any other cookie (analytics, a theme) gets the guest page, so a made-up cookie cannot skip the cache. The visitor's cookie (or API token) goes with the page's requests to your own server, never to another site. New apps' auth store starts from window.__KREFT_SSR_USER__ (the answer of /api/user, or KREFT_SSR_USER_URL), so pages behind .middleware('auth') are drawn with the user's data. Such a page is sent with Cache-Control: private, no-store and is never cached or shared.
  • Guests share a cache, refreshed like Next.js ISR. A page drawn for a visitor who is not signed in is kept for KREFT_SSR_TTL seconds (default 300; kreft dev never keeps them). When it is older, the next visitor still gets it at once while it is drawn again in the background for the visitor after (KREFT_SSR_STALE=off waits for the new drawing instead). The same address asked twice at once is drawn once.
  • Draw a page again on demand. After a change, tell the server which pages are out of date; the next visitor gets them drawn fresh:
    const { revalidatePage } = require('kreftjs/server')
    await post.save()
    revalidatePage('/posts/' + post.slug)   // one page;  revalidatePage('/posts/*') a group;  revalidatePage('*') all

    It acts on the server process it runs in (with several processes, each one's copy expires after KREFT_SSR_TTL).

  • Limits. KREFT_SSR_CONCURRENCY pages are drawn at once (8 with the built-in engine, 2 with jsdom); the others wait up to 15 seconds. A page that takes longer than 15 seconds, fails, or is not a page of the app gets the normal page, and is not tried again for 30 seconds. While drawing, nothing is requested from other sites, WebSockets and timers don't run, and the page sees window.__KREFT_SSR__ = true.
  • If the app shows its errors/404.kreft page, the answer has status 404. A page that kreft build --prerender already drew is sent as it is. Responses carry Vary: User-Agent, Cookie, Authorization and the same security headers as every other page.

In production the built app draws a guest page in about 0.2 seconds the first time and answers from the cache after that; a signed-in page takes about the same, every time.

#Sitemap and robots.txt: kreft sitemap

BASH
kreft sitemap --url https://example.com                  # public/sitemap.xml and public/robots.txt
kreft sitemap --url https://example.com --urls urls.js   # and the addresses in that file

It lists the routes of Kreftjs.router({ routes }) in index.html and routes/web.kreft, skipping redirects and patterns like /posts/:id, plus the urls of backend/routes/seo.js and --urls. A lastmod is written only when you give one (a database date such as 2026-01-02 10:00:00 becomes 2026-01-02). A route can list alternates: { en: '/about', ar: '/ar/about' } for xhtml:link entries.

#Deploying the backend

In a project with a backend, kreft build writes two folders: dist/ (the website, as before) and deploy/, the whole app ready to upload to a Node.js host, in the same folders as your project (like a Laravel app), not packed into one file:

CODE
deploy/
├── public/          the built website (the only folder a browser can reach; it has .htaccess for Apache)
├── backend/         app/, routes/, config/, database/migrations and seeders, lang/ … as they are in your project
│   └── storage/     empty folders: logs, cache, framework, app/public
├── lang/            when the project has it
├── server.js        the start file hosts find by themselves: the same as kreft serve public, from any folder
├── package.json     main + npm start = server.js · npm run migrate · your packages + kreftjs + the database driver
├── .env.example     the settings to fill in
├── .htaccess        a guard for the wrong upload (the whole folder in public_html)
├── Dockerfile  .dockerignore  ecosystem.config.cjs (pm2)
└── README.md        the steps for each kind of host

Upload deploy/ and, on the server:

BASH
npm install --omit=dev        # kreftjs, your packages and the database driver
cp .env.example .env          # fill it in: APP_KEY (npx kreft key:generate --show), APP_URL, DATABASE_URL, MAIL_URL …
npm run migrate               # creates or updates the tables (or KREFT_MIGRATE_ON_START=true)
npm start                     # node server.js (PORT and HOST from the host or .env, default 8000)

What never goes into deploy/: your .env (its .env.example is your project's own, or one made from .env with the secret values left empty), node_modules, the SQLite database of your computer, the contents of storage/ (logs, uploads, cache), hidden files, keys and certificates. Uploads live in backend/storage/app on the server, so keep that folder when you upload a new build. kreft build only deletes a deploy/ folder it made itself (it carries a .kreft-deploy file); kreft build --no-deploy writes dist/ only.

The start file. server.js goes to its own folder, then runs kreft serve public with the kreftjs package installed next to it. So it works as the "Application startup file" of cPanel's Setup Node.js App (Passenger, also on GoDaddy and Namecheap), as the entry file of a Hostinger Node.js app, under pm2, in Docker, or as node server.js, whatever folder the host starts it from. A project with "type": "module" gets the same file as an ES module.

Settings are checked before the server starts. kreft serve (and so server.js) lists every missing or wrong setting in one message and exits with code 1, instead of crashing later or restarting over and over:

Stops the serverOnly a warning
no APP_KEY, or one shorter than 16 bytesan APP_KEY of 16–31 bytes (32 is best)
no APP_URL, or one that is not a web addressAPP_URL on localhost, or http:// instead of https://
no DATABASE_URL while backend/database/migrations has filesAPP_DEBUG=true, APP_ENV other than production
a MySQL / PostgreSQL DATABASE_URL whose driver is not installed (npm install mysql2 / npm install pg)redis chosen without REDIS_URL / REDIS_HOST
Node.js older than 22.5; backend/storage or the SQLite folder not writable

The message names the settings, never their values, and is also written to backend/storage/logs/startup.log (for hosts that hide the output). KREFT_ENV_CHECK=off skips the check.

Check before you upload. kreft deploy:check (in the project, or kreft deploy:check deploy, or npx kreft deploy:check in the uploaded folder) prints what the server will need (the settings, the database driver, Node.js 22.5+, write access to backend/storage) and the same problems, without starting anything. --json gives the result as JSON.

Migrations at start. KREFT_MIGRATE_ON_START=true runs new migrations every time the server starts, logging each one. Turn it on for one process only (not for every pm2 or container copy).

Health check. GET /up answers {"status":"ok","version":"1.2.3","database":"ok"} (the version of your app's package.json), or 503 with "database":"error" when the database does not answer within 3 seconds. Nothing secret is in it, and it answers over plain HTTP too, so a load balancer or Docker can ask it. HEALTH_PATH=/healthz moves it, HEALTH_PATH=off turns it off.

Where to upload it. On a Node.js host (cPanel Setup Node.js App, GoDaddy, Hostinger), put deploy/ in its own folder outside public_html, choose Node.js 22 or newer and startup file server.js, paste the settings (GoDaddy takes one NAME=value per line, no quotes), and press Run NPM Install. On a VPS, pm2 start ecosystem.config.cjs runs three processes: the website (with QUEUE_WORKER=off and SCHEDULER=off), kreft queue:work and kreft schedule:work. With Docker: docker build -t my-app deploy && docker run --env-file .env -p 8000:8000 my-app (mount volumes on /app/backend/storage and, for SQLite, /app/backend/database). deploy/README.md has the steps for each.

Queues and the schedule: run npm run queue:work and npm run schedule:work as their own processes (pm2, systemd) and set QUEUE_WORKER=off and SCHEDULER=off in .env, or leave both on and npm start runs them itself.

Before you go live, work through the Production checklist.

#TypeScript

TypeScript works in the browser (.kreft files and .ts modules) and on the server (routes/api.ts, app/**/*.ts, migrations, seeders).

BASH
kreft new my-app --ts

Inside a .kreft file you can write interface, type, enum, import type, and typed prop, state, derive and saved. kreftjs make:* writes .ts files when the project has a tsconfig.json (or with --ts; --js forces JavaScript).

Execution needs no setup: Kreft uses esbuild if installed, otherwise Node's built-in type stripping (Node 22.6+), otherwise its own zero-dependency stripper.

#Vite, Electron and Tauri

Vite. If your team prefers the Vite ecosystem, Kreft has a plugin that compiles .kreft files on the fly:

BASH
kreft vite:init       # writes vite.config.js with the Kreft plugin
kreft vite:dev        # Vite dev server with the backend API proxied
kreft vite:build      # optimised bundle with code splitting
kreft vite:preview

Electron. Turn the same app into a desktop application. See Desktop apps with Electron below.

Tauri. The same, with installers of a few megabytes, because the system web view is used instead of a bundled browser. See Desktop apps with Tauri.

#Packages

kreft install, kreft i and kreft add use the same npm security pipeline.

SH
kreft install luxon
# CI: explicitly allow installation after policy checks
kreft install luxon --yes
kreft i @scope/package@1.2.3 --dev
kreft install luxon --check --json

#The order of things

  1. Check. Kreft resolves the exact versions in a temporary folder and reviews every package: registry identity, integrity, advisories, license and tier. Your project is not touched.
  2. Ask. If the review passed, you see the summary and the question. A package that failed the review is blocked and no question is asked.
  3. Install, only on Allow. Kreft installs the reviewed packages with their integrity verified and scripts disabled, then updates package.json, the lockfile and node_modules together.
  4. Disallow cancels. Option 2, Enter, an unknown answer, Ctrl+C, EOF or a closed terminal cancel; option 4 also saves a deny rule.

What a No changes: nothing. A cancelled install leaves package.json, the lockfile, node_modules, kreftjs.config.json and other project files exactly as they were. npm may still update its external cache or logs while reviewing metadata. The temporary folder is removed, and no report is written either (no .kreft/ folder appears). The only answers that write anything are the ones that say so: Always allow and Never allow save a rule in kreftjs.config.json.

#What you see

Normal output shows a colored Package Security Assessment Report with only the requested package name, exact version and status, followed by the installation choices. Registry progress, dependency lists and advisory details are hidden. If project policy blocks installation, a short reason replaces the confirmation.

  • Every package, one by one, is written to .kreft/security/latest.txt (and latest.json) when reporting is enabled, except on cancellation. Add --verbose to kreft install to see all of it, and every check message, in the terminal.

After security checks pass, interactive CLI installs display the findings and ask what to do with the requested packages:

Like the JavaScript / TypeScript question in kreft new, package installation uses a numbered menu after the security check completes. For example, run kreft add dayjs, kreft i dayjs or kreft install dayjs:

TEXT
Security checks passed for dayjs@1.11.23. Choose what to do:
  1) Allow installation once
  2) Disallow installation once (default)
  3) Always allow this package in this project
  4) Never allow this package in this project

Installation [1/2/3/4]:

The version shown is the exact version resolved for that operation.

ChoiceWhat happens
1 — Allow onceInstall now after checks pass. No rule is saved; ask again next time. Also accepts a, allow, y, yes.
2 — Disallow onceCancel without changing project files or writing a report. This is the default for Enter, an unknown answer, EOF or Ctrl+C. Also accepts d, disallow.
3 — Always allowInstall now and save the exact reviewed version in security.allowedPackages, for example dayjs@1.11.23. Future installs of that version still run security checks, then skip the question. Also accepts r, always.
4 — Never allowCancel and save the package name in security.deniedPackages, for example dayjs. All versions are blocked on later installs. Also accepts n, never.

For several requested packages, the answer applies to the whole batch. Saved choices apply to the requested packages, not automatic approvals of their dependencies. An already allowed batch skips the question only after the full review passes. Use --yes / -y for unattended CI installs; it never bypasses security policy. IDE terminals and redirected streams can answer the numbered question too. If input is closed or no answer is available, installation visibly cancels. Blocked packages cannot be allowed through this menu; dry runs do not prompt.

The installer copies the manifest, npm lockfile and project .npmrc to a temporary sibling directory inside the project. npm resolves a lockfile with scripts disabled. Kreft inspects every resolved entry, including nested duplicates, peer and optional dependencies. npm handles version conflicts and cycles. Registry metadata is fetched once per exact package/version per operation, with bounded retries and timeouts. User npm configuration and scoped registry settings remain applicable. Reports can contain private package metadata; registry credentials are not copied into reports.

Before fetching package bodies, Kreft enforces exact registry identity, strong integrity metadata, license policy and npm advisory thresholds. Any policy failure leaves the project manifest, lockfile and node_modules untouched. A successful review installs in staging using npm ci --ignore-scripts, which verifies downloaded bytes against lockfile integrity. Kreft compares the resulting lockfile and installed package identities with the approved graph, then promotes the staged tree with recovery on promotion failure. Platform-specific optional omissions are recorded. Existing node_modules is replaced with the approved tree, so extraneous modules and manual edits are removed. An interrupted process or machine failure during promotion may require manual recovery from .kreft-node-modules-*; this is not a crash-atomic multi-file transaction.

Configuration follows the existing JSON configuration convention, in kreftjs.config.json (including the existing config/, Config/ and legacy filename lookup conventions):

JSON
{
  "security": {
    "enabled": true,
    "minimumTier": 2,
    "blockCriticalVulnerabilities": true,
    "blockHighVulnerabilities": true,
    "blockMaliciousPackages": true,
    "ignoreScripts": true,
    "verifyIntegrity": true,
    "auditOnInstall": true,
    "allowUnverified": false,
    "checkDependencies": true,
    "checkLicenses": true,
    "checkMaintenance": true,
    "failOnUnknownSecurityStatus": true,
    "deniedLicenses": ["AGPL-3.0-only"],
    "deniedPackages": ["example-denied", "another-package@1.0.0"],
    "allowedPackages": ["luxon@3.5.0", "@scope/internal-tool"],
    "reports": {
      "enabled": true,
      "format": ["json", "text"],
      "directory": ".kreft/security"
    }
  }
}

The deny and allow lists are empty by default; the entries above illustrate organization-specific restrictions. The other settings shown are defaults. Unknown settings and invalid types fail with an error. enabled, ignoreScripts, verifyIntegrity and checkDependencies must remain true in this implementation. --force and --yes never bypass package policy. --allow-scripts, --trusted, --no-audit and --no-exact are rejected; script-dependent native packages require a separately reviewed build step. Per-version script exceptions are not yet implemented. Desktop scaffolding (kreft add electron tauri) retains its existing separate setup workflow and is not covered by this gatekeeper. Run desktop scaffolding and package installation separately.

#Remembering your decision: allow and deny rules

The prompt's Always allow and Never allow answers write a rule into kreftjs.config.json. You can also edit the rules yourself, without installing anything:

SH
kreft install --allow-package luxon@3.5.0        # allow this exact version for good
kreft install --allow-package @scope/tool        # allow every version of a package
kreft install --deny-package left-pad            # block a package for good
kreft install --forget-package left-pad          # remove the rule again (a name removes every version)
kreft install --packages                         # list the rules (add --json for a machine-readable list)
  • security.allowedPackages lists packages that skip the question. An entry is a package name (any version) or an exact version (name@1.2.3). It never holds a range, a tag or a URL.
  • security.deniedPackages lists packages that are blocked. The same two forms.
  • Allowing never bypasses the review. The security check (registry identity, integrity, advisories, license, tier) runs first, exactly as for any package. An allowed package that fails it is still blocked, and nothing is installed. The allow list only saves you the question. In the same way, --yes and --force never bypass the policy.
  • Always allow records the exact version you reviewed, so a new version of the package is reviewed and asked about again.
  • One package cannot be both. A configuration that allows and denies the same package (with overlapping versions) is rejected with a message. --allow-package on a package you denied removes the deny, and --deny-package on an allowed package removes the allow: you changed your mind on purpose, and the command says it did so.
  • Your file is kept as written. Kreft edits only the security lists. Every other setting, and every ${NAME} placeholder, stays exactly as you wrote it, and the new file is written in one step so a crash cannot leave half a file. If the file cannot be written, the choice still counts for the current installation and Kreft says it was not saved.
  • A skipped question is recorded in the report as decisionSource: "allowedPackages"; an answer at the prompt is "prompt", and a saved choice also has a remembered entry.

Commit kreftjs.config.json to share the rules with your team, or keep them local: the file is the only place they live.

Classifications:

  • Trusted (Tier 1) requires verified provenance evidence this implementation cannot supply, so it is never issued. Requiring Tier 1 blocks installation.
  • Established (Tier 2) requires matching registry identity/integrity, available advisory results, license evidence and (by default) maintainer/repository evidence. These are registry claims, not proof that code is safe.
  • Unverified (Tier 3) indicates missing evidence, deprecation or license expressions requiring manual review. Permit explicitly with allowUnverified: true or minimumTier: 3. Missing registry/advisory evidence still blocks unless failOnUnknownSecurityStatus is also false.
  • Blocked means a mandatory configured policy rule failed. Reports give the package, version, graph location, rule and supporting advisory evidence.

Download counts and dependency counts never establish trust. Package age alone never blocks installation. Advertised provenance is reported as unverified. License denial checks SPDX identifier tokens conservatively, including OR expressions; there is no automatic legal interpretation. Maintenance evidence is limited to metadata, not a claim about maintainer trustworthiness.

Reports default to .kreft/security/latest.json and latest.txt; operations that write reports replace these files. Cancellation preserves any earlier reports. Interactive decisions are recorded in the report as decision: "allow", and a cancellation as status: "cancelled" with policyAllowed: true (which tells the developer's choice apart from a security block). A cancellation writes no report file: see "What a No changes" above. With --json the report goes to stdout either way. Other statuses are approved (successful review without installation), installed, blocked and failed.

--json emits the report to stdout; failures also produce diagnostic stderr and nonzero exit status. --check resolves and evaluates without fetching/extracting package bodies, so its approval does not mean artifact bytes have been verified. CI can run kreft install package --check --json and inspect the exit status before an actual install.

This version supports standalone npm projects with lockfile versions 2 and 3. Aliases, git/file/URL sources, npm overrides, workspaces, npm shrinkwrap and other package managers fail explicitly. They require additional resolution and verification support; they are not silently converted to npm. npm registry advisory availability is required by default. No advisory database guarantees complete malware or vulnerability detection. Source review, cryptographic provenance verification, historical dependency-change analysis and a dedicated malicious-package feed remain future work.

Validation: node --test test/package-rules.test.js covers the allow and deny rules, the prompt answers, the command-line flags and the guarantee that an allowed package is still reviewed. node --test test/package-gatekeeper.test.js exercises policy decisions, malicious specifications, advisory and license blocking, missing evidence, graph mismatch, dry runs, exact pinning and project preservation on failure. Resolution uses npm's documented lockfile behavior and npm ci semantics.

#MCP for AI agents

Kreft includes a Model Context Protocol server, so an AI coding agent can see your project's routes and schema, and query the database read-only.

Tool or resourceWhat it gives
query_databaseRuns one read-only SELECT.
list_routesEvery route with methods, name and middleware.
server_healthUptime and memory.
kreft://routes, kreft://schemaThe route catalogue; the tables, columns and keys.

#Local use (stdio)

BASH
kreft mcp
JSON
{
  "mcpServers": {
    "kreft": { "command": "kreft", "args": ["mcp"], "cwd": "/path/to/your-project" }
  }
}

#Over HTTP

kreft dev and kreft serve also answer at /mcp. Set a token and send it:

ENV
MCP_TOKEN=a-long-random-secret
BASH
curl -H "Authorization: Bearer a-long-random-secret" -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' http://localhost:8000/mcp

#What protects it

  • MCP_TOKEN is required whenever it is set. The APP_KEY is never accepted in its place.
  • In production (NODE_ENV or APP_ENV = production), the endpoint is off (403) until MCP_TOKEN is set.
  • In development without a token, only a direct local client is accepted: a loopback address, a localhost Host header, and no proxy headers (X-Forwarded-*). A remote address, a proxy or a tunnel needs MCP_TOKEN.
  • Browsers from foreign origins are refused. MCP_ALLOWED_ORIGIN adds one origin.
  • query_database is limited: one SELECT, no comments or ;, no mutations or file functions, no SELECT … INTO, and no sleeping or locking. It refuses columns and tables that hold credentials (anything named like a password, token, secret, hash or authentication, and the tokens, sessions and jobs tables), whole-row JSON building, and the database server's own accounts and sessions (mysql.*, performance_schema, sys, pg_authid…). Results are masked again by shape (password hashes). The query runs in a transaction that is always rolled back, with a time limit of 5 seconds (MCP_QUERY_TIMEOUT_MS).

#Calling other MCP servers (client)

Your app can also call tools on a remote MCP server over Streamable HTTP:

JS
const { Mcp } = require('kreftjs/server')

const quran = await Mcp.connect('https://mcp.quran.ai')   // { headers: { Authorization: 'Bearer …' } } if needed
const tools = await quran.tools()
const verses = await quran.call('fetch_quran', { ayahs: '1:1-2' })
await quran.close()

call returns the structured result (or the text, parsed as JSON when possible) and throws if the tool reports an error. Only http(s) URLs are accepted, redirects are refused, and a response over maxBytes (10 MB) is cut off. Never pass a URL a visitor typed: your server would fetch addresses of their choosing, including your internal network (SSRF). Use a fixed or allow-listed URL.

#Running kreft dev outside a project

kreft dev and kreft serve start only in a Kreft project: a folder with index.html, a frontend/ folder, .kreft pages, a backend or a kreftjs.config.json. In any other folder (an empty one, your home folder) they stop and say so, instead of serving whatever is there. kreft dev --force serves the folder anyway. kreft run dev is not a command: inside a project use kreft dev, or npm run dev.

#Kreft Shield

Floods and scanners from one address can slow a server to a crawl. Turn on the Shield with one line in .env (changes apply without a restart):

CODE
SHIELD=true

For every visitor address (the same req.ip() that throttle uses, so set TRUSTED_PROXIES behind a proxy):

ProtectionDefaultSetting
Rate limit: over the limit answers 429 with Retry-After300 requests in 10 sSHIELD_MAX_REQUESTS, SHIELD_WINDOW_SEC
Probing counts more: 401, 403, 404 and 405 answers weigh 5 requests5SHIELD_ERROR_WEIGHT
Concurrency: requests in flight at once from one address60SHIELD_MAX_CONCURRENT
Ban: this many rate-limit hits within the strike window3 hits in 10 minSHIELD_STRIKES, SHIELD_STRIKE_WINDOW_MIN
Ban length, doubling at every repeat up to 24 h15 minSHIELD_BAN_MINUTES
Connections: open sockets from one address; extra ones are closed (stops slowloris floods that never finish a request)100SHIELD_MAX_CONNECTIONS
Overload: when the event loop lags, limits shrink to a quarter300 ms lagSHIELD_MAX_LAG_MS

IPv6 visitors are counted by their /64 prefix, because one customer owns billions of addresses in it and could otherwise rotate through them.

Behind nginx, Caddy or a CDN, set TRUSTED_PROXIES. Without it every visitor looks like the proxy: all users would share one limit and one ban, and a proxy on the same computer (127.0.0.1) is never limited at all. The Shield prints a warning when it sees X-Forwarded-For from an address that is not trusted.

Never limited: addresses in SHIELD_ALLOW="1.2.3.4,5.6.7.8" and this computer (127.0.0.1, ::1), unless SHIELD_LOCAL=true (use it to try the Shield on your own machine). A banned address is answered with a bare 429 before any work is done.

JS
const { Shield } = require('kreftjs/server')
Shield.on('ban', (b) => Log.warning(`banned ${b.ip} for ${b.minutes} min: ${b.reason}`))
Shield.bans()            // who is banned now
Shield.unban('1.2.3.4')  // let an address back in
Shield.ban('1.2.3.4', 60)
Shield.status()          // counters, limits, event-loop lag

The MCP tool shield_status returns the same. Bans are kept in memory, so a restart clears them. The Shield protects the application; a flood that fills your network connection has to be stopped by a firewall or a CDN in front of the server.

#Memory watchdog

Long-running servers can slowly collect memory. Start with --gc (or AUTO_GC=1) and Kreft samples the heap every 30 seconds (AUTO_GC_INTERVAL_MS). When it passes AUTO_GC_THRESHOLD_MB, Kreft clears its own caches and runs garbage collection. This is a safety net; find the leak if you see it often.

The watchdog is a small memory manager:

  • Adaptive. A cleanup also runs when the heap keeps growing (more than AUTO_GC_GROWTH_MB_PER_MIN, default 20) while already above 60% of the threshold, not only after it passes the limit.
  • Least-used first. The in-memory cache (CACHE_STORE=memory) keeps at most CACHE_MEMORY_MAX entries (default 5000) and, under pressure, drops expired and least recently used entries instead of everything. Register your own cache with onMemoryPressure('name', (fraction) => dropped).
  • Leak hint. After each real GC (needs --gc) Kreft records the heap that remains. If it keeps rising by AUTO_GC_LEAK_RISE_MB (default 20) over several collections, it reports a suspected leak. writeHeapSnapshot() saves a .heapsnapshot for Chrome DevTools to show what holds the memory.
  • Alerts. onMemoryAlert((alert) => …) is called when memory is still high after AUTO_GC_ALERT_AFTER cleanups in a row (default 3), or a leak is suspected, at most once per 10 minutes. Without a listener the alert is printed as a warning.
  • Report. getMemoryReport() returns the samples, trend, GC and eviction counts, leak state and alerts as JSON; the MCP tool memory_report returns the same.
JS
const { getMemoryReport, onMemoryAlert } = require('kreftjs/server')
onMemoryAlert((a) => Log.warning(a.message))
Route.get('/admin/memory', () => getMemoryReport()).middleware('auth')

#Security

#Security overview

Kreft is built so the safe thing is the default. This chapter lists what is protected, where, and what stays your job.

#In the browser

  • Escaped views. Everything in { }, k-text and attributes is shown as text. <script> in a user's bio is only text.
  • k-html is cleaned, not trusted. Kreft parses the HTML the way the browser does, in a document that runs nothing, then removes scripts, frames, forms, SVG and MathML, every on… attribute, srcdoc, and addresses that start with javascript: or an unsafe data:. Even so, bind only HTML you trust or that the server already cleaned.
  • A strict Content-Security-Policy works with built apps. kreft build turns every expression into a function ahead of time, so there is no eval and no new Function. Without a build, views compile in the browser and a strict CSP blocks that.
  • Prototype pollution is blocked. Paths and keys such as __proto__, constructor and prototype are ignored in views, translations and JSON bodies.
  • A login cookie is HttpOnly, so a script on your page cannot read it.

#In the phone app

  • Anything inside the app can be read by whoever installs it: the files, the code and every PUBLIC_ value. Secrets (API keys, database passwords, APP_KEY) stay on the server; the app talks to your server, and your server talks to the other services.
  • Sign in with API tokens, not cookie sessions, and keep the token in the phone's secure storage. Use https:// for every address.
  • Kreftjs.native.system.openUrl opens only http, https, mailto, tel and sms addresses, never javascript: or file:. edge-web-view shows only http(s) and relative addresses, in a sandbox that cannot reach your app's data.
  • Live reload (kreft mobile:dev) shares the dev server on your network. Use a private network.

#On the server

#CSRF

Kreft uses the double-submit cookie pattern. Any safe request gets an XSRF-TOKEN cookie; any request that changes data (POST, PUT, PATCH, DELETE) from a browser must send the same value back in X-XSRF-TOKEN (or X-CSRF-TOKEN, a _token field). The comparison is constant-time, and a wrong or missing token answers 419.

  • Kreftjs.api sends the header by itself. HTML forms add <input type="hidden" name="_token" value="{csrfToken}">.
  • Route.csrfCookie('/csrf-cookie') gives a single-page app an endpoint to get the cookie first.
  • Exempt only what must be (webhooks): .withoutMiddleware('csrf').
  • Requests that carry only an API bearer token and no cookie are not browser sessions and do not need CSRF.

#HTML on the server

Anything built into HTML on the server should go through the helpers in kreftjs/server:

JS
const { escapeHtml, cleanHtml, SafeHtml, html } = require('kreftjs/server')

escapeHtml(userText)                         // turn text into safe text
cleanHtml(userHtml)                          // keep a small set of tags and attributes, drop the rest

cleanHtml keeps an allow-list of tags and attributes, checks every address, and filters style. A tag it cannot read is turned into text (&lt;), never passed through.

#Passwords, keys and tokens

ToolWhat it does
Hash.make / Hash.checkPasswords with scrypt, a new salt each time, constant-time compare.
Crypt.encryptString / Crypt.decryptStringAES-256-GCM with a fresh IV, keyed by APP_KEY. Tampering is detected.
Url.signed / Url.checkLinks that work only unchanged (and until a time).
API tokens, reset tokensStored as a SHA-256 hash; the plain value is shown once.

#Limits and lockouts

  • throttle:60,1 limits requests per visitor and route. The sign-in routes allow 6 a minute.
  • Accounts lock after repeated wrong passwords or two-factor codes, whatever the address. See Authentication.
  • Request bodies are limited (MAX_BODY_KB), and JSON bodies cannot carry __proto__ or constructor keys.
  • Every API answer carries X-Content-Type-Options, X-Frame-Options and Referrer-Policy; in production also Strict-Transport-Security.

#Plain HTTP

In production a request with X-Forwarded-Proto: http is redirected to https, and one with X-Forwarded-Proto: https is served when it comes from this machine or from a proxy listed in TRUSTED_PROXIES (so a proxy that ends TLS works with FORCE_HTTPS=true or an https:// APP_URL; anyone else could write that header, so from other addresses it is ignored, and the server says so once in its log). Without that header, FORCE_HTTPS=true or an https:// APP_URL redirects every plain request. The address in the redirect comes from APP_URL when set, otherwise from the Host header only if it looks like a host name; it cannot be used to send visitors to another site.

#API tokens

A token made in the profile page has a list of permissions (read, create, update, delete), and the middleware enforces them from the HTTP method on every route. A read-only token cannot delete anything, even if its owner is an admin.

#Uploads

Files get random names. Unknown extensions are stored as .bin. Public files are served as plain data with a sandbox policy, so they cannot run scripts. Use isImage() to check the real file header.

#The database

  • Values travel as parameters. Table and column names are quoted.
  • The automatic table API (--db) is a development tool with no login. kreft serve only serves the tables you list in kreftjs.config.json, with write: false and hidden: [...] where needed; hidden columns cannot be read or used to sort.
  • Raw SQL helpers (whereRaw, selectRaw, orderByRaw, DB.raw) are for your own SQL; pass user values in their parameter array.

#Packages

kreft add blocks install scripts, typosquats and look-alike names, flags very new packages, and pins exact versions. See Packages.

#What stays your job

  • Check access on the server. Client route guards decide what to show, not who may read data. Every route that returns private data needs auth and, where it matters, admin or a policy.
  • Never trust HTML you did not clean, and never put secrets in PUBLIC_ variables or localStorage.
  • Keep dependencies and Node.js up to date (kreft update, npm audit).
  • Protect the machine. Kreft cannot protect a database, a server or a .env file that others can read.

#Production checklist

Go through this before your first real user:

CheckWhy
NODE_ENV=production and APP_ENV=productionTurns off debug pages, enables HSTS and the https redirect, and makes security errors fatal.
APP_DEBUG=falseNever show stack traces or source code to visitors.
APP_KEY set to a 32-byte key (kreft key:generate)In production the app refuses to start without a key of at least 16 bytes. A random per-process key would also break sessions on restart.
APP_URL=https://your.siteUsed for links in emails, the https redirect and secure cookies.
TRUSTED_PROXIES set if you use a proxyOtherwise every visitor shares the proxy's address and rate limits.
A real DATABASE_URL and a backup planSQLite is fine for small apps; use MySQL or PostgreSQL for several servers.
CACHE_STORE=redis or database, QUEUE_CONNECTION=redis or databasememory is per process. Account lockouts live in the cache, so they are shared between servers only with database or redis.
MAIL_URL setOtherwise emails are only printed in the terminal.
MCP_TOKEN set, or MCP left offThe MCP endpoint is disabled in production without it.
Tables listed in kreftjs.config.json, or no --db at allkreft serve serves only the tables you list.
No test userDo not run --seed against production; delete test@example.com if it exists.
HTTPS in front of the app, and FORCE_HTTPS=trueCookies are Secure in production and on https URLs. Plain HTTP is only redirected to HTTPS with FORCE_HTTPS=true or an https:// APP_URL.
No SESSION_SECURE_COOKIE=false in .envIt switches the Secure flag off, so the login cookie is also sent over plain http://. Older templates wrote it; the server warns about it at start-up in production.
npm audit and kreft updateFix known vulnerabilities before release.
Phone app: --api-url is an https:// address, and the app id is yoursA published app must not call http://10.0.2.2 or keep the id com.example.…. See Publishing your app.
Phone app: no secrets inside itEverything in an app (the code, PUBLIC_ values) can be read by whoever installs it. Keep keys and passwords on the server.

#Known limits

  • Without a build, views are compiled in the browser with new Function, which a strict Content-Security-Policy blocks. Use kreft build for production.
  • Inside a view, < directly followed by a letter starts a tag, so write {a < b} with a space.
  • The memory of which two-factor codes were already used, and login tickets, is kept per process. Behind several servers, a code can be replayed once on each. The per-account lockout (kept in the cache) still limits guessing.
  • The sanitizer removes unsafe markup; it is not a substitute for choosing carefully what HTML you show.
  • --prerender makes static HTML at build time; on a running server KREFT_SSR=all draws every page for every visitor (see Pages drawn on the server). The browser takes a drawn page over by drawing it again from the same data, not by attaching to the server's HTML (no hydration of the existing nodes yet). Pages are sent whole, not streamed: streaming would have to send the status before the page is drawn, so an address the app does not have could no longer answer 404. Without server rendering an address the app does not have answers 200 (the app shows its own 404 page) unless seo.js says otherwise.
  • .kreft files must be served over http:// or https://, not opened from file://.
  • Phone apps run your web app in the phone's WebView and need a server for the backend; iOS builds need a Mac with Xcode. See Mobile: what to know.

#Reference

#Environment variables

Set these in .env (never commit it). Variables that start with PUBLIC_ are copied into the browser as Kreftjs.env; never put a secret in one.

#App

VariableMeaning
APP_NAME, APP_URLName and public address (used in emails, https redirects, secure cookies).
APP_ENV, NODE_ENVproduction turns on production behaviour (either one is enough).
APP_DEBUGtrue shows the interactive error page outside production.
APP_KEYEncrypts sessions and signs links. Make it with kreft key:generate; required in production.
APP_LOCALE, APP_FALLBACK_LOCALE, APP_TIMEZONELanguage and time zone defaults.
HOST, PORTWhere kreft serve listens.
PUBLIC_APP_NAMEThe app's name in the browser, in the phone app's top bar and home page, and under the animated splash logo.
PUBLIC_API_URLThe server a phone app talks to. kreft mobile:build --api-url https://api.example.com writes it for you; read it with Kreftjs.env.PUBLIC_API_URL. It is visible inside the app, so never put a secret in it.
FORCE_HTTPStrue redirects plain HTTP in production.
MAX_BODY_KBLargest request body accepted.

#Database, cache and queues

VariableMeaning
DATABASE_URLsqlite:…, mysql://… or postgres://….
DB_CONNECTION, DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, DB_PASSWORD, DB_SSLThe same as separate values.
CACHE_STOREdatabase, file, memory or redis. Also CACHE_PREFIX, CACHE_DEFAULT_TTL.
QUEUE_CONNECTIONdatabase, redis or sync. Also QUEUE_NAMES, QUEUE_WORKER.
REDIS_URL, or REDIS_HOST REDIS_PORT REDIS_USERNAME REDIS_PASSWORD REDIS_DB REDIS_TLS REDIS_PREFIXRedis connection.
SCHEDULERoff hands scheduling to cron (kreft schedule:run).
MAX_QUERY_ROWS, HARD_QUERY_LIMITUpper limits on rows a query may return.
FILESYSTEM_DISKlocal or public.

#Sign-in and sessions

VariableDefaultMeaning
SESSION_LIFETIME120Minutes of inactivity before a session ends.
SESSION_EXPIRE_ON_CLOSEfalseEnd the session when the browser closes.
SESSION_SECURE_COOKIE, SESSION_SAME_SITE, SESSION_DOMAIN, SESSION_COOKIEproduction / LaxCookie attributes.
AUTH_TOKEN_DAYS30A token unused this long stops working.
PASSWORD_TIMEOUT10800Seconds a password confirmation stays valid.
LOGIN_MAX_FAILURES, LOGIN_WINDOW_SECONDS10, 900Wrong passwords per account before a lockout.
TWO_FACTOR_MAX_FAILURES8Wrong two-factor codes per account before a lockout.
PUBLIC_SESSION_TIMEOUT, PUBLIC_SESSION_WARNING15, 2Minutes of page inactivity before sign-out, and the warning before it.
PUBLIC_DOCS_URLhttp://kreftjs.comWhere the "Documentation" links of a new app's pages go. Change it to https://… or to your own site.

#Network and tools

VariableMeaning
TRUSTED_PROXIES, TRUSTED_PROXY_HOPSWhich proxies' X-Forwarded-For is believed, and how many stand in front with *.
KREFT_ALLOWED_HOSTSExtra host names kreft dev answers to.
MCP_DATABASE_RESTRICTEDSet to true when the MCP connection uses a database user that can read only the tables it should see. Without an engine-enforced read protection (SQLite on Node.js 24+ has one) the query_database tool is turned off; the other MCP tools stay on.
KREFT_ALLOWED_ORIGINSFull origins (like https://app.example.com,http://localhost:5173) whose plain HTML forms may post to your API. A form sent from any other web site, or from the same host on another port, is refused (this stops login CSRF). JSON requests are not affected.
MCP_TOKEN, MCP_ALLOWED_ORIGIN, MCP_QUERY_TIMEOUT_MSMCP endpoint token, one extra allowed browser origin, and the query time limit.
MAIL_URL, MAIL_FROMsmtp://user:password@host:587 sends real email (needs kreft add nodemailer).
LOG_LEVEL, LOG_CHANNELdebug, info, notice, warning, error, critical.
AUTO_GC, AUTO_GC_THRESHOLD_MB, AUTO_GC_INTERVAL_MSThe memory watchdog.

#API cheat sheet

GroupNames
.kreft keywordsstate derive action when watch on prop event use share receive import saved load layout
In the scriptsend props bus store $route $router tick and every Kreft function
In the view{expr} attr={expr} @event k-if k-elif k-else k-each k-key k-match k-case k-default k-model k-show k-text k-html k-ref k-skip k-once k-memo k-animate {for}
AppKreftjs.app(rootOrPath) then .component() .directive() .share() .use() .mount() .unmount()
Datastore ($patch $reset $watch) state signal derived readonly saved storage
Reactingwatch effect tick onCleanup onReady onUpdate onShow onHide onDestroy
Sharingbus (on once off send) share receive
Formsform(values, rules) ($error $errors $valid $busy $submit $check $reset $setErrors) and validate(values, rules)
Server datatable(name) and api (get post put patch delete setup create onError)
Languages$t $choice $locale $dir, Kreftjs.locale() Kreftjs.translations()
RouterKreftjs.router() with .go .replace .back .before .after .route, and children for nested routes
EngineKreftjs.render(view, data, options)
Phone appsKreftjs.native (device haptics file system position dialog on pushBack safeArea asset), the edge store (setTop setBottom reset hideBars), Kreftjs.edgeIcons, the edge- components, and the touch events @tap @longpress @swipe @swipeleft @swiperight @swipeup @swipedown
ServerRoute Model DB Seeder Hash Str Url Mail Crypt Cache Storage Schedule config response abort and the helpers in require('kreftjs/server')

#Compared with other frameworks

Kreft is one framework for the browser and the server. The others below each cover part of that, so the honest comparison is "what do you put next to them". This is a map to help you choose, not a ranking: all of them are good, and most are older, bigger and better known than Kreft.

KreftNext.jsNuxtSvelteKitAstroAdonisJSNestJS
What it isFrontend and backend in oneReact frameworkVue frameworkSvelte frameworkContent sites with islands of interactivityBackend (MVC, Laravel style)Backend (modules, dependency injection)
Components.kreft files, no Virtual DOMReactVueSvelte (compiled)Astro files; React, Vue, Svelte … insidenone (Edge templates, or React/Vue/Svelte through Inertia)none
Pages drawn on the serverYes, for every visitor (KREFT_SSR=all, with the data loaded on the server and the signed-in user's own page), or at build time (--prerender)Yes, for every visitorYes, for every visitorYes, for every visitor, or prerenderedYes, mostly at build timeEdge templates, or SSR with Inertiano
Database layerActive Record Model, migrations, seeders, factoriesnone (use Prisma, Drizzle …)nonenonenoneLucid (Active Record)none (TypeORM, Prisma, MikroORM …)
Sign-in, 2FA, API tokensAll three built in, in every new projectnone (Auth.js …)none (a module)none (Better Auth …)noneSign-in and API tokens official; 2FA through packagesnone (Passport, your own)
Queues, mail, scheduler, cacheBuilt innonenonenonenoneMail and cache official; queues and scheduler through packagesModules
Phone and desktop appsReady commands: Capacitor, Electron, Tauri, HarmonyOSnonenonenone (wire Capacitor or Tauri yourself)nonenonenone
AI agent access (MCP)Built innonenonenonenonenonenone
Installing npm packageskreft add checks signature, provenance, release age, look-alike names and the code before anything is installednpm/pnpm as they arenpm/pnpm as they arenpm/pnpm as they arenpm/pnpm as they arenpm/pnpm as they arenpm/pnpm as they are
Runtime dependenciesNoneManyManyFewManySomeSome
LanguageJavaScript or TypeScriptTypeScript firstTypeScript firstJavaScript or TypeScriptTypeScript firstTypeScript firstTypeScript first
Ecosystem and hiringSmall, newVery largeLargeMedium, growingLargeMediumLarge

On its own, in the browser, Kreft sits next to the UI libraries:

KreftReactVueSvelteAngular
Component.kreft filefunction returning JSX.vue file.svelte fileTypeScript class + template
Reactivitystate, derive, actionuseState, the function runs againref, reactiverunes: $state, $derivedsignals (and RxJS)
Virtual DOMnoyesyesnono
Router, stores, forms and validation, i18n with RTLall built inseparate librariesofficial router and Pinia; forms and i18n separatewith SvelteKit; forms and i18n separaterouter, forms and i18n built in
Build stepnone needed (kreft build optional)needed (JSX)optionalneeded (compiler)needed
Ecosystem and hiringsmall, newthe largestlargemediumvery large, mostly companies

Choose Kreft when you want a whole application (screens, database, sign-in, jobs, mail) from one tool with almost no dependencies, in the Laravel style, and your team is small enough to learn one framework.

Choose something else when:

  • Next.js or Nuxt: your team already knows React or Vue, you need the libraries of that ecosystem, or you need streaming, or a browser that attaches to the server's HTML instead of drawing it again. Kreft draws every page on the server with its data, refreshes cached pages like ISR (see "Pages drawn on the server"), and splits the app by page, but does not stream.
  • Astro: the site is mostly content (blog, documentation, marketing) and ships almost no JavaScript. Kreft apps always ship the framework.
  • SvelteKit: you want server-drawn pages for every visitor with very little JavaScript in the browser, and you like Svelte.
  • AdonisJS: you want the same Laravel-like backend with a larger community and years of production use, and you will bring your own frontend.
  • NestJS: you build a large API or microservices with many teams, and you want strict structure and dependency injection.
  • React, Vue, Svelte or Angular on their own: you only need the browser part, already have a backend, or want the largest library and hiring market (React, Angular).

Things to weigh before choosing Kreft: it is young and has one small community, few third-party packages are made for .kreft files, and nobody has run it at large scale yet. See Known limits.

#Coming from Vue

VueKreft
.vue single-file component.kreft file: script, <view>, <style scoped>
ref(), reactive(), computed()state, derive (JS: Kreftjs.signal, Kreftjs.state, Kreftjs.derived)
watch, watchEffectwatch x { }, when cond { } (JS: Kreftjs.watch, Kreftjs.effect)
{{ x }}, :attr, @click{x}, attr={x}, @click={fn}
v-if, v-else-if, v-else, v-showk-if, k-elif, k-else, k-show
v-for with :key{for x in list key x.id} … {/for}, or k-each + k-key
v-model, v-once, v-memok-model, k-once, k-memo
defineProps, defineEmits, emitprop, event, send()
slots, scoped slots<slot>, <template k-slot:name="{ item }">
provide, injectshare, receive
onMounted, onUpdated, onUnmountedon ready, on update, on destroy
<KeepAlive>, <Teleport>, <Suspense>keep, <kreft-portal>, <kreft-wait>
<Transition>k-animate="fade"
Vue Router with nested routesKreftjs.router(), <kreft-view>, <kreft-link>, children
PiniaKreftjs.store() + use, with { saved: true }
Vite dev serverkreft dev (or kreft vite:dev)
Nuxt static generationkreft build --prerender
Nuxt server/apiserver/*.js served at /api/*

#Glossary

TermMeaning
ComponentA .kreft file: script, view and style together.
StateA value that can change; the view follows it.
Derived valueA value calculated from other values; stays up to date by itself.
StoreState shared by many components.
LayoutThe frame around pages: header, menu, footer.
MiddlewareA check that runs before a route (client side) or a controller (server side).
MigrationA file that describes a change to the database schema.
Seeder / FactoryFills the database with starting data / makes fake rows.
PolicyA class that decides whether a user may do something to a model.
MCPModel Context Protocol: how AI agents read your project through tools.

#Credits

Kreft was created by Mohamoud Hussen Abdi with Claude AI.