Kitten

Reference sections

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 the request.uploads array is empty, and the request.discardedFiles property 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).

The kitten.uploadLimits object sets the limits applied to requests that have a body.

The defaults:

If a request exceeds any of the limits, Kitten deletes all files in the request. Unless the route responds through its onUploadLimit hook, 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 export (e.g., uploadLimits.fileSize in uploadšŸ”’/small/index.post.js), the kitten.uploadLimits object (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, the onUploadLimit hook runs for the files, fieldSize, and body limits, and never for the fileSize limit. 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 a 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 response. 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 the fields limit must be at least 1. Kitten checks the kitten.uploadLimits object 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.)

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 the kitten.uploadLimits object for requests to that route. The others come from the kitten.uploadLimits object, and then from Kitten’s defaults. A limit in the uploadLimits export 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 the kitten.uploadLimits.fileSize limit 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 export by the same rules as the kitten.uploadLimits object 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 the kitten.uploadLimits.fileSize limit.

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 object has the following properties:

Every upload is served with the Content-Security-Policy: sandbox header. An upload whose type is not on that list downloads when its URL is opened; one shown in an <img>, <video>, or <audio> element displays as before.

Kitten serves an upload with the Accept-Ranges: bytes and Content-Length headers, responds to a Range request for one range with 206 Partial Content and those bytes, to an unsatisfiable one with 416 Range Not Satisfiable, and to a HEAD request with the headers alone. A <video> or <audio> element can seek in an upload.

An upload is private by default. Kitten serves a private upload only to you, once you’re signed in, with the Cache-Control: private header 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 the Access-Control-Allow-Origin: * header. The public property 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.)

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 }.
}

Kitten sends the return value of the onUploadLimit hook 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.

The kitten.uploads object contains all uploads made to a POST route that requires sign-in or exports authorise, keyed by ID, in Kitten’s internal database:

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.

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.