Kitten

Reference sections

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 creating 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 the hx-get or hx-post attribute 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. When a route returns a value that Kitten cannot send, Kitten responds with 500 and 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> elements 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 })
}

The response.sendFile() method serves any path it is given, and a route parameter can contain an encoded /, so take only the last part of a parameter with the path.basename() function, as the example does, before you join it onto a folder.

Every response from a page, a route, or a static file has the X-Content-Type-Options: nosniff header, 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.)

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 the authorise function before it reads the request body. It can be sync or async.

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 the kitten.utils.secretsMatch(expected, candidate) method 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 the Expect: 100-continue header, as curl does for bodies over 1 MB. Kitten sends 100 Continue only once it starts reading the body.

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()).

Middleware you add with router.use() runs before any route parses the request body, so the request.body and request.files properties are empty ({}) there. Middleware reads headers; routes read bodies. In development, the first time middleware reads the request.body property 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 property. (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 export, 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.

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.

Like this? Fund us!

Small Technology Foundation is a tiny, independent not-for-profit.

We exist in part thanks to patronage by people like you. If you share our vision and want to support our work, please become a patron or donate to us today and help us continue to exist.