Reference sections
Reference › 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 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.
- 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 and theWWW-Authenticate: Bearerheader, 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 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()).
- Kitten registers the routes you add with the
routerobject after 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). (Kitten doesn’t check regular expression patterns.) - A route you add with the
routerobject stores the session the first time your handler writes to it or reads itsidproperty, 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 the
routerobject don’t respond to WebSocket upgrades.
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.
is (array|string): returns true/false based on whether thecontent-typeheader of 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.
withCode(code, [body]): Shorthand for setting the.statusCodeproperty on theresponseobject and calling theresponse.end()method 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 responds with 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.