Reference
This reference guide lists the features of Kitten. For a comprehensive “owner’s manual”-style technical reference of how Kitten is designed and works internally, please see the Technical Manual.
About
Kitten is a little web kit (“kitten”, get it?) optimised for people (not corporations) who make the new everyday things for themselves and other people – not because they want to become billionaires but because they want to contribute to the common good by helping nurture the Small Web while adhering to the Small Technology Principles.
Kitten features intuitive file system-based routing, HTML and accessibility validation, a built-in object database, WebSockets, zero-code authentication, public-key cryptography, Markdown support, syntax highlighting via highlight.js, semantic styles via Water CSS, and more.
System requirements
- Linux or macOS.
- Common developer tools and system utilities (
git,tar,tee, andxz).
For production servers, only Linux with systemd is supported.
Installing Kitten
To install Kitten, either:
😇 Clone the Kitten repository and run the
./installscript:git clone https://codeberg.org/kitten/app kitten cd kitten ./install😈 Or, copy and paste one of the following commands into your terminal to pipe the installation script into your shell and run it:
Using wget:
wget -qO- https://kittens.small-web.org/install | bashUsing curl:
curl -sL https://kittens.small-web.org/install | bashDownload and view the install script source to verify it’s safe to pipe to your shell.
You can also compare it to the code in the source repository to ensure they’re the same.
Post-installation steps (macOS)
On macOS, you have a couple of manual post-installation steps to perform.
(Detailed instructions on how to carry out the below steps are presented in the installer at installation time.)
You must update your system’s path with the location of the
kittencommand as ~/.local/bin is not on the path by default on macOS.(You will also have to do this on Linux distributions that don’t automatically add this folder to your system path. The installer will prompt you to do this if it detects that this is the case.)
If you want to test peer-to-peer apps locally, you must edit your /etc/hosts file to add Kitten’s localhost aliases (place1.localhost, place2.localhost, …, place4.localhost).
To learn more about building peer-to-peer Small Web apps, see the End-to-end encrypted peer-to-peer Small Web apps tutorial.
If you want to install not the latest version of Kitten but the latest version for a given API version, modify your download command to tack the api version to the URL and to pass it as an argument to the bash script. For example, if you wanted to install the latest Kitten package for API version 1 using CURL, your command would look like this:
curl -sL https://kittens.small-web.org/install/1/ | bash -s -- 1If you’re running an “immutable” Linux distribution like Fedora Silverblue, please install Kitten from your host account (instead of from within a container) at least once so Kitten can set unprivileged ports to start from 80 (so it can run without elevated privileges).
Updating Kitten
You can update Kitten in two ways:
On a development machine, run
kitten update. It installs the newest Kitten release and leaves your apps alone.On a server, Kitten checks for updates itself (see Versioning), and
kitten updatechecks at once, as Check now on the Kitten Settings page does. Both move Kitten and the deployed app together, within the Kitten API version the app declares, and roll back when the new version does not start. Note thatkitten updateruns its own update check beside the server’s, so while automatic updates are on, use Check now instead.
Kitten’s API version 0 releases (23 April, 9 October, and 21 October 2026) do not automatically update themselves to API version 1. On the 23 April and 9 October releases, kitten update moves Kitten to the 21 October release. On the 21 October release, kitten update reports that Kitten is up to date. To upgrade to API 1, please run the installer again (curl -sL https://kittens.small-web.org/install | bash).
For more details, please see Upgrading from API version 0 to API version 1.
Running Kitten
You run kitten from the command-line (using a terminal app). Switch to a folder that has the content your want Kitten to serve and enter the following command:
kitten
You should see Kitten launch and tell you that it’s serving your site or app at https://localhost.
You’re not limited to accessing your local machine via https://localhost, either. You can also use any local IP address that it’s accessible from (see Accessing your local machine from other devices on your local area network for more information). You can also use the IP aliases 127.0.0.2 - 127.0.0.4 and localhost aliases (subdomains) place1.localhost - place4.localhost without certificate errors. The latter, especially, are useful when testing the peer-to-peer features of Small Web apps.
Small Web places made with Kitten are meant to be owned and used by one person. Until an identity and secret has been generated for this person, Kitten will display a link to the special page that generates them. (Your secret on a Small Web place never hits the server.) You can also generate this secret from Kitten’s REPL using the .id create command.)
Note that the first time Kitten is run, it will create a TLS certificate authority and add it to your system trust stores as well as to Firefox and Chrome so you can run your development environment from https://localhost to match the deployment environment as closely as possible. Your operating system will ask your permission before allowing this.
By default, Kitten will be as quiet as possible and only surface warnings and errors. If you want more extensive logging, start it with the LOG environment variable set to the log sections you want to see:
LOG=<sections> kitten [path to serve]
Similarly, if you want to see performance statistics, set PROFILE=true.
Glossary
These are the words we use in this reference for the kinds of pages and components you author in Kitten.
- Static page
An .html or .htm file that we serve as is. (During development, we add a script to it that reloads the page when Kitten restarts after you change a file.) See Static files.
- Dynamic page
A .page.js, .page.ts, or .page.md route that we render into HTML on each request. A dynamic page is either a stateless page or a stateful page. See Valid file types.
- Stateless page
A dynamic page that exports a function. The function is a stateless component that we call on each request and that returns
kitten.html. A Markdown page is stateless unless its front matter has aconstructorsection orstateful: true. A stateless page that also exports anon…event handler is a live page.- Stateful page
A dynamic page that exports a
kitten.Pagesubclass. We create an instance of your class on each request, and the instance stores its state in its properties for as long as the page is connected. Every stateful page is a live page. (A Markdown page with aconstructorsection orstateful: truein its front matter is a stateful page too; see Stateful Markdown pages.)- Live page
Live pages are dynamic pages that automatically create a WebSocket connection to their page socket route and use this connection to enable a Streaming HTML workflow, where you respond to events emitted on the client with interface updates generated on the server that you stream to the client.
Every stateful page is a live page, and so is every stateless page that exports an
on…event handler. We keep a live page in memory, inkitten.pages, while it is connected. (If a page doesn’t connect within ten seconds of its response finishing, we remove it.) See Streaming HTML, Page sockets, and Event handlers.- Stateless component
A function that returns
kitten.html. It has no state of its own and renders from the props you pass it each time. See Stateless components.- Stateful component
A
kitten.Componentsubclass. It stores its state in its properties, handles the events from its part of the page in itson…methods, and streams updates of itself to the page. See Stateful components.A stateful component needs a live page: you add it to the page, or to another stateful component on the page, with
addChild(). On a stateless page that exports anon…event handler, we create akitten.Pageinstance and bind your page function to it, so you can callthis.addChild()in that function. A stateless page that isn’t live has no page instance.
Authoring
JavaScript
Internally, Kitten uses the latest Node.js LTS binary as its runtime (currently Node 24 LTS.).
You can quickly get started with Kitten using plain old JavaScript.
Kitten does not have a build stage, nor does it require any scaffolding.
Type safety
So you’ve started hacking together some JavaScript and you want to add type safety to your site or app.
It’s easy:
For a new project
kitten init js
kitten init also declares the Kitten API version the app supports in package.json (engines.kitten), which a deployed app’s updates follow; see Versioning.
For an existing project
kitten add kitten-types
If you’d rather do things manually so you know exactly what’s happening:
Install the Kitten Types module as a development dependency:
npm install --save-dev @small-web/kitten-typesEither:
a. Add
// @ts-checkto the tops of your JavaScript pages, orb. Create a jsconfig.json file.
kitten add kitten-typessets up a JavaScript project if your project has a jsconfig.json file and no tsconfig.json file. Otherwise, it sets up a TypeScript project.For a JavaScript project, it writes the files listed under tsconfig.json, with
jsconfigin place oftsconfigin their names:- jsconfig.json (the root file)
- jsconfig.server.json
- jsconfig.client.json
- client-globals.d.ts
It also sets your
typecheckscript tonpx tsc -b jsconfig.json. (Without a file name,tsc -blooks for tsconfig.json.)Note that if you already have a jsconfig.json file of your own,
kitten add kitten-typesdoesn’t change it. Instead, it shows a warning and doesn’t write any of these files. Either move your jsconfig.json file aside and run the command again, or set things up by hand.To set things up by hand, copy the files listed under tsconfig.json. Rename tsconfig.json, tsconfig.server.json, and tsconfig.client.json to jsconfig.json, jsconfig.server.json, and jsconfig.client.json. Then change the two paths in jsconfig.json to
./jsconfig.server.jsonand./jsconfig.client.json.
That’s it!
To add type annotations to your project, you can use JSDoc.
TypeScript
Kitten also has TypeScript support without requiring a build step (your .ts files work exactly like your .js files).
For a new project
kitten init
(Or kitten init ts but ts is the default and hence redundant.)
kitten init also declares the Kitten API version the app supports in package.json (engines.kitten), which a deployed app’s updates follow; see Versioning.
For an existing project
kitten add kitten-types
If you’d rather do things manually so you know exactly what’s happening:
The process for enabling type safety for TypeScript projects has just one extra step than that for JavaScript projects:
Install Kitten Types (@small-web/kitten-types) as a development-time dependency.
npm install --save-dev @small-web/kitten-typesCreate a globals.d.ts file in your project:
import '@small-web/kitten-types' export {}
That’s it!
The global kitten type information will now be picked up by your editor.
Kitten automatically transpiles TypeScript files it serves to the browser to JavaScript.
These include:
- client-side scripts (.client.ts files)
- any other .ts file that isn’t a server-side Kitten file type
The client program type checks every file that isn’t a Kitten server file type, using the browser’s types. So if you write code that only runs on the server, put it in a .script.js or .script.ts file. We never serve those files, and the client program leaves them out.
Note that the client program also leaves out tests and test folders, but we still serve the files in them as usual.
- Program
A collection of SourceFiles and a set of compilation options that represent a compilation unit. The program is the main entry point to the type system and code generation.
tsconfig.json
This is the recommended set of configuration files for Kitten, implementing the libraries recommended for Node 24 by the tsconfig/bases project for the server program. kitten init writes all of them, and npm run typecheck runs tsc -b, which checks both programs. (For a JavaScript project with a jsconfig.json file, see For an existing project under Type safety.)
tsconfig.json, tsconfig.server.json, tsconfig.client.json, and client-globals.d.ts
tsconfig.json (root)
// The server and the client program have different kitten globals.
{ "files": [], "references": [{ "path": "./tsconfig.server.json" }, { "path": "./tsconfig.client.json" }] }
tsconfig.server.json
{
"compilerOptions": {
"composite": true,
"tsBuildInfoFile": "./.tsbuildinfo/server",
"target": "ES2025",
"lib": ["ES2025", "ESNext.Array", "ESNext.Error"],
"module": "Preserve",
"moduleDetection": "force",
"verbatimModuleSyntax": true,
"isolatedModules": true,
"allowImportingTsExtensions": true,
"noEmit": true,
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"skipLibCheck": true,
"allowJs": true,
"checkJs": true
},
"exclude": ["node_modules", "**/*.client.js", "**/*.client.ts", "client-globals.d.ts"]
}
tsconfig.client.json
{
"compilerOptions": {
"composite": true,
"tsBuildInfoFile": "./.tsbuildinfo/client",
"target": "ES2025",
"lib": ["ES2025", "DOM", "DOM.Iterable"],
"module": "Preserve",
"moduleDetection": "force",
"verbatimModuleSyntax": true,
"isolatedModules": true,
"allowImportingTsExtensions": true,
"noEmit": true,
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"skipLibCheck": true,
"allowJs": true,
"checkJs": true
},
"include": ["**/*"],
"exclude": ["node_modules", "**/app_modules/**", "**/__archive__*/**", "**/tests/**", "**/test/**", "**/*.test.*", "**/*.spec.*", "globals.d.ts", "**/*.get.js", "**/*.head.js", "**/*.patch.js", "**/*.options.js", "**/*.connect.js", "**/*.delete.js", "**/*.trace.js", "**/*.post.js", "**/*.put.js", "**/*.get.ts", "**/*.head.ts", "**/*.patch.ts", "**/*.options.ts", "**/*.connect.ts", "**/*.delete.ts", "**/*.trace.ts", "**/*.post.ts", "**/*.put.ts", "**/*.socket.js", "**/*.socket.ts", "**/*.page.js", "**/*.page.ts", "**/*.page.md", "**/*.component.js", "**/*.fragment.js", "**/*.component.ts", "**/*.fragment.ts", "**/*.fragment.html", "**/*.fragment.css", "**/*.fragment.md", "**/*.layout.js", "**/*.script.js", "**/*.styles.js", "**/*.layout.ts", "**/*.script.ts", "**/*.styles.ts"]
}
client-globals.d.ts
import '@small-web/kitten-types/client.d.ts'
export {}
HTML
You work with HTML in Kitten using Kitten’s html tagged template string format that is exposed at kitten.html.
e.g., Here’s a simple page route that prints “Hello, world!”:
export default function () {
return kitten.html`
<h1>Hello, world!</h1>
`
}
Put the above code into a file called index.page.js (or index.page.ts), run kitten in that directory, and navigate to https://localhost in your browser to see it work.
To learn more about Kitten HTML, see the Dynamic Pages tutorial.
Kitten has a semi-forgiving HTML parser.
XML-style closing tags are not required for regular HTML tags.
For example, you can use
<img>instead of<img />.For custom Kitten components, you must close your tags.
So, for example:
- Valid:
<${myComponent} /> - Valid:
<${myComponent}>Slotted content</> - Invalid:
<${myComponent}>
- Valid:
The parser will make a best-effort to close unclosed tags.
So, for example, it will replace
<p>Hellowith<p>Hello</p>but it’s not foolproof.You will get an unexpected close tag error if you put flow content where phrasing content is expected (e.g., a
<div>inside a<p>tag, etc.)Comments in HTML are stripped from the final output.
There’s currently no way to include comments in the markup generated by Kitten.
Interpolated values
Kitten uses regular JavaScript tagged template strings for HTML templates (kitten.html). So the way you get dynamic values into templates is through string interpolation.
String interpolation, without guardrails, is the easiest way to open your web app up for Cross-Site Scripting (XSS) / injection attacks. So Kitten does everything it can to make sure that values are interpolated safely everywhere.
Kitten treats all interpolated values (anything within a ${…}) as text, and ensures that each one is safe for the location the interpolation targets.
HTML created using kitten.html is trusted and kept as HTML when interpolated into other HTML templates.
All other values are escaped by default so that untrusted content cannot add markup or execute code on your page.
If you have a value you trust (e.g., because you’re sure you created it or that you’ve otherwise manually sanitised it), you can tell Kitten “I trust and vouch for this value so interpolate it as-is” by calling the kitten.markAsTrusted() method on the value.
When interpolating array values, the behaviour depends on the location of the interpolation:
In text nodes, an array’s elements are handled separately and according to the general rules for interpolated values:
kitten.htmlrenders as markup and strings are escaped.In attributes, URLs, scripts, and tags, the elements of an array are joined and treated as one string.
Here are some examples of HTML being generated and interpolated into templates:
kitten.html`<ul>${items.map(item => kitten.html`<li>${item}</li>`)}</ul>`
kitten.html`<p>${isNew ? kitten.html`<b>new</b>` : ''}</p>`
The return value of kitten.html is considered markup in text nodes only. In an attribute, a script, or tag position, it is joined, if necessary (if it has multiple top-level DOM nodes) and treated like a string. (Its type, however, is not String, so to call a string method on such an interpolated value, you must cast it, i.e., String(myKittenHtml).)
To safely interpolate untrusted markup into your page (e.g., from other people, an API, etc.), use kitten.safelyAddUntrustedHtml.
To join kitten.html values, do not use the + operator, as that will give you a plain string, which is escaped. Instead, place them in an array and interpolate the array into your page (e.g., [someHtml, someOtherHtml]).
Values interpolated into JavaScript attributes (on*, hx-on*, Alpine’s @, :, and x- attributes, or following the javascript: prefix of a URL attribute) or into scripts must either be a number, a boolean, null, or a value from kitten.markAsTrusted. Anything else, including a string, an array, an object, and undefined, throws when the page renders.
If you want to interpolate a string into an HTML attribute, put it in a data-* attribute and read it back in the handler.
e.g.,
kitten.html`<button data-name=${name} @click='greet($el.dataset.name)'>Greet me!</button>`
kitten.html`<button data-name=${name} onclick='greet(this.dataset.name)'>Greet me!</button>`
kitten.html`<script id='js' data-post-id=${postId}>go(document.getElementById('js').dataset.postId)</script>`
kitten.markAsTrusted
kitten.markAsTrusted(value) takes a string or an array of strings and marks them as trusted.
Interpolating a trusted value into kitten.html inserts the value without escaping it and bypasses all security checks in text and scripts. In attribute position it is attribute source, except on a component tag or next to other text, where it must be one attribute name, as a string must. In an attribute value it skips the URL and JavaScript checks and is escaped like any attribute value. In tag position it must be one element name, as a string must. Only pass it a string you wrote or trust.
import fs from 'node:fs'
const logo = fs.readFileSync(new URL('./logo.svg', import.meta.url), 'utf-8')
kitten.html`<a href='/'>${kitten.markAsTrusted(logo)}</a>`
Objects
You can pass an object to data, hx-vals, hx-vars, hx-headers and hx-request, and to a script of type application/json, application/ld+json, importmap or speculationrules. Kitten writes it as JSON, and htmx or your own JSON.parse reads it back as plain data. Nothing inside it ever runs.
kitten.html`<button name='deletePost' data=${{ id: post.id }} connect>Delete</button>`
kitten.html`<script type='application/json' id='post'>${{ postId, title }}</script>`
You cannot pass an object to x-data, x-bind or any other Alpine.js attribute. Alpine runs some of the strings inside those objects as code: an init or destroy property of x-data, and every property of an x-bind object. If one of those strings came from another person, Alpine would run their text. So Kitten refuses an object there, the same way it refuses a string. Put each value in a data-* attribute and read it from $el.dataset inside the Alpine expression:
kitten.html`<div data-name=${name} x-data='{ name: $el.dataset.name, open: false }'>`
Code
In a JavaScript attribute, a script, data, or an hx- object attribute, a kitten.markAsTrusted value is code, inserted as written, and so is a kitten.js result. So is a string spread under a JavaScript attribute name, data, or the hx- object attributes when it was written in the template on the component’s tag (see Spreads). kitten.js takes no interpolated value. A string in the filter of trigger or hx-trigger (click[…]), or in the morph configuration of morph, swap, hx-swap, hx-swap-oob, or swap-target (morph:…, config:…), throws. Put such a string in a data-* attribute.
URLs
A URL attribute (href, src, action, formaction, poster, and the other single-URL attributes) whose scheme comes from a value, or from a spread of a value that was not written in the template on the component’s tag, must not be javascript:; such a value renders as #kitten-url-scheme-not-allowed. A javascript: URL from another person ran when clicked. Any other scheme is handed to the browser or the operating system, as an https: link to any site is, so a data: image, a tel: number, or your app’s own scheme renders as written. A scheme written in the template, such as href='file://${path}', is unchanged, and so is one written in the template on a component’s tag when the component spreads its props; after javascript:, a value follows the rule for JavaScript attributes. A component that renders a prop as the whole URL (href=${props.href}) renders a javascript: value as #kitten-url-scheme-not-allowed even when you wrote it on the component’s tag; pass it to kitten.markAsTrusted where you write the tag.
Attribute position
A string in attribute position (<button ${value}>) must be one attribute name. true, a number, and an object throw; false, null, undefined, and the empty string render nothing. For attribute source, pass a kitten.markAsTrusted value (${kitten.markAsTrusted('disabled hidden')}); for values, pass a spread (...${{ href: url }}). On a component tag, a value in attribute position must be one attribute name, including a kitten.markAsTrusted value.
Tag position
A value in tag position (<${tag}>) must be a component or one element name. false, null, undefined, and the empty string render the children alone; any other value throws. Every element name is accepted there, script included; never let other people choose the tag.
Components and fragments
A component receives its props as written and escapes them when it renders them. A prop that mixes text and a value arrives as one string. A .fragment.md inserts each value as kitten.html does; markup there must be a kitten.html result or a kitten.markAsTrusted value.
Spreads
A string spread onto an element under a JavaScript attribute name (on*, hx-on*, @, :, x-) or an object attribute name (data, hx-vals, and the others) throws unless it was written in the template on the component’s tag or passed to kitten.markAsTrusted. A component that forwards its props with ...${props} still forwards a handler written on its tag, such as <${Button} onclick='save()' />. A record from a request cannot set one: <${Card} ...${record} /> throws when record has an onclick string.
style, srcdoc and kitten.css
A value in style or srcdoc is escaped twice. A quote, <, or > in it reaches the CSS or the frame as an entity; for a value you trust, pass a kitten.markAsTrusted value, which is escaped once. kitten.css refuses a value containing <.
What Kitten does not check
Kitten does not check a value that a handler reads from dataset. Alpine’s $watch, an x-bind object and a bound :on* attribute run such a value as code, and x-html and innerHTML render it as markup.
The page tag
You’ll notice in the Hello, world! example that we returned just a <h1> tag instead of the full HTML structure for the page.
Kitten has a default template that creates the boilerplate of an HTML page for you (the whole structure, starting with <!doctype html><html lang='…'><head>…, etc.)
To add to parts of this template you can use two mechanisms:
- The
<page>tag - Special page slots
A head slot overrides Kitten’s own head tags one property at a time; see Special page slots.
The page tag takes the following attributes:
HTML attributes
These customise the <html> tag:
lang(defaulten)
Head attributes
These customise the <head> tag:
title: sets contents of<title>tag (default: the text of the first<h1>in the page or, if there isn’t one, a title made from your project folder’s name and the page’s path, e.g., “My App – About”)charset: sets contents of<meta charset='…'>tag (default:UTF-8)viewport: sets contents of<meta name='viewport' content='…'>tag (default:width=device-width, initial-scale=1.0)icon: sets contents of<link rel='icon' href='…'>(default:data:,)
Body attributes
These customise the <body> tag:
bodyClass: setsclass=…on body (default:'')
Library includes
These attributes trigger library includes:
htmx: includes Kitten’s internal version of htmxidiomorph: includes Kitten’s internal version of the htmx idiomorph extensionws: includes Kitten’s internal version of the htmx WebSocket extensionalpine: includes Kitten’s internal version of Alpine.jscss(includes the Water semantic CSS library)
Libraries like htmx, idiomorph, etc., are automatically added to live pages (stateful pages, and stateless pages that export event handlers). In other words, in daily usage, you should not have to specify the htmx, idiomorph, or ws tags manually.
Other attributes
These attributes customise other Kitten-specific behaviour:
syntax-highlighter: turns on syntax highlighting for the page (includes the default syntax highlighting themes – see below – that are applied to any code blocks marked up in HighlightJS. Kitten’s Markdown parser automatically generates code fences with HighlighJS markup).syntax-highlighter-theme-light: sets thehrefof the lightmode Highlight.js stylesheet to use. (default: ‘/🐱/library/highlight.js/styles/measured-light.css’)syntax-highlighter-theme-dark: sets thehrefof the dark mode Highlight.js stylesheet to use (default: ‘/🐱/library/highlight.js/styles/measured-dark.css’)
See the Syntax Highlighting section for more details.
Special page slots
Kitten moves the contents of a <content for='…'> tag out of its place in your page and into a slot in Kitten’s page template.
Use the slot property names on kitten.page as for values:
kitten.page name | Value | Where the content goes |
|---|---|---|
html | HTML | In place of the opening <html lang='…'> tag |
head | HEAD | At the end of <head>, before the styles collected from your page |
startOfBody | START_OF_BODY | At the start of <body>, before your page |
endOfBody | END_OF_BODY | At the end of <body>, after Kitten’s own elements |
These aliases have the same values: HTML and Html; HEAD and Head; START_OF_BODY, StartOfBody and startofbody; END_OF_BODY, EndOfBody and endofbody.
(Kitten tries to be forgiving.)
Although not recommended, you can also provide the value directly as a string literal. e.g., for='HEAD'. If doing this, note that the value must be all uppercase and, when it contains multiple words, must be underscore-separated. e.g., for='head' does not match the HEAD slot, and its content is not rendered.
You can target the same slot from several <content> tags. Their contents are added in the order they appear in the source.
A head slot overrides properties in Kitten’s own default head tag. (It doesn’t overwrite the entire default head tag.) In other words, if the contents of a head slot contain <title>, viewport, icon or charset, Kitten replaces its own default tag with the one provided. Other properties are still added from a <page> tag, if one exists. And any not overriden property falls back to Kitten’s defaults.
For example, this page sets its title in the head slot:
export default () => kitten.html`
<h1>Hello</h1>
<content for='${kitten.page.head}'>
<title>Special page slots</title>
</content>
`
See the special page slots tutorial.
Client-side scripts
Kitten loads client-side libraries used by your page (htmx, Alpine.js, etc.) in the page’s <head> with defer. This means they don’t block your page from rendering. It also means none of them exist until the browser parses the whole page.
Scripts in your page
If a script uses a Kitten library, or anything that another script defines, make it a module:
<script type='module'>
htmx.config.scrollBehavior = 'smooth'
</script>
Modules, inline or loaded via the src attribute, run after the libraries, in the order they appear on the page. By the time they run, the whole page is ready.
A plain <script> runs as soon as the browser parses it, before any libraries exist. One use case for such scripts might be to include third-party libraries or widgets.
The above script execution rules hold true regardless of where the script is physically-located on the web page, including in the head, startOfBody, and endOfBody special page slots. The slots change where your content goes, they do not determine when scripts in your content are run by the browser.
Once all modules have run, the browser fires the DOMContentLoaded event and the page becomes active: Alpine.js starts, htmx attributes start working, and the page’s socket starts connecting.
Note that a module’s top-level declarations are private to it. If your markup needs to refer to a value from a module (e.g., from an onclick handler, as in the example below), add it to globalThis:
<script type='module'>
globalThis.greet = () => alert('Hello!')
</script>
<button onclick='greet()'>Greet</button>
Including custom client-side code in your server-side page files (.page.js files) is cumbersome. Since your kitten.html templates are already JavaScript template strings, you will have to escape certain bits of code (e.g., code that interpolates values at runtime in the client) and you have to remember to use a module script, as you saw above. Kitten provides you with a simpler convention with its client scripts feature.
The page’s client script
You can put a page’s client-side code in a .client.js (or .client.ts) file with the same name as the page (e.g., index.client.js for index.page.js or about.client.js for about.page.js). This is known as a client script file.
Kitten loads a client script file as a module after the libraries, so you don’t have to add a <script> tag for it.
You also don’t have to worry about escaping any code.
While you cannot interpolate server-side values directly into client-side scripts, you can interpolate them into data-* attributes in DOM elements in your server-side pages and read them back from your client side script:
index.page.js:
export default () => kitten.html`
<p id='rendered' data-time='${new Date().toISOString()}'></p>
`
And index.client.js:
const rendered = document.getElementById('rendered')
const time = new Date(rendered.dataset.time).toLocaleTimeString()
rendered.textContent = `The server rendered this page at ${time}.`
To run code once the page is active, use await kitten.ready.
On a live page, kitten.ready resolves when the page’s socket opens, so kitten.trigger() and streamed updates work from that line on. On any other page, it resolves at DOMContentLoaded. (If you send a message before the socket opens, Kitten queues it and sends it when the socket opens.)
To configure a library before the page becomes active, do it before the await.
For example, index.client.js:
htmx.config.scrollBehavior = 'smooth'
await kitten.ready
const status = document.getElementById('status')
status.textContent = 'Ready'
kitten.trigger(status, 'ping')
Just like everywhere else in Kitten, you can also write your client scripts in TypeScript. When you do, Kitten will automatically transpile it and serve it as JavaScript for you. Just remember to give it the client.ts extension instead (e.g., index.client.ts). Also see: TypeScript.
A navigation action that swaps just the body of a page (e.g., a link with hx-boost or an HX-Location response) preserves the current page’s libraries and client script. If the page you’re navigating to requires different libraries, its own client script, or a page socket, use full navigation instead.
Kitten serves any .js or .ts file that isn’t a route or a dependency (see Valid file types) to the browser. Put server-only code that isn’t a route, a component, or a layout in a .script.js or .script.ts file to avoid it being served as client-side JavaScript.
Request and response helpers
Kitten has a number of request and response helpers defined to make your life easier.
You use two of them, response.badRequest() and response.get() in the authentication tutorial.
Request
is (array|string): returns true/false based on whether thecontent-typeof the request matches the string or array of strings presented. This is used internally for Express Busboy compatibility but you might find it useful in your apps too if you’re doing low-level request handling.
Response
withCode(code, [body]): Shorthand for setting.statusCodeonresponseand callingresponse.end()with an optional body. Useful when returning custom HTTP Status Codes like the ones used in the Small Web Protocol.ok(body?): Returns 200 OK.created(body?): Returns 201 Created.json (data): Returns a JSON serialised response of the passed data.jsonFile (data, fileName?): Triggers a download of the passed data in JSON format (default file name isdata.json).file (data, fileName?, mimeType?): Sends downloadable file (default name isdownloadand default MIME type isapplication/octet-stream).sendFile (filePath, options?)(async): Serves the file atfilePathwith Range request support, and answers 404 when there is no file there.options.typeis the content type (defaultapplication/octet-stream),options.fileNamethe name the browser saves the file as,options.attachment(true) makes the browser download it, andoptions.headersadds headers to the response. The headers are sent before it returns, and the promise resolves when the response has ended.get (location),seeOther (location): 303 See Other redirect (always uses GET).redirect (location),temporaryRedirect (location): 307 Temporary Redirect (does not change the request method).permanentRedirect (location): 308 Permanent Redirect (does not change the request method)badRequest (body?): 400 Bad Request.unauthenticated (body?),unauthorised (body?),unauthorized (body?): 401 Unauthorized (unauthenticated).forbidden (body?): 403 Forbidden (request is authenticated but lacks sufficient rights – i.e., authorisation – to access the resource).notFound (body?): 404 Not Found.error (body?),internalServerError (body?): 500 Internal Server Error.
Streaming HTML
Kitten gives you a simple-to-use event-based HTML over WebSocket implementation called Streaming HTML (because you’re streaming HTML updates to the client) that you can use to build web apps.
See the Streaming HTML tutorial for details, and Event handlers for the rules of event handling.
Kitten components
Stateless components
The simplest Kitten component is any function that returns kitten.html.
We call this a stateless component and it’s essentially a render function.
A stateless component can be as simple as:
const sayHello = () => kitten.html`
<h1>Hello</h1>
`
Of course, components without props are not very useful, so component functions usually take a parameter object with properties (or “props”, for short):
const sayAnything = ({ thingToSay = 'Hello' } = {}) => kitten.html`
<h1>${thingToSay}</h1>
`
console.log(kitten.html`<${sayAnything} thingToSay='Goodbye' />`)
The above example outputs:
<h1>Goodbye</h1>
To learn more about Kitten components, see the following tutorials:
Stateful components
Stateful components are KittenComponent subclasses. Idiomatically, you author your components to extend kitten.Component (which is a reference to the KittenComponent class on the global kitten object).
While stateless components are simple to use, lightweight, and perform well, Kitten’s unique Small Web design means that there are certain routes in your apps that will only ever be hit by one person: the person who owns the web site or app you’re building. This is an amazing simplification compared to Big Web apps that means that you can simplify your authoring experience by maintaining state throughtout the render hierarchy of your interaces (as you would when building a desktop or mobile interface).
Stateful components are far more ergonomic when authoring using Kitten’s Streaming HTML workflow. They make it more ergonomic to listen for events from live pages and carry out precise updates, morphing small bits of your interface in response to events and doing so in a maintainable manner by breaking up your interface up into small, well-encapsulated components.
While stateful components are designed for use in your authenticed routes for the person who owns the Small Web site or app you’re authoring, this shouldn’t put you off of using them for public routes, especially given the ease of authoring they provide. Remember, we’re working with Small Web numbers. If you build a public route in your app using stateful components and then notice performance issues, you can always refactor them using stateless ones. (It’s usually a bad idea to prematurely optimise and doubly so when speaking about a Small Web context.)
Here’s an example of a stateful Kitten component that has a child component (not shown; but inferred to also be a stateful component).
import Child from './Child.component.js'
export default class ParentComponent extends kitten.Component {
// Child will be strongly-typed via inference.
child
constructor () {
super()
this.child = this.addChild(new Child())
}
override html () {
return kitten.html`
<div id='parent'>
<${this.child} />
</div>
`
}
}
When adding child components, you call the component’s addChild() method from your component’s constructor or later on in your component’s lifecycle. The addChild method handles creating the parent/child relationship as well as firing necessary lifecycle handlers on the child at the right time.
If the html() render function looks familiar, it’s because it’s basically the entirity of a stateless component. In a stateful component, your render function should simply be rendering the current state of your component as reflected its instance state and/or in the persisted state of your application in its database.
Note that although you are passing a reference to your KittenComponent subclass in the kitten.html, it still works as Kitten knows to use its component property to get a reference to its html() render method. You can, of course, manually pass a reference to it and that will also work. So this is also valid, and equivalent in result to the code above, but more verbose and unnecessary:
override html () {
return kitten.html`
<div id='parent'>
<${this.child.component} />
</div>
`
}
See the type safety section for how to get autocompletion when referencing the kitten global.
For a real-world example of the use of the kitten.Component class – and its page-level equivalent, kitten.Page – see the code for the Internal Database page of Kitten’s own Settings app.
Event handlers
Pages and stateful components handle events from the browser in on… handlers.
Naming
A connected element (an element with a
connectattribute) with attributename='update'emits anupdateevent and Kitten routes this to anonUpdate()handler.An element without a
nameattribute emits an event named after itsidattribute. If the element has neither, Kitten logs an error and drops the event.Kitten ignores everything after a colon in the name. e.g.,
name='update:first'emits an event calledupdate.A handler has three positional parameters: the event’s data, the WebSocket message event and the message headers. e.g.,
onUpdate(data, event, headers). In htmx messages,headers['HX-Trigger-Event']contains the name of the DOM event that triggered the message.
Where handlers live
On a stateful component, a handler is a method. The event is routed to the nearest component that contains the element that emitted it.
On a stateless page, a handler is an exported function. Kitten binds it to the live page, so
thisrefers to thekitten.Page. Use afunctiondeclaration or an expression, not an arrow function (arrow functions ignore the binding).On a stateful page, an unhandled event doesn’t fall back to the page. When a component that contains the element cannot be found, Kitten logs a warning. The markup for a page that handles events must have a single root element. Otherwise, Kitten logs an error. If the component that contains the event source element is not added to the page using
addChild(), Kitten logs a warning.
A good smell for when to refactor a stateless page into a stateful page is if your page exports lots of on… event handlers and they start to become unmanageable or unsightly, or if each handler has to work out which part of the page its event came from. In a stateful page, you can split the page into stateful components, and Kitten routes each event to the component that contains the element that emitted it.
Lifecycle hooks
onConnect(pageDetails)called when the page socket connects. It’s also called when a component that’s alerady connected is added to the page.onDisconnect(pageDetails)called when the page socket disconnects and when the component is removed.onAddToParent()called whenaddChild()adds the component to its parent.pageDetailsis{ page, request, response }.connect,disconnect, andaddToParentare reserved names. Don’t use them as event names.
Component helpers
addEventHandler(target, eventName, handler)listens foreventNameon any event emitter, withthisbound to the component. Kitten removes the listener when the component disconnects.addPageEventHandler(eventName, handler),addSessionEventHandler(eventName, handler), andaddGlobalEventHandler(eventName, handler)listen on the page, on the session, or onkitten.events, withthisbound to the component. Kitten removes the listener when the component disconnects.emitPageEvent(eventName, ...args),emitSessionEvent(eventName, ...args)andemitGlobalEvent(eventName, ...args)emit an event on the page, on the session, or onkitten.events.update()renders the component again and streams it to the page, morphing it into place. The component must have a single root element.sendToPage(html)streams Kitten HTML with a single root element to the page. It’s morphed in place unless its root element overrides the default behaviour by including aswap-targetattribute (syntactic sugar forhx-swap-oob) or is a<script>.remove()removes the component from the page and from its parent, disconnecting it.
Client side
kitten.trigger(this, 'eventName', data) emits an event from your own client-side JavaScript. The first argument is the element the event originates from (its event target). Kitten routes the event to the component that contains that element.
In the method signature shown above, this refers to the element itself in an inline event handler. You can also use a reference to any other element when calling it, say, from a global script.
kitten.ready is a promise that resolves when the page is active: when the page’s socket is open on a live page, and at DOMContentLoaded otherwise. See Client-side scripts.
Listening to all events
Kitten also emits all events on kitten.events as kittenPageEvent and kittenPageEvent-<pageId>, with the following data: { page, name, handler, id, target, data, headers, event }.
Example
A counter component that changes a persisted count when you press its buttons:
// Initialise the persisted counter object, if necessary.
kitten.db.counter ??= { count: 0 }
class Counter extends kitten.Component {
override html () {
return kitten.html`
<div>
<div aria-live='assertive'>${kitten.db.counter.count}</div>
<button name='update' connect data='{value: -1}' aria-label='decrement'>-</button>
<button name='update' connect data='{value: 1}' aria-label='increment'>+</button>
</div>
`
}
onUpdate (data: { value: number }) {
kitten.db.counter.count += data.value
this.update()
}
}
See stateful pages and components in the Streaming HTML tutorial for a walkthrough.
Icons

Kitten includes a subset of the Phosphor icon set by Helena Zhang and Tobias Fried as Kitten components.
The main difference with the original set is that some icons have been removed and some have been renamed to bring the library in line with the Small Technology Principles.
Specifically:
All brand icons for Big Tech/Silicon Valley/surveillance capitalists/people farmers have been removed.
The words ‘user’ and ‘users’ have been replaced with ‘person’ and ‘people’. (In Small Tech and on the Small Web we don’t have users, we have people, and we treat them as such.)
e.g., The Phosphor icon called
user-checkexists as a Kitten component atkitten.icons.personCheck. The icon “user” has been renamed to “person-close-up” (as there is already a “person” icon) and may be found atkitten.icons.personCloseUp.The BTC icon has been removed (proof of work; environmental concerns).
Finding icons
In your Kitten app, you can access the icons as stateless Kitten components at the following namespace:
kitten.icons
In that namespace, you browse the icons in three ways:
- Directly, by name, e.g.,
kitten.icons.cat - In categories, e.g.,
kitten.icons.categories.nature.cat - Using tags, e.g.,
kitten.icons.tags.kitten.cat
The categories and tags objects are authoring-time aids. While you can use them in your code, it’s better practice to reference the icons directly from the root namespace. These two properties are marked as unenumerable so they do not pollute the namespace and will not show up if you’re iterating over all the icons in the root namespace.
To get autocompletion in your editor, your editor must support the TypeScript language server (any modern code editor worth using will e.g., Helix editor, etc.) Beyond that, please see the type-safety section for how to set up your project so it uses Kitten’s types.
Using icon components
You can use the components in your kitten.html as you would any other Kitten component.
e.g., A simple Kitten page that displays a large, pink cat icon in duotone:
export default function () {
return kitten.html`
<${kitten.icons.cat}
size=40%
weight=duotone
colour=deeppink
/>
`
}
As the icons are Kitten components, you can customise how they appear by passing properties (“props”) to them:
alt: Alternative text (alt-text). Provide this to explain the purpose of the icon for people who use screen readers. If no alt text is provided, it will default to the name of the icon.colour: Pass a CSS colour. Defaults tocurrentColor, which will pick up the colour of its context.weight: One ofregular,light,thin,bold,fill, orduotone. Defaults toregular.size: Pass a CSS measurement to use as the width/height (the icons are square). Defaults to1em.mirror: Pass a boolean. Mirroring can be useful in right-to-left layouts. Defaults tofalse.
And other props you provide will be passed as attributes to the SVG tag of the icon.
Extending icon components
You can extend the SVG (e.g., to add animation, etc.) by slotting any valid SVG content into it.
e.g., This makes the cat into a Cheshire cat (fades in and out):
export default function () {
return kitten.html`
<${kitten.icons.cat}
size=40%
weight=duotone
colour=deeppink
>
<animate
attributeName="opacity"
values="0;1;0"
dur="3s"
repeatCount="indefinite"
/>
</>
`
}
While the above example is good for a one-time use modification, you can, of course also make a reusable cheshireCat component.
Here’s one that has all the same defaults as the one in the above example but is fully configurable via props.
Notice how it passes any other props it receives to the base component it’s extending via composition.
const cheshireCat = ({duration = 3, minOpacity = 0, maxOpacity = 1, ...props}) => {
return kitten.html`
<${kitten.icons.cat} ...${props}>
<animate
attributeName="opacity"
values="${minOpacity};${maxOpacity};${minOpacity}"
dur="${duration}s"
repeatCount="indefinite"
/>
</div>
`
}
export default function () {
return kitten.html`
<${cheshireCat}
size=40%
weight=duotone
colour=deeppink
/>
`
}
Displaying all icons
Here’s a simple example that displays all the icons, separated alphabetically, with their component names appearing in a tooltip when you hover over them.
You can find a screenshot of it at the top of this section.
export default function () {
return kitten.html`
<page css>
<markdown>
# All icons
These are all the icons in the [code]kitten.icons[code] namespace.
</markdown>
${Object.entries(kitten.icons).map(([name, icon]) => kitten.html`
<${icon} size=2em weight=duotone colour=deeppink>
<title>${name}</title>
</>
`)}
`
}
Markdown support
Kitten’s Markdown support comes from markdown-it.
Kitten supports a very rich set of Markdown features including:
typographical niceties (like converting typewriter quotes “” into curly quotes “”, etc.)
adding classes, identifiers and attributes to your markdown
e.g.,
# Classy heading {.myClass #identifier attribute=value attribute2="spaced value"}A heading that contains a value gets the value’s index in its
id: with no value before it,# Hello ${name}has theidhello-0. To build theidfrom the value, write it:## My ${name} {#my-${kitten.slugify(name)}}kitten.slugifytakes only a string. Anidwritten this way is never numbered; give each heading a different one.e.g.,
This is my [classy span]{.myClass} and I love it!e.g.,
Inline images  are rendered normally, using just an `<img>` tag. ')e.g.,
Inline footnotes rock.^[Inline footnote are easy to write and update.]
When writing Markdown, please indent the contents of your code fences to follow the natural indentation rhythm of your page.
Specifically, do not pull them flush left in an effort to remove trailing whitespace. Kitten does this for you, intelligently, when creating your preformatted code areas in HTML.
If you do pull the code fence contents outside of the natural indentation rhythm of the page, you will get a render error.
You can use Markdown in your Kitten apps in a variety of ways:
Markdown pages (.page.md files).
You can create whole pages using Markdown by placing your Markdown in page.md files. These pages are transpiled into JavaScript before being rendered into HTML just like regular JavaScript pages (page.js) files.
Markdown’s backslash escapes apply, and \${, \< and \} render ${, < and }, inside code too.
Your Markdown pages can have front matter in YAML format.
Kitten’s YAML parser is based on the Node yaml module and you can use it directly in your own Kitten apps by referencing it from kitten.yaml.
Front matter
Kitten’s YAML front matter supports some special properties. Specifically:
script (literal block scalar)
You can include arbitrary JavaScript in a script block.
For example, here’s the Kitten Count example as a Markdown page with a script block:
---
script: |
let count = 1
---
# Kitten count
${'🐱️'.repeat(count++)}
As this example shows, you can use JavaScript string interpolation inside of Markdown pages just as you would in a regular JavaScript file.
layout (string)
Specifies the layout template to use for the Markdown page.
The value for the layout property is a string that contains the relative path to the layout template (.layout.js file) you want to import and use.
Any custom properties in front matter are passed to the layout template as properties.
For example, if your layout template is called main.layout.js and it is located in the layouts/ folder of your project and you want to include it in a page called index.page.md at the root of your project, your front matter might look like this:
---
layout: './layouts/main.layout.js'
title: 'Feed me!'
author: 'Oskar Kalbag'
---
Woof.
And your layout template might look like this:
export default function mainLayout ({ SLOT, title, author } = {}) {
return kitten.html`
<header>
<h1>Oskar’s blog</h1>
<p>I am a dog.</p>
</header>
<main>
<h2>${title} by ${author}</h2>
${SLOT}
</main>
<footer>
<p>PS. Have you fed me?</p>
</footer>
`
}
The title and author fields you see in the example above are custom properties the author wants passed to the layout template.
Stateful Markdown pages
Markdown pages can also be stateful.
There are two rules that determine whether your Markdown page is a stateful page (so you can add and use stateful Kitten components on it):
If the page includes the new
constructor: |section in the YAML front-matter, it is automatically treated as stateful.If the page is specifically marked using the
stateful: trueflag in the YAML front-matter.
If a stateful Markdown page has a layout, the layout must also be stateful (a kitten.Page or kitten.Component subclass). Otherwise, Kitten throws an error when it renders the page.
A quick example:
---
title: An interactive markdown page
layout: ./index.layout.js
script: |
import Reaction from './Reaction.fragment.js'
constructor: |
this.reaction = this.addChild(new Reaction())
---
# Hello!
What do you think of this page?
<${this.reaction} />
Custom properties in front matter
Any properties other than the special ones listed above are passed to your page’s layout template (if it has one) as props.
In a stateless Markdown page, Kitten also passes two built-in properties to the layout template:
request: reference to the KittenRequest object. (A Node.js http.IncomingMessage object as as extended by Polka and then again by Kitten. The important Kitten addition is thesessionproperty that refers to the current session.)response: reference to the KittenResponse object. (A Node.js http.ServerResponse object as extended by Kitten. Kitten mixes in a number of useful response helpers.)
This is because there is no way for you to pass them to your layout yourself in Markdown.
In a stateful Markdown page, Kitten passes your custom properties to your layout component’s constructor (as an object) and to its html() method. Your layout can reach the request and response objects via this._page.request and this._page.response.
Markdown fragments
You can place pieces of Markdown into Markdown fragment files (fragment.md).
Markdown’s backslash escapes apply, and \${, \<, and \} render ${, <, and }, inside code too.
Unlike Markdown pages, Markdown fragments do not support front matter. A fragment can interpolate its props (${props.name}) and its slots, both default and named. The <div> that wraps the fragment has the props spread on it (<div ...${props}>). Pass class or id to set its class or id.
Markdown in Kitten HTML tagged template strings
Finally, you can embed Markdown directly in your Kitten HTML tagged template string by surrounding your Markdown content between <markdown>…</markdown> tags.
e.g.,
export default () => kitten.html`
<h1>This is HTML</h1>
<markdown>
- _This_
- is
- __Markdown!__
</markdown>
<footer>
<p>This is more HTML</p>
</footer>
`
Unlike HTML, Markdown is whitespace-sensitive so make sure you indent your code properly or it will get parsed incorrectly.
You can see some of the Markdown features mentioned here demonstrated in the examples/components and examples/markdown folders of the Kitten examples, as well as in the source for the Kitten web site itself.
Syntax highlighting
Syntax highlighting in Markdown is provided via Highlight.js.
To turn on syntax highlighting for your page, include a <page> tag in your file that includes the syntax-highlighter attribute:
<page syntax-highlighter>
The default themes for light and dark mode are the Measured Light and Measured Dark accessible syntax highlighting colour scheme implementations for Highlight.js.
You can override this setting by setting the syntax-highlighter-theme-light and syntax-highlighter-theme-dark attributes of your <page> tag to the absolute or relative path to the respective theme CSS file.
View the full list of default Highlight.js themes.
See the <page> tag reference for more details.
Certain versions of the 1Password password manager browser extension appear to rewrite the Highlight.js class names in Kitten pages, thereby preventing the syntax highlighting from working. If you encounter this, please let the 1Password folks know so they can fix their code.
Symlinks
If you have symlinks with extensions that Kitten knows how to route, your symlinks will get routed as if they were regular files.
e.g., You have a README.md file and you want the index of your page to display it without redundancy. Create a symlink inside your project folder:
ln -s ./README.md index.page.md
Now, when you hit the index of your site, you will see the README file.
Kitten will only route symlinks that point to files in your project directory or to folders under it, not outside. (Otherwise, it would open the door to a whole family of potential security issues.)
Deploying a Kitten application
To deploy your app as a service, you use the deploy command from a regular account (not root) under Linux:
kitten deploy <httpsGitCloneURL>
For example, the following will create and run a production server of the Persisted Kitten Chat example, as hosted on my personal Codeberg account at my hostname.
kitten deploy https://codeberg.org/aral/persisted-kitten-chat
As Kitten runs in an unprivileged account, systemd must let services for that account remain running when you sign out of your server (otherwise your Kitten server will stop when you exit your ssh session or log out of your server). kitten deploy enables this (lingering) for the account for you.
If it can’t, it shows a warning with the command to run yourself. e.g., If you installed Kitten under a Linux account called kitten:
sudo loginctl enable-linger kitten
Note that the name you use in the enable-linger command is the name of the Linux account, not the Kitten process/systemd unit file name. If you deployed a Kitten app from a Linux account called aral, you would instead type sudo loginctl enable-linger aral.
Kitten will not automatically create an alias for www for you, pass --aliases=www.<hostname> (or the shorthand, --aliases=www) if you want that. You can, of course, also list any other subdomains other that www that you want Kitten to serve your site/app on in addition to the main domain.
If your app uses node modules and a package-lock.json exists, Kitten runs npm ci on your project and on any app modules your project might have. Without a package lock file, Kitten runs npm install instead.
Updating a deployed Kitten application
How your deployed app is updated depends on who it is for.
If you are making a Small Web app for everyday people, declare the Kitten API version it supports in its package.json (see Versioning). Kitten then checks for updates to your app and to itself, installs them together, and rolls back an update that does not start.
If you are building something for yourself and are happy to update the site by hand, you can do so from the App Settings page of your Kitten site (/🐱/settings/app/).
If you want your Kitten site to update every time you push to its tracked branch, set up a webhook.
When Kitten starts up, it runs npm ci in your app’s folder and in each of its app modules where the packages in the folder’s package-lock.json differ from the record npm keeps at node_modules/.package-lock.json (or where there is no node_modules folder). If a folder has no package-lock.json, Kitten runs npm install there instead.
🪝Webhook
You can set up a webhook on your remote Git source code repository that updates the site whenever you push to its tracked branch.
You can find your webhook URL and webhook secret on the App Settings page of your Kitten site (/🐱/settings/app/).
If your domain changes (i.e., if you point a new domain to your site using Kitten’s Settings panel), remember to update your webhook at your git host to use your new Webhook URL.
Your Kitten site expects the webhook secret in either the Authorization header or in the body of a POST request in a field called secret (the body should be application/x-www-form-urlencoded).
e.g., Instructions for Codeberg:
- From your project’s repository, follow the Settings link.
- In the Settings menu, select Webhooks.
- Press the Add webhook button.
- From the button’s pop-up menu, select Forgejo.
- Enter the Webhook URL from below into the Target URL field.
- Leave the HTTP method set to
POST. - Set the POST content type to
application/x-www-form-urlencoded. - Leave the Secret field empty.
- Set Trigger on to
Push events - Set Branch filter to the branch Kitten tracks:
releaseif your repository has one, your default branch otherwise (the App Settings page shows which) - Enter the Webhook secret from below into the Authorization header field.
- Leave the Active checkbox checked.
- Press the Add webhook button.
Once the webhook has been added, your site updates whenever you push to the tracked branch.
Each push runs the same update as Kitten’s automatic updates. We install your app’s dependencies before switching to the new commit and install the newest Kitten release for the API version declared by the commit (if that’s a newer release than the one you’re running), and roll both back if the new version fails to start or if its home page responds with a server error. (If the package.json file in the commit doesn’t declare an API version, we install the newest release for the API version you’re running.) An update that fails is not retried (see Versioning). Fix the issue and push again to trigger another update attempt. You can see the outcome of each update in the update history on the Kitten Settings page.
A webhook also works for an app that declares engines.kitten (see Versioning, below). It updates your own server as soon as you push (e.g., for a security fix), while other people’s servers install the same update at their next automatic check.
This is a feature that will be useful to developers who are deploying their own sites and apps for their own use as opposed to developers making apps for use by everyday people who use technology as an everyday thing. For the latter use case, please see Versioning, below.
Versioning
To try out a Kitten app from its git repository without deploying it, use kitten run.
A Kitten app declares the Kitten API version it supports in its package.json file:
{
"engines": {
"kitten": "1"
}
}
The Kitten API version is a whole number that’s incremented when a Kitten release contains one or more breaking changes.
Before you add or update engines.kitten on an existing app, update Kitten locally on your development machine and run the kitten check command. This will report any issues it finds in your codebase that are incompatible with the latest version and suggest fixes (and sometimes it can even fix them for you). Once your app increments its API version, deployed instances of it are automatically upgraded to the newest Kitten release of that version at the next automatic upgrade check.
The tracked branch
A deployed Kitten app pulls in changes from one of two branches in a publicly-readable remote git repository:
The
releasebranch if the repository has oneThe default branch otherwise (likely
main).
Any new commit on the tracked branch is a candidate for installation and upgrade.
For Small Web apps you expect other people to deploy to their own servers, we recommend that you either use a release branch or work in feature branches and only merge into main when you want to make a release.
Here’s how you’d release a new version of your app when using a release branch:
git push origin main:release
If your app doesn’t declare an engines.kitten value, deployed apps stay on the API version of the Kitten version they’re deployed with.
To upgrade such an app, you can:
- Push to its tracked branch after setting up a webhook in its Kitten Settings
- Use the Update to latest commit button on the App Settings page
- Use the Check now button on the Kitten Settings page
- Run
kitten updateon the server.
Kitten itself still updates automatically on these servers (to the newest release within its API version). To stop it from doing so, set Check for updates to never on the Kitten Settings page. (The four ways of updating listed above still work when you do.)
App version syntax
An app’s version comprises a dash-separated string listing its API version, the first six characters of its commit, and the commit’s date in UTC. e.g. 1-3f9a2c-20261007101500. Apps that don’t declare engines.kitten do not have an API version.
What Kitten installs
Every six hours (the interval is on the Kitten Settings page), a production server asks the distribution server for releases and its app’s repository for the head of the tracked branch, and chooses what to install:
| Situation | What is installed |
|---|---|
| A new Kitten release for the API version your app declares | Kitten, and the new head of the tracked branch when there is one, together |
| Kitten has a release for a newer API version, and the app still declares the current one | Kitten stays on the current API version; the Kitten Settings page shows a notice |
| The head of the tracked branch declares a newer API version, and a Kitten release for it exists | That release and the new head, together, in one restart |
| The head declares a newer API version, and no Kitten release for it exists yet | Nothing for the app; Kitten within the current API version |
| The head declares an older API version than the running Kitten | Nothing for the app; Kitten within the current API version |
The app has no engines.kitten | Kitten within the current API version; on a requested check, the head as well |
An update that fails to start is not tried again; anything newer is. After a Kitten-and-app pair fails, Kitten tries Kitten alone and then the app alone, where the app’s API version allows it. Try again on the Kitten Settings page clears the record of failed updates and checks again.
Rollback
Before Kitten switches to a new version, it copies the app’s databases. The new version then has a limited time to start and answer its home page. If it does not, after two attempts, Kitten points back to the previous version and the previous app commit, restores the databases from the copy, and sets aside the databases the new version wrote in updates/failed-data/ under Kitten’s data folder. Nothing in that folder is ever deleted by Kitten. The Kitten Settings page lists the ten newest updates and rollbacks, with the Kitten version of each update linked to Kitten’s change log as it was at that release.
Uploads are not copied or restored.
A rollback restores the databases as they were before the update and sets aside anything written between the switch and the rollback. If your app changes the shape of its data, write migration code that gives existing data the shape the new version needs.
Signed packages
Kitten packages are signed. Kitten installs an update only when its signature verifies against one of the public keys built into Kitten. The one-line installer does not verify the package it downloads.
Upgrading from API version 0 to API version 1
Kitten’s API version 0 releases (23 April, 9 October, and 21 October 2026) do not automatically update themselves to API version 1. On the 23 April and 9 October releases, kitten update moves Kitten to the 21 October release. On the 21 October release, kitten update reports that Kitten is up to date. To upgrade to API 1, please run the installer again:
curl -sL https://kittens.small-web.org/install | bash
On a development machine the installer replaces Kitten.
On a production server it installs the new version beside the old one and hands over to the new kitten update, which upgrades Kitten, and your app alongside it if the app on the tracked branch declares engines.kitten in its package.json file. It will also automatically roll back if your upgraded app fails to start with the upgraded Kitten.
If your app does not contain an engines.kitten declaration in its package.json, it will not be upgraded to API version 1. In that case, kitten update will exit with error code 1 if the tracked branch has a newer commit, and with success code 0 otherwise.
To prepare an app for API version 1:
Run
kitten checkin its folder and make the changes it reportsSet
engines.kittento"1"in its package.jsonPush that commit to the
releasebranch (or to the default branch if there is noreleasebranch)Run the command, above, to install the latest Kitten on your production server.
Recovering by hand
If a new version of Kitten cannot start and cannot roll back (e.g., its launcher or update-guard.js has a defect), the service will stop after five restart attempts.
To recover manually, should that happen, in Kitten’s data folder (~/.local/share/small-tech.org/kitten), point app and runtime at the previous version, delete updates/pending, and restart:
cd ~/.local/share/small-tech.org/kitten
ls versions runtimes
ln -sfn versions/<previous version> app
ln -sfn runtimes/<its Node.js version> runtime
rm updates/pending
systemctl --user restart kitten
The Node.js version is the third part of the version’s name.
If the app has also changed, updates/pending will contain a previousAppCommit property. In that case, check out that commit from the app’s folder with git checkout --force --detach <that commit> before you delete the record.
Databases backed up by a rollback can be found in updates/failed-data/.
Production servers require systemd.
🌲 Evergreen Web (404 → 307)
Kitten has built-in support for the Evergreen Web (404 to 307) technique.
To implement 404 to 307 redirection for your Small Web place in Kitten, simply set domain you want to forward to in your Small Web Settings page which you can reach in your browser at /🐱/settings/.
Let’s say you are deploying your new Small Web place at your own domain (e.g., https://ar.al) but you already have a personal web site or a blog there. You will already have content that other people might have linked to and/or rely on. It would be a shame for all those links to break when you deploy your new site.
The Evergreen Web (404 to 307) technique is very simple:
On your new site, issue a 307 redirect for any paths that result in a 404 (not found) error to the previous version of your site. That way, if the path existed in the previous version of your site, it will be found there and, if it did not, it will result in a 404 error there.
Of course, you’re not limited to one level of indirection. If the previous version of your site replaced an even earlier version, there’s no reason why you cannot add a 404 to 307 rule there also and have a chain of redirects going all the way back to the earliest version of your site.
One of the great advantages of this technique is that you can just leave older versions of your site running (perhaps at different subdomains) and they can all continue to exist using whatever technologies they were using at the time. (You don’t have to take static exports, etc., of the data.)
By using 404 to 307, you will contribute to an evergreen web by not breaking URLs.
To see it in action, run the evergreen-web example.
For more information, see 4042307.org.
Cascading archives
Similar to the Evergreen Web technique, but useful when your old site was static (or if you output a static version of your old site).
Kitten looks for three special folders:
- __archive__1
- __archive__2
- __archive__3
If they exist, it serves their contents as static files from the root of the site.
These routes are added after all other routes.
So if a route cannot be found in the current version of your site, Kitten will search for it in the above archives, in the order shown above.
Valid file types
Kitten doesn’t force you to put different types of routes into predefined folders. Instead, it uses file extensions to know how to handle different routes and other code and assets.
Here is a list of the main file types Kitten handles and how it handles them:
| Extension | Type | Behaviour |
|---|---|---|
| .page.js|.ts | Dynamic page (JS|TS) | JavaScript/TypeScript route that is rendered into HTML and served in response to a HTTP GET request for the specified path. |
| .page.md | Dynamic page (Markdown) | Markdown route with optional front matter that supports JavaScript imports and the use of Kitten components and fragments in Markdown that is rendered into HTML and served in response to a HTTP GET request for the specified path. |
| .post.js|.ts, .get.js|.ts, .put.js|.ts, .head.js|.ts, .patch.js|.ts, .options.js|.ts, .delete.js|.ts, .trace.js|.ts | HTTP route | Served in response to an HTTP request for the specified method and path. (A .connect.js or .connect.ts file stops Kitten at start-up, as Node never passes CONNECT requests to routes.) |
| .socket.js|.ts | WebSocket route | Served in response to a WebSocket request for exactly the specified path. Only file type to keep part of its file extension in its route pattern (e.g., the file /my.socket.js exists at the URL fragment /my.socket.) |
| .component.js|.ts | A component file, returns HTML | Ignored by router. |
| .layout.js|.ts | Layout component, returns HTML | Ignored by router. |
| .fragment.js|.ts | A fragment file, returns HTML | Ignored by router. |
| .fragment.html | An HTML fragment file | Ignored by router. |
| .fragment.css | A CSS fragment file | Ignored by router. |
| .fragment.md | A Markdown fragment file | Ignored by router. |
| .script.js|.ts | Server-side script file | Ignored by router. Useful for including server-side JavaScript modules. File is not accessible from the client. Put server-only helpers here. Kitten serves any .js or .ts file that isn’t listed in this table to the browser. |
| .styles.js|.ts | Server-side styles file | Ignored by router. Useful for including server-side CSS (in JS). File is not accessible from the client. |
| .client.js|.ts | Page client script | Served as a static file; loaded as a module by the page with the same name. |
| Other (.html, .css, .js, .jpg, .gif, etc.) | Static files | Any other files in your project apart from the ones listed above are served as static files. |
HTTP routes
HTTP data routes are served in response to an HTTP request for the specified method and path.
All HTTP request methods are supported.
You create an HTTP route by create a JavaScript file named with the HTTP request method you want to respond to.
For example, to respond to GET requests at /books, you would create a file named books.get.js in the root of your source folder.
The content of HTTP routes is an ESM module that exports a standard Node route request handler that takes http.IncomingMessage and http.ServerResponse arguments.
For example, your books.get.js route might look like this:
kitten.db.books ??= []
export default ({ response }) => {
response.json(kitten.db.books)
}
A route can also return its response body. Kitten serves a kitten.html result or a kitten.markAsTrusted value as text/html, and a string as text/plain, unless the route sets a content type itself. The status helpers, such as response.ok() and response.withCode(), do the same with the body you pass them. htmx swaps what hx-get or hx-post fetches as HTML whatever its content type, so a route whose result htmx swaps must return kitten.html.
A route can return a stream: a Node Readable, a web ReadableStream such as the body of a fetch response, or an async iterable. Kitten pipes it to the response as application/octet-stream unless the route sets a content type. A route that returns a value Kitten cannot send is answered 500 with a message that reports what to return.
Kitten automatically ends responses that haven’t already been started. Once you call response.writeHead(), response.flushHeaders(), or response.write(), the response is yours to end, unless you return a value, which Kitten sends. The response helpers, including response.sendFile(), end the response for you. If a route fails after it has started its response, Kitten closes the connection and logs the error.
To serve a file with Range request support, so that <video> and <audio> can seek in it, call response.sendFile(). This library/[name].get.js route serves a video from a folder outside the app:
import path from 'node:path'
export default ({ request, response }) => {
const fileName = path.basename(request.params.name)
return response.sendFile(`/media/videos/${fileName}`, { type: 'video/mp4', fileName })
}
response.sendFile serves any path it is given, and a route parameter can contain an encoded /, so take only the last part of a parameter with path.basename, as the example does, before you join it onto a folder.
Every response from a page, a route, or a static file has X-Content-Type-Options: nosniff, so a browser uses the content type it is sent.
Each HTTP route parses its own request body once Kitten has chosen it to respond, with its own limits, and before its default export runs. Kitten responds with 404 to a request with a body that no route responds to, without parsing the body. (Note that Node then reads and discards the rest of the body.)
authorise
A script can’t sign in, so it can’t use a route that requires sign-in. To let a script use a route (e.g., to upload files with a token), keep the route outside 🔒 folders and export authorise({ request }) from it. Kitten calls authorise before it reads the request body. It can be sync or async.
- If it returns
true, Kitten reads the body and runs your route. APOSTroute that exportsauthorisestores uploads, as a route that requires sign-in does. - If it returns anything else (including a truthy value that isn’t
true), Kitten responds with 401 andWWW-Authenticate: Bearer, without parsing the body or running your route. - If it throws, Kitten logs the error with the route’s file and responds with 500.
This upload.post.js route, from the authorise example, accepts uploads from scripts that send a token in the Authorization header, and responds with the names of the files it stored:
export const authorise = ({ request }) => kitten.utils.secretsMatch(`Bearer ${kitten.db.settings.uploadToken}`, request.headers.authorization)
export default ({ request, response }) => {
response.json({ files: request.uploads.map(upload => upload.fileName) })
}
The example’s main.script.js creates the token once and stores it in the database:
kitten.db.settings ??= {}
kitten.db.settings.uploadToken ??= crypto.randomUUID()
export default () => {}
Use kitten.utils.secretsMatch(expected, candidate) to compare a secret from a request with the one you expect. It returns true only when both are the same string, and it takes the same time for any two strings of the same length. This ensures that the time it takes doesn’t reveal how much of a guess is right.
Only HTTP routes can export authorise. A route that requires sign-in, a page, or a socket route that exports authorise fails to load with a line that explains why, and so does a route whose authorise export isn’t a function. (Sign-in already protects a 🔒 route.)
Note that, when Kitten responds with 401, Node reads and discards the rest of the request body. A script that wants to avoid sending a body Kitten will refuse can send Expect: 100-continue, as curl does for bodies over 1 MB. Kitten sends 100 Continue only once it starts reading the body.
Routes added in main.script.js
main.script.js can add routes and middleware with the router argument that Kitten passes to its default export (the same object as kitten.app.router), using Polka’s methods (e.g., router.get(), router.post(), and router.use()).
- Kitten registers the routes you add with
routerafter its own routes and/uploads/, and before your app’s file routes. A route with the same method and URL as one of your route files stops Kitten at start-up, and so does one at a path that Kitten reserves (see Reserved routes). (We don’t check regular expression patterns.) - A route you add with
routerstores the session the first time your handler writes to it or reads itsid, as file routes do (see Sessions and authentication). - Routes you add with
router.post(),router.put(),router.patch(),router.delete(), androuter.all()(and withrouter.add()for one of those methods) parse the request body before your handlers run. They store no files, and Kitten responds with 413 to a request over a limit. - Routes you add with
routerdon’t respond to WebSocket upgrades.
Middleware you add with router.use() runs before any route parses the request body, so request.body and request.files are empty ({}) there. Middleware reads headers; routes read bodies. In development, the first time middleware reads request.body on a request whose body hasn’t been parsed, Kitten logs a line that explains why it is empty.
Middleware you add with router.use() also runs after Kitten’s own routes and /uploads/, so it doesn’t run for the requests that they respond to. And it runs before the route decides whether the request requires sign-in, so middleware that responds itself at a 🔒 path responds to visitors who aren’t signed in, and its session is stored only if it writes to request.session or reads its id. (Middleware isn’t a route.)
Remember that a router route for one of the methods above that calls next() (e.g., router.all('*', …) that logs requests) parses the body before the file route behind it runs. If that file route would have stored files, or has its own uploadLimits, it responds with 500 and logs a line that explains that middleware which passes requests on belongs in router.use(). Put middleware like this in router.use() instead.
Uploads
Kitten automatically saves files sent from a multipart form (enctype='multipart/form-data') that contains a file input (<input type='file'>) to a POST route that requires sign-in (🔒) or exports authorise.
Files are stored in kitten.paths.APP_UPLOADS_DIRECTORY which refers to the uploads folder in kitten.paths.APP_DATA_DIRECTORY.
Kitten saves files only for a POST to a route that requires sign-in (🔒), whether it is your app’s or one of Kitten’s own, and for a POST to a public route that exports authorise. A visitor who isn’t signed in is redirected to sign in before Kitten reads the request body. A multipart request to any other public route has its fields parsed into request.body and its files discarded, so request.uploads is empty, and request.discardedFiles is the number of files Kitten discarded. (Note that a public route without authorise cannot take uploads even with its own code, as Kitten parses the request body before your route’s default export runs.)
A public route still receives a body that is not multipart (e.g., a JSON body or a webhook payload), up to its body limit, as request.rawBody, and parsed into request.body when it is JSON or URL-encoded.
An upload is private by default: Kitten serves it only to you, once you’re signed in. To show an upload to everyone, make it public (see Private and public uploads).
kitten.uploadLimits
kitten.uploadLimits sets the limits applied to requests that have a body.
The defaults:
fileSize: 20 MB (20,000,000 bytes) per file.files: 10 files.fields: 1,000 fields in a form, multipart or URL-encoded. Minimum: 1.fieldSize: 1 MB (1,000,000 bytes) per field value.fieldNameSize: 100 bytes per field name in a URL-encoded form.body: 4 MB (4,000,000 bytes) per request, not counting files. For a multipart form the limit applies to the aggregate size of its field values. For any other request (URL-encoded form, JSON body, webhook payload) it applies to the size of the body.
If a request exceeds any of the limits, Kitten deletes all files in the request. Unless the route responds through onUploadLimit, Kitten responds with its 413 Payload Too Large page and logs the limit:
❌ 413 on POST /upload/: a file is larger than the limit (Kitten’s default fileSize limit is 20,000,000 bytes). Export onUploadLimit from upload🔒/index.post.js to respond.
The line mentions where the limit that the request exceeded is set: the route’s uploadLimits (e.g., uploadLimits.fileSize in upload🔒/small/index.post.js), kitten.uploadLimits (e.g., kitten.uploadLimits.fileSize), or Kitten’s default, as above. Kitten adds the last sentence of that line only for a fileSize, files, fieldSize, or body limit on one of your app’s POST routes.
A POST route that requires sign-in or exports authorise can respond to the fileSize, files, fieldSize, and body limits itself by exporting onUploadLimit. On any other POST route, onUploadLimit runs for the files, fieldSize, and body limits, and never for fileSize. Kitten always responds with its 413 page to the fieldNameSize and fields limits. Only your form’s markup, or a crafted request, can exceed those.
Kitten responds with 404 to a request over a limit to a path with no route.
When Kitten cannot parse form or if it is sent a JSON body that is not JSON, it returns a 400 Bad Request response. If a URL-encoded body is sent in a charset other than UTF-8 or Latin-1 Kitten returns a 415 Unsupported Media Type error resposne. These responses are sent before your route’s default export runs.
To change a limit, set your custom value in main.script.js, e.g.,
kitten.uploadLimits.fileSize = 50_000_000
You can also change all limits by assigning kitten.uploadLimits to an object.
Infinity removes a limit. A limit you leave out, or set to something other than a number (including NaN), takes Kitten’s default.
Each limit must be a whole number or Infinity, and fields must be at least 1. Kitten checks kitten.uploadLimits once main.script.js has run. If a limit breaks these rules, Kitten stops at start-up with a line that mentions the limit and its value. If a key isn’t a limit (e.g., filesize), Kitten stops with a line that mentions the key and lists the limits.
Kitten reads the limits on every request, so a change made while the server is running will apply starting with the next request. (If you change a limit to a value that breaks the rules above while the server is running, each request whose body Kitten parses fails instead.)
uploadLimits
An HTTP route can set its own limits by exporting uploadLimits, a plain object with any of the limits in kitten.uploadLimits. Each limit it sets replaces the one in kitten.uploadLimits for requests to that route. The others come from kitten.uploadLimits, and then from Kitten’s defaults. A limit in uploadLimits that isn’t a number (including NaN) is the same as one you leave out.
This upload🔒/small/index.post.js route, from the upload limits example, limits each image to 100 KB, while the example’s main.script.js sets kitten.uploadLimits.fileSize to 1 MB for its other routes:
kitten.db.images ??= []
export const uploadLimits = { fileSize: 100_000 }
export default function ({ request, response }) {
request.uploads.forEach(upload => {
upload.public = true
kitten.db.images.push({
path: upload.resourcePath,
altText: request.body.altText ? request.body.altText : upload.fileName
})
})
response.get('/upload/')
}
export function onUploadLimit ({ request, response, limit }) {
const error = limit.name === 'fileSize' ? 'file-too-large' : 'upload-too-large'
response.get(`/upload/small/?error=${error}&altText=${encodeURIComponent(request.body.altText ?? '')}`)
}
Kitten checks a route’s uploadLimits by the same rules as kitten.uploadLimits when the route loads. If a limit breaks the rules, the route fails to load with a line that mentions the limit, its value, and the route’s file. If a key isn’t a limit, the line mentions the key and the file and lists the limits. If the export isn’t a plain object, the line mentions the file.
Kitten’s own restore route (/💕/data/restore/) exports uploadLimits = { fileSize: Infinity }, so you can restore a backup that is larger than kitten.uploadLimits.fileSize.
request.uploads
In a POST route, request.uploads is an array of Upload objects, one per file. It’s empty when the request does not include a file, and always empty in a public route without authorise.
Each Upload has the following properties:
id: the upload’s unique ID.fileName: the name of the file on the person’s computer.filePath: where the file is stored on disk.mimetype: the file’s MIME type.encoding: the transfer encoding of the file, e.g.,7bit.field: the name of the form field the file originated from.truncated: alwaysfalse. Kitten deletes a file overkitten.uploadLimits.fileSizeand either runs the route’sonUploadLimitor responds with 413.done:trueonce the file is written to disk.resourcePath:/uploads/<id>/, where Kitten serves the file inline when its type isimage/png,image/jpeg,image/gif,image/webp,image/avif, audio, video, ortext/plain, and as a download otherwise.downloadPath:/uploads/<id>/download/, where Kitten serves the file as a download.public:truewhen Kitten serves the upload to anyone, andfalse(the default) when it serves it only to you, signed in. See Private and public uploads.delete(): deletes the file from disk and removes it fromkitten.uploads.
Every upload is served with Content-Security-Policy: sandbox. An upload whose type is not on that list downloads when its URL is opened; one shown in <img>, <video>, or <audio> displays as before.
Kitten serves an upload with Accept-Ranges: bytes and Content-Length, answers a Range request for one range with 206 Partial Content and those bytes, an unsatisfiable one with 416 Range Not Satisfiable, and a HEAD request with the headers alone. A <video> or <audio> element can seek in an upload.
Private and public uploads
An upload is private by default. Kitten serves a private upload only to you, once you’re signed in, with Cache-Control: private and no Access-Control-Allow-Origin header. Anyone else is redirected to the sign-in page, as for a 🔒 page. This ensures that a file you upload (e.g., a backup, or a draft) isn’t public to anyone who learns its URL.
To serve an upload to anyone, set its public property to true in your POST route. Kitten persists it in its internal database and serves a public upload to anyone, with Access-Control-Allow-Origin: *. public must be exactly true, so a form field’s 'true', which is a string, leaves the upload private.
This upload🔒/index.post.js route, from the file uploads example, makes each image public, as the example shows its images in a public gallery:
kitten.db.images ??= []
export default function ({ request, response }) {
request.uploads.forEach(upload => {
upload.public = true
kitten.db.images.push({
path: upload.resourcePath,
altText: request.body.altText ? request.body.altText : upload.fileName
})
})
response.get('/upload/')
}
Note that uploads stored by earlier versions of Kitten are public. (The first time Kitten opens its internal database after the upgrade, it marks every existing upload public, except backup archives left in the uploads store by a restore, which contain Kitten’s internal database.)
onUploadLimit
A POST route can export onUploadLimit next to its default handler. Kitten calls it in place of the default handler for a request over the fileSize, files, fieldSize, or body limit (on a route that doesn’t store files, never for fileSize):
export default function ({ request, response }) {
// Kitten never calls this for a request over a limit.
}
export function onUploadLimit ({ request, response, limit }) {
// limit is { name, value }.
}
limit.name:fileSize,files,fieldSize, orbody.limit.value: the value of that limit for the route: from itsuploadLimits, fromkitten.uploadLimits, or Kitten’s default.request.body: the form fields that arrived complete before the limit, and{}for any other body. For afileSizeorfileslimit, it contains all text fields that come before the file input.request.uploads: always empty.
Kitten sends the return value of onUploadLimit as it sends a route’s return value, with status 200 unless the hook sets another. htmx does not swap a 4xx response by default. To send 413, call response.withCode(413, …).
Kitten responds with its 500 page to all requests to a route whose onUploadLimit export is not a function.
Kitten does not process <page> directives in markup a POST route returns. A hook can respond in three ways:
With Streaming HTML, the hook emits an event on the session and the page sends the error over its WebSocket:
// upload🔒/index.post.js
export function onUploadLimit ({ request, response, limit }) {
request.session.emit('uploadLimitExceeded', limit)
response.ok()
}
// upload🔒/index.page.js
export function onConnect () {
this.addSessionEventHandler('uploadLimitExceeded', limit => {
const message = limit.name === 'fileSize' ? `The image must be ${limit.value / 1_000_000} MB or smaller.` : 'The upload is too large.'
this.send(kitten.html`<${status}>❌ ${message}</>`)
})
}
With htmx, the hook returns the form with the error and the fields the person entered, and htmx swaps it in:
export function onUploadLimit ({ request, limit }) {
const error = limit.name === 'fileSize' ? `The image must be ${limit.value / 1_000_000} MB or smaller.` : 'The upload is too large.'
return kitten.html`<${images} error=${error} altText=${request.body.altText ?? ''} />`
}
With a plain form, the hook redirects to the page with an error code, and the page renders the sentence for that code (Post/Redirect/Get):
export function onUploadLimit ({ request, response, limit }) {
const error = limit.name === 'fileSize' ? 'file-too-large' : 'upload-too-large'
response.get(`/upload/?error=${error}&altText=${encodeURIComponent(request.body.altText ?? '')}`)
}
See the Streaming HTML file uploads, file uploads with Ajax, and upload limits examples.
kitten.uploads
kitten.uploads contains all uploads made to a POST route that requires sign-in or exports authorise, keyed by ID, in Kitten’s internal database:
get(id): returns theUploadwith the given ID, orundefinedwhen there is none.length(): returns the number of uploads.all(): returns an array of everyUpload.allIds(): returns an array of every upload ID.delete(id)(async): deletes the file from disk and removes the upload.
For example, this upload🔒/index.post.js route saves the path of every uploaded image in the default database and redirects back to the upload page, /upload/:
kitten.db.images ??= []
export default function ({ request, response }) {
request.uploads.forEach(upload => {
kitten.db.images.push({
path: upload.resourcePath,
altText: request.body.altText ? request.body.altText : upload.fileName
})
})
response.get('/upload/')
}
See the multipart forms and file uploads tutorial, and the file uploads, file uploads with Ajax and Streaming HTML file uploads examples.
WebSocket routes
You create a WebSocket route with a .socket.js (or .socket.ts) file. e.g., updates.socket.js serves WebSocket connections at /updates.socket.
A socket route responds only at its own path, so updates.socket.js doesn’t respond at /updates.socket/anything/. For a family of sockets, use a parameter: [room].socket.js responds at /lobby.socket and /kitchen.socket. The wildcard parameter ([any]) in a socket route’s name matches one segment and preserves the .socket suffix, so rooms/[any].socket.js responds at /rooms/lobby.socket and not at /rooms/lobby/.
Only socket routes, page sockets, and Kitten’s development socket respond to WebSocket upgrades. Kitten responds with 404 to any other upgrade and closes the socket. A socket route passes on every request that isn’t an upgrade, and a socket route in a 🔒 folder requires sign-in for upgrades.
A WebSocket message, to a page or to a socket route, may have at most 1 MB. Kitten closes a socket that sends a larger one with code 1009. A live page whose socket Kitten closes with code 1009 reconnects, which reloads it.
Unlike other routes, WebSocket routes keep their extension. Kitten also doesn’t apply URL normalisation to WebSocket clients like it does for all other routes (it doesn’t add a trailing slash to URLs that are missing one).
Your route exports a handler function that Kitten calls once per connection, passing it the following parameter object: { request, socket }:
request: the HTTP request that opened the connection.socket: the ws WebSocket for the connection, with two extra methods:all(message): sends the message to every client connected to the route, including itself.broadcast(message): sends the message to every other client connected to the route.
Both methods return the number of connections they sent the message to. If you pass them a promise, they return a promise of that number.
To open a WebSocket connection from your server to another server, use kitten.WebSocket, which is the WebSocket class from ws.
In the following example, the echo.socket.js route responds to messages by adding them to a list on the page:
export default function ({ request, socket }) {
console.info('Echo socket: new client connection.', request.session)
socket.addEventListener('message', event => {
const message = JSON.parse(event.data).message
socket.send(kitten.html`
<ul id='echos' swap-target='beforeend'>
<li><strong>“${message}”</strong> received on server.</li>
</ul>
`)
})
}
Page sockets
You don’t manually author socket routes for live pages. Kitten automatically creates a page socket at <page path>default.socket and routes its messages to your event handlers. (For a wildcard page, the page socket’s path includes the path that the page matched.)
A page socket attaches only to a page that its own page route rendered, for the same session. Kitten treats any other page id as one that doesn’t exist: it sends the page the reload command and closes the socket. A page socket that opens without a session cookie (e.g., in a browser that blocks cookies) is closed without the reload command, so live pages need cookies. Kitten responds with 404 to a GET request to a page socket’s path that isn’t a WebSocket upgrade.
Messages sent using the send() and update() methods of the page, or the update() and sendToPage() methods of a component are morphed into the page. Kitten adds an hx-swap-oob="morph" attribute to the first element in the message unless it has an hx-swap-oob (aka swap-target) attribute of its own or is a <script>.
A plain string passed to the page’s send(), a component’s sendToPage(), this.everyone.send(), or this.everyoneElse.send() is escaped and sent as text, and Kitten logs a warning that mentions the page. Send kitten.html for markup.
this.everyone.send(), this.everyoneElse.send(), and manually-authored socket routes don’t automatically add the hx-swap-oob attribute for you, so you must add a morph or swap-target (syntactic sugar for hx-swap-oob) attribute manually. Furthermore, if your page connects to a manually-authored socket route, you must manually add the htmx-idiomorph attribute to its <page> tag for morph to work.
Unlike the page’s send() method, a manually-authored socket route doesn’t escape plain strings. It sends them exactly as they are. So, if htmx swaps your message into the page, build it with kitten.html, not a plain template string. The socket route then sends the HTML that kitten.html renders, with any values you interpolated into it escaped.
If a template contains a promise or an async component, kitten.html returns a promise. You can send that promise without awaiting it, using any of these methods:
the page’s
send()methodthis.everyone.send()andthis.everyoneElse.send()a socket route’s
send(),all(), orbroadcast()methods
Kitten waits for the promise to resolve, then sends the result to everyone who’s connected at that point. (If the promise rejects, Kitten logs a warning and doesn’t send the message.)
this.everyone.send(), this.everyoneElse.send(), all(), and broadcast() return the number of connections they sent the message to. When you pass them a promise, they return a promise of that number instead (and 0 if the promise rejects).
Note that a message sent this way can arrive after a message you send directly after it. To keep your messages in order, await the template before you send it.
See the htmx, the htmx WebSocket extension, and socket routes and two-way WebSocket communication tutorials.
URL normalisation
Kitten automatically normalises URLs that do not have a trailing slash when they should to add one.
It does so using a permanent 308 redirect that preserves the method of the request.
This means, for example, that a request to https://my.site/hello will be forwarded to https://my.site/hello/.
This is both to help implement canonical paths for your sites/apps and to avoid the unexpected situation of a relative include failing from your page if a slash is not provided in the path. (e.g., if you have an index.js file and an index.html file in a folder called hello and you include the JavaScript file using <script src='./index.js'></script>, that will succeed if the page is hit as /hello/ but fail if it is hit as /hello.)
Sessions and authentication
Kitten automatically manages sessions and authentication for you.
You can add a lock emoji (🔒) to the end of any route to make it an authenticated route.
Authenticated routes are only accessible by the owner of the site after they sign in using their secret.
If an authenticated route is a folder, any child routes also require authentication.
Kitten requires sign-in only when the route that responds to a request requires it. So a public route stays public next to an authenticated route that also matches its path (e.g., admin/help.page.js next to admin🔒/[section].page.js, or static files next to a root [slug]🔒.page.js). A visitor who isn’t signed in and requests an authenticated route is redirected to /💕/sign-in/ with a 303. For a GET request that isn’t an upgrade, and whose URL is at most 2,048 characters, the redirect includes the requested URL in the sign-in page’s return parameter, and signing in returns the visitor to it.
Kitten looks for 🔒 only in the part of a route’s path inside your app, so an app in a folder whose path contains 🔒 doesn’t require sign-in everywhere. Kitten removes every 🔒 from a route’s URL, so a🔒/b🔒.page.js responds at /a/b/.
You can also manually check if the owner of the site is signed in by checking if request.session.authenticated is true or not. request.session.authenticated is read-only, and assigning to it throws a TypeError.
Kitten keeps a session that isn’t signed in only in memory, at most 10,000 of them, and a new session replaces the oldest one at the cap. Its data does not survive a restart or a deploy. We store a session, and set its cookie, the first time your route writes to request.session or reads request.session.id, when a live page renders, and when you sign in. This applies to pages, HTTP routes, routes that main.script.js adds through router, and middleware added with router.use(). Until then, each request has a new session, so a refusal, a 401 from authorise, a static file, and a route that never uses its session set no cookie. Use the session before your route starts its response: once the headers are sent, a session that is not yet stored cannot be stored, and we print a warning with the request’s method and URL. A property whose name starts with an underscore is not session data (we never copy one on sign-in), so writing one stores nothing.
Signing in creates a new session, with a new id and the data of the session you signed in from, and ends that session. Kitten stores only a signed-in session’s id and createdAt, so the session survives a restart but the data your app stores on it does not.
Signing out ends the session. It takes two requests (the sign-out page’s script clears your identity from the browser and then posts to /💕/sign-out/), so signing out needs JavaScript.
A session expires eight hours after it is created. Kitten deletes a session when it expires, when you sign in from it or sign out, and when a new session replaces it at the cap. When Kitten deletes it, the session emits kittenSessionDelete. kittenSessionDelete is a reserved event name. A live page whose session is deleted reloads itself.
When listening for session events from components, use addSessionEventHandler, which removes the listener when the component disconnects. If you manually add a listener using session.on, remember to remove it with session.off in your component’s onDisconnect() handler, passing the same function you passed to session.on. A listener that is not removed stays active on the session until it expires and might constitute a leak.
Finally, you can manually direct people to sign in and out by redirecting them to the following routes:
/💕/sign-in/💕/sign-out
Remember that the Small Web – and therefore, Kitten – does not have the concept of users. There is only ever one owner of the site, who is a person. And only this owner can sign into the site. The site might be viewed by countless people over time but they cannot authenticate with it or create accounts on it.
(If you want to build this functionality yourself, for your app, you of course can but it is neither encouraged nor supported. Please see the FAQ for more details.)
The idea is that everyone has their own Small Web site and, when they want to communicate with each other, they do so in a peer-to-peer fashion.
This is the core difference between the Big Web – which is made of up of centralised silos often owned by trillion-dollar and multi-billion-dollar corporations that make their money by farming you for your data – and the Small Web, which is a peer-to-peer web of people who use technology as an everyday tool to communicate with each other and enrich their lives.
To understand the technical architecture of the Small Web better, please see the End-to-end encrypted peer-to-peer Small Web apps tutorial.
To learn more about sessions and authentication, please see the following two tutorials:
Data scopes
In Kitten, you have a number of different scopes, with varying lifetimes, where you can store data.
These are, from most limited and ephemeral to widest and most permanent:
| Scope | Lifetime | Availability | Usage | Example |
|---|---|---|---|---|
| Page storage | Life of a single page loaded in a browser window/tab | Only on live pages (a stateful page, or a stateless page that exports an event handler) | Keep data in instance properties in your kitten.Page or kitten.Component subclass. In stateless pages, this within exported event handlers references the live page, so you can do the same thing there. | Streaming date |
| Session storage | Common to all pages within a client-side browser session (e.g., multiple pages open in tabs in the same browser) until the server restarts. | On any handler that receives a request property | Store data on the session object you have on the request property you’re passed in your page route and page onConnect() handlers. | Sessions tutorial |
| Route globals | Shares state between all handler calls of a route but is ephemeral (destroyed on server restart) | Any route | Create a file-level variable. | Draw Together |
| Globals | Shares state within your application but is ephemeral | Anywhere | Create a global variable (e.g., globalThis.myVariable) | n/a |
| Persisted | Kept in the app database (persisted to disk; survives server restarts) | Anywhere | See Database section, below. | Persistence tutorial |
Database
Kitten has an integrated JSDB database that’s available from all your routes as kitten.db.
JSDB is a transparent, in-memory, streaming write-on-update JavaScript database for the Small Web that persists to a JavaScript transaction log.
Tables in JSDB are simply JavaScript objects or arrays and JSDB writes to plain old JavaScript files.
You can also create type-safe databases. To learn how to do so, read the Database App Modules tutorial.
You can inspect and alter your database from the Kitten’s interactive shell while your app/site is running.
You can also get information about the database and specific tables, delete the whole database and specific tables, and tail specific tables using the command-line interface via the db info [tableName] (or just db [tableName], which is a convenience alias), db delete [tableName] and db tail <tableName> commands.
To access the JavaScript source code of your database, follow the “Open app data folder” link in Kitten’s initial terminal output.
Your databases are located under the main data folder:
~/.local/share/small-tech.org/kitten/data/
Each project gets its own folder in there with a name based on the absolute path to your project on your disk. e.g., A Kitten project stored in /var/home/aral/projects/my-project and served at localhost, port 443, will have its database in a folder called var.home.aral.projects.my-project.localhost.443 in the main data folder. (A different domain or port gives the project a different folder.)
Route parameters
You can include route parameters in your route paths by separating them with underscores and surrounding the parameter names in square brackets.
For example:
manage_[token]_[domain].socket.js
Will create a WebSocket endpoint at:
/manage/:token/:domain.socket
You can also intersperse path fragments with parameters:
books_[id]_pages_[page].page.js
Will make the dynamic page available for HTTP GET requests at:
/books/:id/pages/:page
So you can access the route via, say, https://my.site/books/3/pages/10.
You can also specify the same routes using folder structures. For example, the following directory structure will result in the same route as above:
my-site
╰ books
╰ [id]
╰ pages
╰ [page].page.js
Note that you could also have set the name of the page to index[page].page.js_. Using just [page].page.js for a parameterised index page is a shorthand.
You can decide which strategy to follow based on the structure of your app. If, for example, you could access not just the pages but the references and images of a book, it might make sense to use a folder structure:
my-site
╰ books
╰ [id]
├ pages
│ ╰ [page].page.js
├ references
│ ╰ [reference].page.js
╰ images
╰ [image].page.js
You may, or may not find that easier to manage than:
my-site
├ books_[id]_pages_[page].page.js
├ books_[id]_references_[reference].page.js
╰ books_[id]_images_[image].page.js
Kitten leaves the decision up to you.
Optional parameters
To create an optional parameter, prefix your parameter name with optional- inside the square brackets.
For example, the following route:
delete
╰ index_[subdomain]_[optional-return-page].page.js
Will match both of the following paths:
- /delete/my-lovely-subdomain/
- /delete/my-other-subdomain/troubleshooting/
The wildcard parameter
Finally, you can also use the special wildcard parameter to match any string:
my-site
╰ books_[any].page.js
The about route will match any path that begins with /books/.
Under the hood, Kitten uses Polka for its routing and translates Kitten’s file system-based naming syntax to Polka’s routing syntax.
Route order
When more than one route matches a request, the most specific one responds. We order routes by their URL patterns, whatever order the file system returns your files in, so your app behaves the same on every machine. Pages, HTTP routes, and static files follow the same rule.
We compare two patterns segment by segment. At the first segment where they differ:
- a literal segment (e.g., about) comes before a parameter (e.g., [slug]),
- a parameter comes before an optional parameter (e.g., [optional-page]), and
- an optional parameter comes before the wildcard parameter ([any]).
If one pattern runs out of segments first, it comes first, unless its last segment is the wildcard or an optional parameter, in which case the longer pattern comes first.
This means that about.page.js responds at /about/ next to [slug].page.js, and docs/[any]/edit.page.js responds at /docs/a/edit/ next to docs/[any].page.js. (At the same URL, a .head.js route comes before a page, which would otherwise respond to HEAD requests, as Polka runs GET routes for them.)
Routes at the same URL
Two routes with the same method at the same URL stop Kitten at start-up with a line that mentions both files and the URL. This ensures that one route never replaces or shadows another without you knowing. Each of these pairs stops Kitten, for example:
- about.page.js and about.page.ts
- page2.html and page2.page.js
- zz🔒.page.js and zz/index.page.js
- secret.page.js and secret🔒.page.js
- default.socket.js and index.page.js (whose page socket is at
/default.socket) in the same folder
We compare URLs without case and without parameter names, so [slug].page.js and [name].page.js in one folder collide too. Routes whose patterns overlap but aren’t the same (e.g., index.page.js at / and [optional-page].page.js) don’t collide, and route order decides which one responds.
App Modules
When working on larger projects, you might end up with pages at varying levels within the site, all of which need to use the same global resource (for example, a layout template or a utility class).
In these situations, your import statements might start to get unruly.
Take the following example:
my-site
├ site.layout.js
╰ books
╰ the-handmaids-tail
╰ pages
╰ cover.page.js
Let’s say your cover.page.js uses the site layout template.
Here’s what its import statement would look like:
import site from '../../../site.layout.js'
export default () => kitten.html`
<${site}>
…
</>
`
That’s both cumbersome to write and error-prone. (Especially when you consider that different pages at different levels of the hierarchy may want to use the same file. You don’t want to spend your day counting dots.)
Enter App Modules.
App Modules are special local Node modules that exist only in your app (not on npm). They live in the special app_modules folder in your project and Kitten knows to ignore them when calculating its routes from the file structure of your project.
App Modules, like all Node modules, need a package.json file but they can get away with specifying a subset of the information contained in ones for npm packages. And, like all Node modules, they need to be npm installed into your project (but from a local file path instead of from npmjs.org).
Finally, if you have type checking enabled in your projects, you should add an index.d.ts file to your App Modules so your editor doesn’t complain when using the TypeScript Language Server (LSP).
Here’s how you’d make your site layout into an App Module:
Create the app_modules directory and then a directory for your module:
mkdir -p app_modules/site-layoutAdd the files your module will need:
my-site ├ app_modules │ ╰ site-layout │ ├ site.layout.js │ ├ index.d.ts │ ╰ package.json ╰ books ╰ the-handmaids-tail ╰ pages ╰ cover.page.jsIn your package.json file, you need to specify three properties:
name,type, andmain:{ "name": "@app/site-layout", "type": "module", "main": "site.layout.js" }Finally, if you have type checking enabled and you want to avoid type errors in your editor, your index.d.ts file should look like this:
import siteLayout from './site.layout.js' export default siteLayout
And that’s it.
All you need to do then is to install the App Module.
From the root of your project, install your module using its local path:
npm install ./app_modules/site-layout
Finally, from cover.page.js (and any other page, anywhere in your project) you can now import your layout using:
import site from '@app/site-layout'
That’s much better, isn’t it?
Database app modules
Database app modules are special type of app module that Kitten expects to have the name database.
You are not limited to using the default, untyped database Kitten sets up for you.
The default database, like many of the beautiful defaults in Kitten, exists to make it easy to get started with Kitten and use it to build quick Small Web places, teaching programming, etc.
If, however, you’re designing a Small Web place that you will need to maintain for a long period of time and/or that you are going to collaborate with others on, it would make sense to create your own database and to make it type safe so you get both errors and code completion during development time.
You can create your own custom database using a special type of app module called the database app module.
Like any other app module, your database app module goes in the special app_modules directory in the root of your project. What’s special is that the app module must be called database.
Make sure your database app modules are using JSDB version 6.0.1 or later as previous versions suffer from a possible data corruption/security issue where string keys were not being sanitised in the same way values were during serialisation.
To learn how to create your own database app module for your Small Web project, please read the Database App Module tutorial.
For a real world example, see the database app module in Catalyst that wraps Kitten’s global JSDB instance with type information and some utility methods.
Static files
You do not have to do anything special to server static files with Kitten. It is, first and foremost, a web server, after all. Any file that’s in your project folder that isn’t a hidden file or in a hidden folder and isn’t a special Kitten file (e.g., .page.js, .socket.js, .post.js, etc.), will be served as a static file.
Reserved routes
Kitten tries to be as minimally invasive into your site or app’s own namespace as possible. That said, there are certain routes that it does reserve. Some of these are part of the Small Web protocol and others are Kitten-specific.
Paths under /💕/ and /🐱/ belong to Kitten, and so do paths below /uploads/, where Kitten serves uploads. A route file in your app, or a route that main.script.js adds through router, at one of those paths stops Kitten at start-up with a line that mentions the file (or the router call) and the URL. (/uploads/ itself is yours. A [slug] or [any] route at the root of your app also matches those paths, and we don’t refuse it, as Kitten’s own routes come first.)
Reserved Kitten-specific routes
Kitten-specific routes are kept in the 🐱 namespace so as not to pollute your app/site’s own URI space.
These include routes for default functionality that Kitten provides like the settings interface:
- /🐱/settings (authenticated route)
Reserved Small Web protocol routes
The protocol is currently under development and evolving rapidly.
The following routes are reserved as part of the Small Web protocol, which is namespaced by the Small Web emoji/logo (💕).
They are used to implement public-key authentication and manage the communication between Small Web instances and the Catalyst instances that host them:
/💕/id
/💕/id/ssh
Kitten’s sign-in and sign-out routes are also in this namespace:
/💕/sign-in
/💕/sign-out
Kitten currently does not implement the full Small Web protocol. (The Small Web protocol is, itself, a work in progress.) It is currently up to apps to implement aspects of it in ways that make sense for them.
For example, Place is in the process of implementing the following routes:
- /💕/follow
- /💕/profile
In time we’ll see whether or not it makes sense to pull in more base Small Web protocol implementations into Kitten proper.
Redirects
Before it handles sessions and sign-in, Kitten checks two tables in its internal database on each request. Both tables are plain objects. Set a property to add a redirect, and delete it to remove one.
Domain redirects
kitten._db.settings.domainRedirects maps a Host header value to a URL prefix. Kitten redirects a request whose Host is a key to the value followed by the request’s path and query, with a 307 redirect. The value must not end with a slash.
When it starts, Kitten requests one TLS certificate for the app’s domain and all keys together, so a new domain redirect takes effect after a restart. If DNS for a key does not point at the server, the certificate is refused and the restart fails. Deleting a domain redirect takes effect on the next request.
kitten._db.settings.domainRedirects['old.example'] = 'https://new.example'
With this redirect, Kitten redirects https://old.example/notes/?page=2 to https://new.example/notes/?page=2.
Kitten checks domain redirects before URL normalisation, so the path reaches the new domain unchanged: https://old.example/notes redirects to https://new.example/notes.
Look over there! is a Kitten app that manages domain redirects, with HTTPS for each redirected domain.
Local redirects
kitten._db.settings.localRedirects maps a request path to a location. The key is the path as the browser requests it: percent-encoded and without the query. URL normalisation runs first, so the key ends with a slash unless its last segment contains a dot (/blog/2024/hello/, /about.html).
The value is any location response.redirect() accepts. Kitten encodes each % in it that does not start an escape as %25. Kitten redirects the request with a 307 redirect.
kitten._db.settings.localRedirects['/blog/2024/hello/'] = '/notes/hello/'
A local redirect preserves links when the structure of a site changes.
Kitten client-side libraries
Kitten comes with several client-side libraries which are automatically served at runtime that you can use in your sites/apps.
The page tag provides a high-level interface for including most of them on your pages.
For example, to include htmx, you can add the following page tag to any HTML fragment that ends up on your page:
<page htmx>
You can also include any of them in your sites/apps manually, just like any other client-side script, by knowing their paths:
In /🐱/library/:
| Library name | File name | Page tag attribute name | Version | Notes |
|---|---|---|---|---|
| Kitten cryptography module | crypto-1.js | n/a (ES module) | ^1 | |
| Kitten key store module | key-store-1.js | n/a (ES module) | ^1 | A signed-in person’s identity as non-extractable Web Crypto keys in IndexedDB. |
| htmx | htmx-2.js | htmx | ^2 | Own fork. |
| htmx WebSocket | htmx-ws-2.js | ws | ^2 | |
| htmx idiomorph extension | htmx-idiomorph-0.8.js | idiomorph | ^0.8.0 | idiomorph from npm with Kitten’s own copy of the extension. |
| Alpine.js | kitten-alpine-1.js | alpine | ^3 | Alpine.js, started by Kitten after every module on the page. alpinejs-3.js is still served for sites that include it by path. |
| kittenRuntime | kitten-1.js | n/a (always included) | ^1 | Configures htmx and defines kitten.ready. |
| Development-time hot reload | kitten-hot-reload-1.js | n/a (development only) | ^1 | |
| Prism (CSS) | prism-1.css | n/a | ^1 | Used internally to syntax highlight Kitten error messages. Also see built-in Highlight.js syntax highlighter. |
| Water (CSS) | water-2.css | water | ^2 |
You can access the file names of htmx, its WebSocket and idiomorph extensions, Alpine.js, Water, and kitten-1.js on the kitten.libraries object, as htmx, htmxWebSocket, htmxIdiomorph, alpineJs, water, and kittenRuntime. In production, htmx, htmxIdiomorph, alpineJs, and water contain the minified file names. htmxWebSocket and kittenRuntime are the same in production.
In production, htmx and Alpine.js are also gzipped (.min.js.gz).
The -N notation specifies the major version of the library. Since Kitten sites automatically update, if there is a major version update to a library, it will be adding alongside previous versions so as not to break existing sites. So if htmx 2.x.x comes out, for example, with breaking changes and we start supporting it, it will be added as htmx-2.js. All minor and patch updates will be automatically updated without changing the name of the include.
🐢 Kitten’s interactive shell (REPL)
Introduction
Kitten has an interactive shell (REPL) that extends the default Node.js REPL with Kitten-specific features.
When working with Kitten interactively (i.e., during development), you can launch the shell using the s key from any Kitten instance running in your terminal.
You’ll know you’re in Kitten’s interactive shell when you see the following prompt:
🐱 💬
Connecting to a Kitten service
When Kitten runs as a service (e.g., an app you’ve deployed to a server using kitten deploy), there’s no terminal for you to press s in. Instead, Kitten listens for shell connections on 127.0.0.1, port 1337, and you open its interactive shell with the kitten shell command.
On the server, run:
kitten shell
From your own machine, run the same command on the server over SSH:
ssh -t you@server .local/bin/kitten shell
The -t option gives the shell a terminal to run in. (We use the path to the kitten launcher in your home folder as ~/.local/bin might not be on the path for commands you run over SSH.)
Press Ctrl D to exit the shell. Your Kitten service continues to run.
Note that the shell doesn’t ask you to authenticate, so any account on the server can connect to it and run code in your Kitten server. Only run Kitten on a server where you trust every account. (See issue #369.)
Commands
In addition to executing JavaScript statements, Kitten also provides a number of useful custom commands you can use. These commands always begin with a dot.
For a full list of available commands, including ones inherited from Node.js’s own REPL, use the .help command.
.ls
The .ls command shows you the keys of Kitten’s global kitten object – one of the most useful objects you can access in Kitten’s shell.
It is a convenience function for the more verbose Object.keys(kitten) JavaScript statement that you can also use for the same purpose.
.id
Shows your Small Web place ID (ed25519 public key) if you have one.
Otherwise, prompts you to use the .id create command to create your Small Web place secret.
.id create
Creates your Small Web place secret (ed25519 private key, encoded as a lovely emoji string that you should keep in your password manager).
The output looks something like the following:
🆔 Identity » New ID created. 🔑 This is your secret:
.settings
Shows the URL for accessing the Kitten Settings page of your app.
e.g., If you’re running it in development on the default port, it’ll return:
https://localhost/🐱/settings/
.sign-in
Shows the Sign In page URL for authenticating with your Kitten app.
e.g., If you’re running it in development on the default port, it’ll return:
https://localhost/💕/sign-in/
.sign-out
Shows the Sign Out page URL for signing out of your current session on your Kitten app.
e.g., If you’re running it in development on the default port, it’ll return:
https://localhost/💕/sign-out/
.stats
Shows statistics about your Kitten app (including statistics on event handlers and listeners) as well as any other Kitten processes that might be active on your machine, as well as basic statistics on all running processes and on the machine itself.
Explore ways you can use Kitten’s shell (REPL) in the Kitten’s Interactive Shell (REPL) tutorial.
The kitten global
The global kitten object has the following members:
Rendering
kitten.html: Kitten HTML tagged template string with support for Kitten components and JavaScript string interpolation.kitten.css: CSS tagged template.kitten.js: JS tagged template.kitten.markdown: Markdown wrapper.kitten.md: Reference to the MarkdownIt instance used internally by Kitten.kitten.safelyAddUntrustedHtml: Use this method to add untrusted markup to your page safely.kitten.markAsTrusted: Returns a value thatkitten.htmlinserts exactly as written. Only pass it a string you wrote or trust (see Interpolated values).kitten.sanitise: A wrapper around sanitize-html that removes every HTML tag not on the allow list. With the default allowed tags, the result is safe to add as HTML content withkitten.markAsTrusted(). It isn’t safe to include directly in a JavaScript attribute such asonclick(or Alpine.js’sx-data,x-init, etc.) as a quotation mark in the value can end the string and open you up to an injection attack. Instead, put it in adata-*attribute and read the value of that data property in your handler (see Interpolated values).kitten.slugify: Slugify a string.kitten.yaml: YAML parser and serialiser.
Pages and components
kitten.Page: KittenPage class.kitten.Component: KittenComponent class.kitten.page: Special page slot names (constants) that can be used as targets of<content for='…'>tags.kitten.pages: Record of all active KittenPage instances, keyed by page ID (UUID).kitten.components: Kitten’s built-in components.kitten.icons: Kitten’s built-in icon set.
Data
kitten.db: The default JSDB database for your app.kitten._db: Kitten’s internal database. Itssettingscontain the redirect tables.kitten.uploads: Uploads sent via<input type='file'>in your pages to aPOSTroute that requires sign-in, which Kitten saves inkitten.paths.APP_UPLOADS_DIRECTORY.kitten.uploadLimits: Limits on the size of a file and the number of files and fields in every request with a body, and on the size of a field, a field name, and a body.kitten.Upload: Represents an uploaded file.kitten.paths: File system paths of important Kitten resources.
The server and the app
kitten.app: The Kitten app.kitten.domain: The domain or Web Number (IP Address) Kitten is running at.kitten.port: The port number Kitten’s running at.kitten.projectIdentifier: The unique identifier for this Kitten site/app, calculated using the base path of the source code as well as the domain and port the server is running on.kitten.package: Represents the currently-installed Kitten package.kitten.appRepository: Represents the git repository of the app that Kitten is currently serving.kitten.automaticUpdates: Schedules and runs automatic updates of both Kitten itself and the app that Kitten is running.kitten.version: Kitten’s version number and related utilities.kitten.deploy: For internal use by Kitten’s web app.kitten.events: Global Kitten event emitter.kitten.requests: A truncated log of the last 25 request URLs for debugging purposes.
Libraries
kitten.libraries: Constants for well-known/supported client-side libraries meant to be referenced in page routes.kitten.WebSocket: Reference toWebSocketclass from ws.
Cryptography
kitten.crypto: Kitten Cryptography API.
Utilities
kitten.utils: Kitten utility functions and properties, includingkitten.utils.secretsMatch.kitten.log: Kitten’s logger.
Introspection
kitten.$tables: The names of the tables in your custom JSDB database (kitten.db).kitten.$showEventsOnTable: Easily listen for events on JSDB tables from the Kitten Interactive Shell (REPL).
Kitten Introspection API
Kitten provides special properties and methods that make it easier to use the Kitten Shell (REPL) to interact with and debug your app.
You have the following introspection endpoints on the global kitten object:
$tables: returns a list of the tables available onkitten.db. You can pass any of these values tokitten.$showEventsOnTable()(see below).$showEventsOnTable(<nameOfTable:string): Events that occur on the table are logged to the console. This is for debugging use in the Kitten Interactive Shell (REPL) only and does not perform listener cleanup. If you use it in production, it will lead to memory leaks (so don’t) :)
In development, when a new page connects, you will see code in the console that you can copy and paste to get a reference to that page in the REPL.
Once you have a reference to the page or any other KittenComponent instance, you can use the following properties and methods:
$info(): This method will give you an overview of the component, displaying its component hierarchy and its methods. This is the equivalent of calling the$tree()method and accessing the$methodsproperty.$tree(): Displays the component hierarchy starting from the referenced component.$methods: List of this component’s methods.$properties: List of this component’s properties.$children: Displays the names of this component’s direct child components.$componentWithId(): Returns a reference to a component using its short ID (as displayed in the$info()and$tree()methods. (The short ID is the first fragment of a Kitten Component’s UUID and looks a bit like a short git hash.)
If you use WezTerm and you want to quickly copy the page = … line to get a reference to the page using Quick Select Mode, add this to the object you return from your ~/.config/wezterm/wezterm.lua:
quick_select_patterns = {
"^page = .*?$"
},
Sectioned logs and lifecycle and event logs.
Kitten has lifecycle and event logs to help you debug your apps when you use stateful components.
While some logging will automatically be enabled when you enter Kitten’s Interactive Shell (REPL), if you want to see the logs for a given section at all times, you must manually turn it on using the new LOG environment variable. e.g.,
LOG=event,lifecycle kitten
The sectioned logs are loosely based on Node’s debuglog feature with limited support for wildcards (available only at the end of strings, so LOG='life*' will match lifecycle). You can set LOG='*' kitten to have all sections displayed.
You can also turn logging on and off and decide which sections to enable at runtime (e.g., via authored code or via the REPL), using the following methods:
| Method | Description |
|---|---|
| on()/all() | Turns on all sections. |
| off()/none() | Turns off all sections. |
| only(<LogKeys[]>) | Turns on only the sections specified in the passed array. |
| listEnabled() | Lists the enabled sections on the console. |
The available sections that are useful for authors are:
| Section | Description |
|---|---|
| lifecycle | Page and component creation, connection, removal, etc. |
| event | Event log (both client and server-originating events). |
| router | Router logs (can be very verbose). |
| verbose | Detailed logs that you will rarely need. |
| debug | For you to use as an alternative to console.log |
For detailed debugging of Kitten itself, there are also the following sections:
| Section | Description |
|---|---|
| html | HTML renderer logs |
| streamingHtml | Streaming HTML sends and updates |
| watcher | File system watcher logs |
| webSocketRoute | Logs from the WebSocketRoute class |
| pageSocketRoute | Logs from the PageSocketRoute class |
Beyond this, there is an internal repl section that is used by the Kitten REPL.
Command-line interface (CLI)
Use kitten help to access command information from your terminal.
To get detailed help on a specific command, use kitten help <command name>. For example, kitten help serve.
You can also pass the --help or -h option to any command to get more detailed information about it. So kitten serve --help is equivalent to kitten help serve.
If you have the kitty terminal installed, be aware that it includes a tool also named kitten. This can cause conflicts with the kitten CLI tool, as both share the same name. As a result, they may interfere with each other, and you may find it difficult to launch the correct tool.
In such a situation, you can always start Kitten using the full path to Kitten – ~/.local/bin/kitten – or create an alias/symbolic link to it with a different name.
Default command
serve
kitten [path to serve] [options]
kitten serve [path to serve] [options]
Serves a Kitten place.
💡 If do not specify a path to serve, the default directory (./) is assumed.
Options
--domain: Main domain name to serve the site at. Defaults tolocalhost.--aliases: Additional domains to serve the site at, as a comma-separated list. e.g.,www(short forwww.<domain>). Kitten serves the same site at every alias, and its TLS certificate includes the main domain and all aliases. Kitten ignores aliases when the main domain islocalhostor one ofplace1.localhosttoplace4.localhost.--port: The port to create the server on. Defaults to 443. Pass --port or --port=0 for random port.--open: Open the page in the default browser.--working-directory: The working directory Kitten was launched from. Defaults to current directory (default .)
When running multiple Kitten instances to test peer-to-peer web functionality during development, remember to use a different domain and port for each instance (for example, place1.localhost for one and place2.localhost:444 for the other) to ensure that sessions work correctly.
This is because Kitten sessions make sure of cookies and cookies do not provide isolation by port.
Kitten supports four localhost subdomains (place1 to place4) that can be run on any valid port for testing peer-to-peer Small Web apps locally.
An apps running on a random port gets a random data directory assigned to it. This directory is only valid for as long as the server is up. The next time you run the same app from a random port, it will get a different data directory and the data from the first run will not carry over. In other words, do not run your app on a random port if it uses a database and relies on data persistence between runs.
The random port feature is useful for local web apps that run locally on your device (the equivalent of command-line applications or native apps).
e.g., see the Markdown Preview utility in the examples folder.
Small Web apps are not meant to be run from random ports on production machines. Always deploy to run from port 443 in live environments (e.g., a VPS or a dedicated device like a single-board computer connected to your home router).
Project commands
init
kitten init [language]
Initialises a type-safe Kitten project in the current folder. language is either js or ts (the default).
kitten init:
runs
npm initif there is no package.json fileinstalls TypeScript and Kitten Types as development dependencies
adds the type configuration files (including client-globals.d.ts) and globals.d.ts, and adds a
typecheckscript to package.jsonadds
engines.kittento package.json with the API version of the Kitten you’re running (see Versioning)adds LICENSE (AGPL version 3.0), README.md, CHANGELOG.md, and .gitignore files
adds a sample src/index.page.ts (or src/index.page.js) unless there is already a src folder, or an index.page.ts (or index.page.js) file in the project folder
It skips any file that already exists. (See Type safety.)
add
kitten add [aspect]
Adds an aspect to the project in the current folder. The only aspect is type safety, which you can call types (the default), type-safety, or kitten-types.
kitten add types does the type safety part of kitten init only: it doesn’t add engines.kitten or any of the other project files. It sets up a JavaScript project if the folder has a jsconfig.json file and no tsconfig.json file, and a TypeScript project otherwise. (See For an existing project under Type safety.)
check
kitten check [path]
kitten check [path] --fix [id]
Checks your app’s source code for what you must change to run it on the Kitten you have installed, and lists each finding with the change to make. path defaults to the current folder. Run it before you move an existing app to a new Kitten API version (see Versioning).
We check the files that Kitten serves (see Valid file types), and your app modules. Markdown pages and fragments go through the same transform that Kitten’s loader uses. We never import or run your code. Instead, we parse it and render each template with Kitten’s own kitten.html and probe values, so we report what the renderer refuses or escapes. (kitten check doesn’t check types. If your package.json has a typecheck script, run npm run typecheck for that.)
Each finding is one of three kinds:
- error: code that throws, or renders wrongly, on this Kitten. We report an error only when the code alone makes it certain.
- warning: code that may be wrong, depending on a value we can’t know (e.g., an identifier interpolated into a
<script>that may be a string at run time), or code that works but that you should change (e.g., anengines.kittenthat isn’t a whole number). - notice: code that uses something whose behaviour changed, which you should look at once (e.g.,
request.uploads).
Each finding starts with an emoji for its kind (📝 for a notice, 🟠 for a warning, and ❌ for an error), its kind, the ID of its check, and its file, line, and column, followed by the change to make and a link to the change log entry or reference section that describes it. Where we can’t be sure of the line (e.g., in the text of a Markdown page), we give the file alone.
After the counts, we tell you how many findings --fix can fix, or that it can’t fix any of them.
kitten check exits with 1 when it reports an error. It also exits with 1 when it can’t run (e.g., for a path that doesn’t exist, the root or home folder, an unknown check ID, an unknown option, or a --fix it refuses). It exits with 0 otherwise, so you can run it in continuous integration.
We show every finding, whatever your package.json declares in engines.kitten. This means that a notice can still appear once you’ve made the change it describes, as we can’t tell from the code that you’ve looked at it. (Notices never change the exit code.)
These checks link here, as no change log entry describes them:
kitten-types-outdated: a@small-web/kitten-typesdependency whose major version doesn’t contain this Kitten’s types, and a dependency on, or an import of, the deprecated@small-web/kittenmarkdown-render-escaped: akitten.md.render()orkitten.md.renderInline()result interpolated into text withoutkitten.markAsTrusted, which Kitten escapessource-not-parsed: a file that Kitten can’t parse, on which no other check rantemplate-syntax-error: a template whose markupkitten.htmlcan’t parsetemplate-render-error: a template for whichkitten.htmlthrows whatever its values are (a value after an unfinished backslash escape, or a value that is part of a JavaScript or object attribute on a component tag)template-not-probed: a template that we can’t render with probe values, whose values you should check by hand
Pass --only <id> to run one check.
Pass --fix to apply the fixes of the checks that have them (icon-pascal-case, safely-add-html-renamed, and introspection-prefix), or --fix <id> to apply the fixes of one check. (Put the folder first, as in kitten check <folder> --fix <id>, or we read the folder as the ID.) We then run the checks again and print that report.
--fix changes a file only when its content is committed in Git, i.e., equals the file’s version in HEAD, so git checkout HEAD -- <file> undoes the fix. Otherwise, it lists the files and changes nothing. Pass --allow-uncommitted to change uncommitted files too. Whatever you pass, --fix:
- refuses, and changes nothing, when a file it would change is outside your project or isn’t valid UTF-8
- never applies two fixes that overlap, and reports each one it leaves
- writes nothing if a file changed after we checked it
Database commands
Run the database commands from your app’s folder. They open the databases of the app in that folder as served at localhost, port 443 (the defaults of kitten serve). (Pass --domain and --port to open the databases of the app as served at another domain or port.)
db (alias for db info)
kitten db [table name]
kitten db info [table name]
Shows database and table information.
db delete
kitten db delete [table name]
Deletes either the whole database or the table with the specified table name after asking you for confirmation.
db tail
kitten db tail <table name>
Shows a summary of the head (start) and tail (end) of your database table (remember that database tables in JSDB are append-only JavaScript logs) and starts to follow additions to it.
Press Ctrl C to exit as you would a regular shell tail command.
Options
--all: Shows every line of the table, instead of a summary of its head and tail, before following additions to it.
_db (internal database)
kitten _db [table name]
kitten _db info [table name]
kitten _db delete [table name]
kitten _db tail <table name>
The _db commands work like the db commands, on Kitten’s internal database for your app (kitten._db) instead of your app’s database. _db is an alias for _db info, and _db tail also takes the --all option.
Deployment of Kitten applications
deploy
kitten deploy <git HTTPS clone URL> [options]
Creates a Kitten place by deploying a Kitten project from a git repository as a systemd service.
kitten deploy also enables lingering for the account, so the service runs when nobody is logged in; when it cannot, it prints the loginctl command to run.
Options
--domain: Main domain name to serve the site at. Defaults to the server’s hostname. (If you pass a domain that isn’t the hostname,kitten deploychanges the hostname to match it.)--aliases: Additional domains to serve the site at, as a comma-separated list. e.g.,www(short forwww.<domain>). Kitten serves the same site at every alias, and its TLS certificate includes the main domain and all aliases.
run
kitten run <git HTTPS clone URL> [options]
Is the little brother of the deploy command. Runs a Kitten project from a git repository locally as a regular process.
Its options are the same as those of the default serve command, except --open.
Kitten daemon (systemd service) commands
status
kitten status
Shows Kitten systemd service status.
logs
kitten logs [options]
Tails (follows) the Kitten systemd service logs using journald.
Options
--since: Time span to show logs for. For example,6 hours ago,yesterday, etc. (defaults to1 hour ago).
start
kitten start
Starts the Kitten systemd service.
stop
kitten stop
Stops the Kitten systemd service.
restart
kitten restart
Stops and then starts the Kitten systemd service. If the service isn’t running, kitten restart exits with an error. (Use kitten start instead.)
enable
kitten enable
Enables the Kitten systemd service, so it starts when the server boots.
kitten deploy enables the service for you, so you only need this command after kitten disable. (Enabling doesn’t affect restarts on failure: systemd restarts the service when it fails whether or not it’s enabled.)
disable
kitten disable
Disables the Kitten systemd service, so it no longer starts when the server boots. (It doesn’t stop a running service. Use kitten stop for that.)
shell
kitten shell
Opens the interactive shell of the Kitten service running on this machine, by connecting to 127.0.0.1, port 1337. See Connecting to a Kitten service for how to use it from your own machine over SSH.
General commands
version (aliases: --version and -v)
kitten version
kitten --version
kitten -v
Displays the Kitten version, made up of:
- Date of the build (the Kitten’s birthday)
- The git commit hash of the build (as represented by the RGB colour equivalent of the hex value; the Kitten’s favourite colour)
- The API version (the major semver component from package.json.)
Your app declares the Kitten API version it is written for in its package.json, with "engines": { "kitten": "1" } (kitten init adds this for you). A deployed app then follows the newest Kitten release of that API version. Run kitten check before you add it to an existing app. (See Versioning.)
help (aliases: --help and -h)
kitten help
kitten help <command name>
kitten <command name> --help
kitten <command name> -h
Use kitten help to access command information from your terminal.
To get detailed help on a specific command, use kitten help <command name>. For example, kitten help serve.
You can also pass the --help or -h option to any command to get more detailed information about it. So kitten serve --help is equivalent to kitten help serve.
update
kitten update
kitten update --api-version=<API version>
On a development machine, kitten update installs the newest Kitten release from kittens.small-web.org. With --api-version, it installs the newest release for that API version. When the release is older than the installed Kitten, it asks before downgrading.
On a server with a deployed app, kitten update checks for an update as Check now on the Kitten Settings page does: it chooses the Kitten release and the app commit to install (see Versioning), restarts the service, and waits for the outcome. It exits with 0 when the update is confirmed or nothing is newer, 1 when it was rolled back or could not be prepared, and 2 when another update is in progress or the outcome is not known in time; kitten logs shows the server’s progress. On a server, kitten update refuses --api-version.
Note that kitten update runs its own update check beside the server’s, and if the two overlap, we may not be able to roll the update back. So, while automatic updates are on, use Check now on the Kitten Settings page instead.
The downgrade prompt shows when the installed Kitten is more recent than the release: a development build, or an API version later than the one you pass.
uninstall
kitten uninstall
Uninstalls Kitten after asking for confirmation.
kitten uninstall:
stops the Kitten service if it’s running, and disables it and removes its systemd unit file if it’s enabled
removes Kitten, its runtime, its other installed versions and runtimes, and its update records
removes the local certificate authority from your system trust stores, and deletes your localhost certificates
removes the
kittencommand (~/.local/bin/kitten)
It doesn’t remove your apps’ data, including their databases (in ~/.local/share/small-tech.org/kitten/data), deployed apps (in ~/.local/share/small-tech.org/kitten/deployments), apps you’ve run with kitten run (in ~/.local/share/small-tech.org/kitten/clones), or the Let’s Encrypt certificates for your domains (in ~/.local/share/small-tech.org/kitten/tls/global). Delete these folders yourself if you don’t need them anymore.
Troubleshooting
Here are some edge cases you might encounter (because others have encountered them) and what you can do about it:
Linux: Untrusted localhost TLS certificates in Chrom(ium)
If at some point Chrom(ium) starts complaining that your development-time localhost certificates are untrusted under Linux, check that you haven’t accidentally installed a copy of ca-certificates and/or p11-kit in your unprivileged account using a third-party package manager like Homebrew (brew).
If this is the issue, you should:
- Remove the
ca-certificatesandp11-kitpackages from Homebrew (you will also have to remove any packages that depend on them. e.g., python, OpenSSL, etc.) - Restart your machine.
- Run
sudo update-ca-trust extract - Uninstall Kitten (
kitten uninstall) - Reinstall Kitten via the one-line installation command or from your working copy of the source code (
./install)
That should do it.
To check if your system trust store is set up correctly, you can run the following command:
trust list --filter=ca-anchors | grep Localhost
And you should see output that resembles the following:
label: Localhost Certificate Authority for aral at dev.ar.al
Building Kitten
If you’re working on Kitten itself, the Build and release section of the Technical Manual covers how to build, install, and release Kitten.
Debugging
To run Kitten with the Node.js debugger (INSPECT=true), see the Debugging recipes in the Technical Manual.
Profiling
To see how long your pages take to import and render (PROFILE=true), or to generate a flame graph (FLAME_GRAPH=true), see the Debugging recipes in the Technical Manual.
Testing
Kitten’s test suites, and the npm scripts that run them, are described in the Testing section of the Technical Manual.
Deployment (of Kitten itself)
To release a new version of Kitten to kittens.small-web.org, see Releasing in the Technical Manual.
Core dependencies
| Dependency | Purpose |
|---|---|
| @small-tech/https | Drop-in replacement for Node’s native https module with automatic TLS for development and production using @small-tech/auto-encrypt and @small-tech/auto-encrypt-localhost. |
| @small-tech/jsdb | Zero-dependency, transparent, in-memory, streaming write-on-update JavaScript database that persists to JavaScript transaction logs. |
| Polka@next | Native HTTP server with added support for routing, middleware, and sub-applications. Polka uses Trouter as its router. |
| tinyws | WebSocket middleware for Node.js based on ws. |
| sanitize-html | Clean up untrusted HTML, preserving whitelisted elements and whitelisted attributes on a per-element basis. Built on htmlparser2 for speed and tolerance |
| simple-git | Git client used in deployments and for handling automatic updates in production. |
| sade | A small command-line interface (CLI) framework that uses mri for its argument parsing. |
| @noble/curves | Cryptography: converting Ed25519 keys to X25519 keys, deriving Ed25519 and X25519 public keys, and the X25519 key exchange in kitten.crypto.getSharedSecret(). (Signing, encryption key agreement, and key derivation use the Web Crypto API.) |
| @noble/ciphers | Cryptography: XChaCha20-Poly1305 encryption. |
| ed25519-keygen | Cryptography: SSH key generation from ed25519 key material. |
Kitten’s renderer is built upon xhtm and vhtml although both of those libraries have been inlined and extended.
For an automatically-generated full list of modules and contributors, please see CONTRIBUTORS.md.
Kitten Cryptography API
The Kitten Cryptography API is one module in two places: kitten.crypto on the server and /🐱/library/crypto-1.js in the browser, as an ES module. Keys are 32 bytes. Where a parameter takes hex, it takes a hexadecimal string.
A Kitten server never has a person’s secret. Call the functions that take a private key or ourPrivateKey in the browser.
Secrets and encoding
secretToEmojiString(secret): Encodes a 32-byte secret as a KittenMoji string (see Cryptographic properties).emojiStringToSecret(emojiString): Decodes a KittenMoji string to the 32-byte secret.bytesToHex(bytes): Converts aUint8Arrayto hex.hexToBytes(hex): Converts hex to aUint8Array. Throws aRangeErrorfor a string that is not hex.randomBytes(bytesLength = 32): Returns cryptographically random bytes from the Web Crypto API.random32ByteTokenInHex(): Returns 32 random bytes as hex. Use it wherever you need a secret token, for example a domain token or a webhook secret.getPublicKey(secretKey): Derives the ed25519 public key for a 32-byte secret key.
Identity creation
createKeys(domain): Creates a random 32-byte secret and returns its key material:private.ed25519(the secret asasBytesand as a KittenMojiasString),private.ssh.asString,public.ed25519(asBytesand hexasString), andpublic.ssh(asBytes,asString, andfingerprint).domainis only used in the SSH key’s comment,Kitten: person@<domain>. Kitten’s/💕/hello/page calls it in the browser.deriveKeysFromSecretKeyForDomain(secretKey, domain): Returns the key materialcreateKeys()returns for an existing secret, withoutprivate.ed25519.
Signing
sign(message, privateKey): Signs a message (bytes or hex) with an ed25519 private key (bytes, hex, or a Web CryptoCryptoKey) and returns the 64-byte EdDSA (Edwards-curve Digital Signature Algorithm) signature.verify(signature, message, publicKey): Returnstruewhen the signature is valid for the message and the ed25519 public key (bytes, hex, or aCryptoKey), andfalseotherwise, including for a malformed key or signature.
Encryption
encrypt(key, plaintext): Encrypts a UTF-8 string or bytes with XChaCha20-Poly1305 under a 32-byte key and a random 24-byte nonce, and returns nonce ‖ ciphertext.decrypt(key, encoded): Decrypts nonce ‖ ciphertext (bytes or hex) and returns the plaintext bytes. Rejects when the key is wrong or the ciphertext has been altered.
Domains
A domain’s identity is the ed25519 public key it publishes at https://<domain>/💕/id/. Where a function takes ourPrivateKey, pass the KittenMoji secret, the raw 32-byte secret, or the identity that getIdentity() returns from the key store (below).
publicKeyForDomain(domain): Fetches the ed25519 public key the domain publishes and returns its 32 raw bytes. Use it toverify()a signature made by the domain’s owner, in the browser or on a server; to pin a domain’s key and notice when it changes; or to show its fingerprint to compare in person. Rejects when the request fails, when the domain responds with an HTTP error status, or when the body is not a hex-encoded 32-byte key. Include the port in the domain when it is not 443.sharedSecretForDomain(domain, ourPrivateKey): Returns the 32-byte symmetric key shared with the domain. Maps the domain’s ed25519 public key to X25519, andourPrivateKeytoo when it is a secret, performs the Diffie-Hellman key agreement in Web Crypto, and derives the key with HKDF-SHA-256 (HMAC-based key derivation with SHA-256). The result is cached per domain.encryptMessageForDomain(message, ourPrivateKey, domain): Encrypts a string for the domain with the shared secret and returns a versioned envelope:v2:followed by the hex nonce ‖ ciphertext.decryptMessageFromDomain(encryptedMessage, ourPrivateKey, domain): Decrypts an envelope from the domain and returns the UTF-8 string. Rejects an envelope that does not start withv2:.getSharedSecret(privateKey, publicKey): Returns the raw X25519 Diffie-Hellman output for an ed25519 private key and an ed25519 public key, without HKDF. PrefersharedSecretForDomain().
Key store
In the browser, /🐱/library/key-store-1.js stores a person’s identity as non-extractable Web Crypto keys in IndexedDB, or in memory for the session when IndexedDB is unavailable. The raw secret is never persisted. Kitten’s sign-in page stores the identity and its sign-out route clears it.
getIdentity(): Returns the stored identity, ornullwhen nobody is signed in. Pass it asourPrivateKeyto the domain functions above.storeIdentity(secret): Imports a 32-byte secret as an identity and stores it.clearIdentity(): Removes the stored identity.importIdentity(secret): Imports a 32-byte secret as an identity without storing it.
An identity has signingKey (ed25519, non-extractable), keyAgreementKey (X25519, non-extractable), ed25519PublicKeyHex, and x25519PublicKeyHex. See Browser support for a WebKit limitation on X25519 keys.
Cryptographic properties
Overview
The security (and privacy) of Catalyst/Kitten are based on a 32-byte cryptographically-random secret string that only the person who owns/controls a Small Web place knows.
This is a Base256-encoded ed25519 secret key where the Base256 alphabet is a set of curated emoji surrogate pairs without any special modifiers chosen mainly from the animals, plants, and food groups with some exceptions (to avoid common phobias or triggers, etc.) that we call KittenMoji.
🐵🐒🦍🦧🐶🐕🦮🐩🐺🦊🦝🐱🐈🦁🐯🐅
🐆🐴🧮🦄🦓🦌🦬🐮🐂🐃🐄🐷🐖🐗🐽🐏
🐑🐐🐪🐫🦙🦒🐘🦣🦏🦛🐭🐁🐀🐹🐰🐇
🎈🦫🦔🦇🐻🐨🐼🦥🦦🦨🦘🦡🐾🦃🎹🐓
🐣🐤🐥🐦🐧💕🦅🦆🦢🦉🦤🪶🦩🦚🦜🚲
🐊🐢🦎📚🐉🦕🦖🐳🐋🐬🦭🐟🐠🐡🦈🐙
🐚🐌🦋🐛🐜🐝🪲🐞🦗🎭🎁🧬🪱🦠💐🌸
🎠🌈🌹🧣🌺🌻🌼🌷🌱🪴🌲🌳🌴🌵🌾🌿
🎤🍀🍁🪺👽🍇🍈🍉🍊🍋🍌🍍🥭🍎🍏🍐
🍑🍒🍓🫐🥝🍅🫒🥥🥑🍆🥔🥕🌽🧸🫑🥒
🥬🥦🧄🧅🍄🥜🌰🍞🥐🥖💩🥨🥯🥞🧇🧀
🎶🏸🎾🎨🍔🔭🍕🌭🥪🌮🌯😸📷🌜🥚🚂
🛼🚁👾👻🥗🍿🧩🖖🥫🎸🍘🍙🍚🃏🍜🍝
🍠🍢🍣🍤🍥🥮🍡🥟🥠🩰🦀🦞🦐🦑🎡🍦
🍧🍨🍩🍪🎂🍰🧁🥧🍫🍬🍭🍮🎓🍼🎮🛹
🫖🌍🌎🌏🧭🌠🪐🪀🧵🧶🧋🎉🪁🙈🙉🙊
The KittenMoji standard was frozen in time on Friday, November 25th, 2022.
The string created by joining the list of the full KittenMoji alphabet has the following hash: d9b1533de36a75c9e47f1713aada4ff332918ff0d3cada5b645ca84d73dd50d6.
When setting up a Small Web app via Catalyst, this key is generated in the person’s browser, on their own computer, and is never communicated to either the Catalyst instance or the Kitten app being installed. Instead the ed25519 public key is sent to both and signed token authentication is used when the server needs to verify the owner’s identity (e.g., before allowing access to the administration area).
We use the Web Crypto API and non-extractable keys to ensure that even if a session is intercepted by a cross-site scripting attack, the long-term secret key is still safe. (In such a hypothetical attack, if successful, the attacker will be able to sign/encrypt messages as the person who owns the Small Web site/app but will not have access to their key material.)
The expected/encouraged behaviour is for the person to store this secret in their password manager of choice.
For encryption, we use Diffie-Hellman key exchange and XChaCha20-Poly1305 where the secret key from the key exchange is run through the HKDF-SHA-256 key derivation function.
Static keys that never leave the client are a core aspect of Kitten’s usable security model. This means the number of messages encrypted with a single key is essentially unbounded. This is we use XChaCha20 which has a 192-bit nonce that’s safe to generate randomly. This let’s us avoid the added complexity of key rotation or nonce-state management.
Kitten running on a development machine can also recreate these SSH keys and configure the person’s SSH access to their server when the secret key is provided.
The person’s ed25519 public key is used as their identity within the system and enables their Small Web place (Kitten app) to communicate with the Catalyst instance for administrative reasons (e.g., to cancel hosting, etc.)
Threat model
The audience for Catalyst/Kitten and the Small Web in general is everyday people who use technology as an everyday thing and want privacy by default in the systems they use.
If you are an activist, etc., who might be specifically targetted by nation states, etc., please do not use this system as it does not protect against, for example, infiltration of hosting providers by nation state actors.
Given that the secret key material is generated in a web app, you must trust that the code being served by the server is what you expect it to be. Currently, there is no validation mechanism for this, although this is on the roadmap going forward (via, for example, a browser extension). This is not a problem unique to web apps, given that native apps are commonly dynamically built by app stores (at which point a nation state actor could inject malicious code) and given the lack of verifiable builds in mainstream supply chains.
You can, however, overcome this limitation by hosting Kitten and Catalyst yourself, on your own hardware (e.g., a single-board computer like a Raspberry Pi).
The other thing to be aware of is that the security of the system is based on your secret key remaining secret and, initially at least, there will not be a way to change this secret key. (On the longer roadmap, it would be nice to provide a means of changing it but this is not a trivial process, especially if encryption keys have been derived from it and encrypted messages exist within a Kitten app).
Browser support
WebKit cannot read an X25519 CryptoKey back from IndexedDB (WebKit bug 312279). The write succeeds but the read returns null. Sign-in works in Safari. After sign-in, getIdentity() returns null, and end-to-end encryption does not work. There is currently no acceptable workaround that doesn’t weaken the cryptographic properties of Kitten. Until the bug is fixed in WebKit, use a non-WebKit/non-Safari browser for Small Web apps that require end-to-end encryption.
Questions?
Contact Aral on the fediverse.