The BasicsResponses

Marmeon 1.2.3 — the documentation of the 1.x line. The newest version of this page: /docs/responses

V · The Basics

Responses

On this page

Introduction

What a controller returns becomes the response. Most controllers answer with a page or a redirect, and the base class Controller has a method for each kind of answer:

modules/notes/controllers/ShowNoteController.ts
import type { Authenticated } from '@marmeon/auth';
import type { Row } from '@marmeon/database';
import { Controller, type HttpContext } from '@marmeon/http';

export class ShowNoteController extends Controller {
  handle(ctx: HttpContext<Authenticated, { note: Row<'notes'> }>) {
    if (ctx.params.note.user_id !== ctx.user.id) return this.redirect().route('notes.index');
    return this.view('notes/Show', { note: ctx.params.note });
  }
}

A result is a description, not a finished response. The framework turns it into one at the end of the request, because only then does it know who asked: a browser's first visit gets a server-rendered document, a visit inside the app gets the page as JSON.

Pages

this.view(name, props) answers with a page. The name is the view's path inside its module's views/ folder: notes/Show is modules/notes/views/Show.tsx. A name without a view is a compile error, and so is a prop the view does not get, since the view takes its props from the controller's type:

modules/notes/views/Show.tsx
import type { PageProps } from '@marmeon/http';
import { Head } from '@marmeon/react';
import type { ShowNoteController } from '../controllers/ShowNoteController.ts';

export default function Show({ note }: PageProps<ShowNoteController>) {
  return (
    <main>
      <Head title={note.title} />
      <h1>{note.title}</h1>
      <p>Written {note.created_at}</p>
    </main>
  );
}

Props travel as JSON, and the view's types say so: a Date prop arrives as a string, a Map as an empty object, and a field that is undefined not at all. Send only what the page shows. Every prop reaches the browser, so a column such as a password hash must never be in it.

The status defaults to 200. A last argument of options sets another, and headers: this.view('notes/Gone', { id }, { status: 410 }). The pages page covers views, layouts and the head.

Props that load later

A prop can be more than a value. A function is called only when the response includes the prop, optional() sends a prop only when the page asks for it, defer() loads it right after the page shows, and merge() appends what a partial reload brings:

modules/notes/controllers/ShowNoteHistoryController.ts
import type { Authenticated } from '@marmeon/auth';
import type { Row } from '@marmeon/database';
import { Controller, defer, optional, type HttpContext } from '@marmeon/http';
import { NoteHistory } from '../NoteHistory.ts';

export class ShowNoteHistoryController extends Controller {
  readonly #history: NoteHistory;

  constructor(history: NoteHistory) {
    super();
    this.#history = history;
  }

  handle(ctx: HttpContext<Authenticated, { note: Row<'notes'> }>) {
    const { note } = ctx.params;
    return this.view('notes/Show', {
      note,
      history: defer(() => this.#history.of(note.id)),
      stats: optional(() => this.#history.stats(note.id)),
    });
  }
}

The deferred props page explains each of them, with islands and polling.

Shared props

Some props belong to every page: the signed-in user, the languages of a switcher. A middleware shares them with SharedData, and interface SharedProps declares their types:

middleware/ShareAppProps.ts
import { once, SharedData, type HttpContext, type Next } from '@marmeon/http';
import { Locales } from '@marmeon/i18n';

declare module '@marmeon/http/page' {
  interface SharedProps {
    /** Optional: a path without a route passes no group's middleware, and its error page has no shared props. */
    locales?: readonly string[];
    support?: { email: string };
  }
}

export class ShareAppProps {
  readonly #shared: SharedData;
  readonly #locales: Locales;

  constructor(shared: SharedData, locales: Locales) {
    this.#shared = shared;
    this.#locales = locales;
  }

  handle(_ctx: HttpContext, next: Next<{}>) {
    this.#shared.share('support', { email: 'help@example.com' }).share('locales', once(() => this.#locales.supported));
    return next();
  }
}

List the class in the web key of middleware in bootstrap/app.ts. A function is evaluated only when a page renders, at most once per request, never for a redirect or JSON. If one throws, the page fails once the others have settled, with the error of the first in prop order (shared props first). The wrappers of page props work here too. The page's own prop of the same name wins, and usePage().props reads the shared ones in any component.

Declare shared props as optional. A path that matches no route passes no group's middleware, so its 404 page renders without them, inside the same layout. The starter kit shares the signed-in user as auth, and the session shares the validation errors of the last form as errors and the conflict of a stale save as _conflict. A page's own prop called _conflict is dropped, because it would fake or hide the conflict a form shows; the shared one always wins.

To pass the app's name or a public key from configuration to the browser, share it here. See values for the browser.

Once props

once() sends a prop with the first page that has it. The browser then keeps it for as long as the tab shows the app, and tells the server which ones it holds, so the server skips them on later pages:

share('locales', once(() => this.#locales.supported));
countries: once(() => this.#countries.all(), { key: 'countries', for: { days: 1 } }),

The key lets several views share one value, and for (a Duration) sends it again after that time. A full page load, such as signing in or out, a new build or a language switch, starts over. A change of the page's language during client-side navigation (through the URL, say) sends once props again too. A once prop is for data that is the same on every page, such as a country list. Anything that changes while the page is open is a normal prop, and its value must be plain data: a Map, a function or a promise inside it is a compile error.

Redirects

this.redirect() sends the browser elsewhere. Name the route, and its parameters and query are checked against your routes:

modules/notes/controllers/StoreNoteController.ts
import type { Authenticated } from '@marmeon/auth';
import { Controller, defineRequest, type ContextOf } from '@marmeon/http';
import { rules as r } from '@marmeon/validation';
import { NoteRepository } from '../NoteRepository.ts';

export const StoreNoteRequest = defineRequest({
  schema: r.object({ title: r.string().trim().required().max(120) }),
});

export class StoreNoteController extends Controller {
  static request = StoreNoteRequest;

  readonly #notes: NoteRepository;

  constructor(notes: NoteRepository) {
    super();
    this.#notes = notes;
  }

  async handle(ctx: ContextOf<typeof StoreNoteRequest> & Authenticated) {
    const note = await this.#notes.insert({ user_id: ctx.user.id, title: ctx.body.title, body: '' });
    return this.redirect().route('notes.show', { note: note.id }, { tab: 'edit' });
  }
}
CallGoes to
this.redirect('/notes')The URL as written.
this.redirect().route(name, params, query)A named route. Parameters the path does not take go into the query.
this.back(fallback)The previous page of this site, from the Referer header, or fallback, by default /.
this.redirect().intended().route(name)The page a guest wanted before the route's guard sent them to its login, else the route.

A redirect answers a GET with 302 and every other method with 303, so the browser follows a form's PUT or DELETE with a GET. .status(301) sets another status, and .header(name, value) adds a header.

back() takes only a Referer of this host, and intended() only a path of this site, so neither can lead to another site. A referring page whose path starts with several slashes or backslashes (https://app//evil.example) is sent to /evil.example on this site, never to the host that a browser would read out of //evil.example. this.redirect(url) goes wherever you say.

A client-side visit, form submission or upload request that is answered with a redirect to another origin (this.redirect('https://other.example')) does not follow it: the server answers 409 with x-marmeon-location instead, and the browser leaves the app with a full page load. The visit's fetch would otherwise send its x-xsrf-token header on to that origin. "Another origin" is measured against the origin the request came to, so //other.example counts too. Redirects within the app, and the redirects of plain browser requests, are unchanged.

Flash data and flash messages

A redirect can carry data to the next request:

return this.back().with('email', ctx.body.email);

with(key, value), or with({ … }) for several, keeps the values in the session for the next request, where the injected Session reads them with get(). withErrors(errors) and withInput(input) flash a form's errors and its input. errors is a Record<string, readonly string[]>, the field's name ('email', or 'address.city' for a nested one) with its messages: withErrors({ email: ['Already taken.'] }). A field whose name looks secret, among them one that contains "password", "passcode", "secret", "token", "credential", "signature", "jwt", "recovery", "card", "cvc", "cvv" or "iban", an API key, private key or session id, or a one-time code (otp, totp_secret, code, sms_code, backup_codes; not footprint, zip_code, language_code or promoCode), the _token and every file are left out of the input. The names follow the rules of remembered input, without include, and every field whose name your app added with redact.keys (or a package with addKeys()) is left out as well. The framework does both for you when validation fails, so you rarely call them. The errors and the input, whichever way you flashed them, wait for the page of that submit (for five minutes at most), as the conflict of a stale save does, so a prefetch or another tab in between neither takes nor shows them; read them through the errors prop and old(). See flash data.

A flash message is something to show the user once, such as "Note saved.":

return this.redirect().route('notes.index').flash('toast', { kind: 'success', message: 'Note saved.' });

It waits in the session for the next response the user sees, and fires exactly once in the browser, where the layout shows it with useFlash('toast', …). A prefetch or an island in between never takes it. Declare the keys and their data in interface FlashData, and a wrong key or a wrong shape is a compile error:

modules/notes/flash.ts
declare module '@marmeon/http/page' {
  interface FlashData {
    toast: { kind: 'success' | 'error' | 'info'; message: string };
  }
}

export {};

A page and an action's JSON can carry a flash message too: this.view(…).flash(…) and this.json(…).flash(…). Both flash data and flash messages need a started session, so a route of the api group cannot use them: the redirect fails with an error that names the route and says to put it in the web group, or to add StartSession to its group.

JSON

this.json(data) answers with JSON. Its type travels to the browser: an action that calls the route gets result.data typed as the data the JSON carries:

modules/notes/controllers/PinNoteController.ts
import type { Authenticated } from '@marmeon/auth';
import type { Row } from '@marmeon/database';
import { Controller, type HttpContext } from '@marmeon/http';
import { NoteRepository } from '../NoteRepository.ts';

export class PinNoteController extends Controller {
  readonly #notes: NoteRepository;

  constructor(notes: NoteRepository) {
    super();
    this.#notes = notes;
  }

  async handle(ctx: HttpContext<Authenticated, { note: Row<'notes'> }>) {
    await this.#notes.update(ctx.params.note.id, { pinned: true });
    return this.json({ pinned: ctx.params.note.id });
  }
}

The status defaults to 200; this.json(data, { status: 201 }) sends another. this.json(undefined) answers 204 with no body. An API client gets the same JSON, and the actions page shows how a page calls such a route without leaving.

Conflict

conflict(current) answers a save that went stale: someone else changed the record first. It is a function you import from @marmeon/http, not a method of the controller. Return it, do not throw it. A data layer that gives a Result maps its err to it:

modules/notes/controllers/SaveNoteController.ts
import { can } from '@marmeon/auth';
import type { Row } from '@marmeon/database';
import { conflict, Controller, defineRequest, type ContextOf } from '@marmeon/http';
import { rules as r } from '@marmeon/validation';
import { NotePolicy } from '../policies/NotePolicy.ts';
import { NoteRepository } from '../NoteRepository.ts';

export const SaveNoteRequest = defineRequest({
  schema: r.object({ body: r.string().required(), version: r.integer().required() }),
  authorize: can(NotePolicy, 'update', 'note'),
});

export class SaveNoteController extends Controller {
  static request = SaveNoteRequest;

  readonly #notes: NoteRepository;

  constructor(notes: NoteRepository) {
    super();
    this.#notes = notes;
  }

  async handle(ctx: ContextOf<typeof SaveNoteRequest, { note: Row<'notes'> }>) {
    const saved = await this.#notes.saveIfCurrent(ctx.params.note.id, ctx.body.body, ctx.body.version);
    if (!saved.ok) return conflict({ version: saved.error.version, body: saved.error.body });
    return this.json({ version: saved.value.version });
  }
}

An action gets { kind: 'conflict', current, message }, with current typed as Serialize<T> (what JSON makes of it). An API client gets status 409 with { message, current } and the header x-marmeon-conflict: 1. message is the framework's text in the request's language; conflict(current, { message: 'notes.stale' }) sends a text of yours or a key of your language files. The second argument takes message and nothing else; any other option is a TypeError.

The answer to an action or an API client is never cached, takes no flash messages and never carries a location. A request that asks for a page, such as a visit or a form of useForm, or a request whose first accepted type is HTML, such as a form posted without JavaScript, is answered like a failed validation: it goes back to the page it came from (the Referer, else /), and the session keeps the conflict and the input of the form for that page. The page of the document that sent the form takes it, once; a prefetch or another tab's request in between leaves it waiting. The form shows it as form.conflict; see forms.

Going back needs a write (POST, PUT, PATCH or DELETE) in a route with a session, such as the web group. A request that asks for a page and is a GET, or reaches a route without a session, answers 406, whatever headers the client sent: an API route never turns into a redirect or a failure. An action or a JSON client still gets the 409. Every other request is answered, an API client with no Accept header or with */* included. A table's action cannot return it; see tables.

Other results

ResultResponse
A Response made by your codeGoes out as it is.
A stringText: text/plain; charset=utf-8, the body as written.
An Html, from the html templateHTML: text/html; charset=utf-8.
An object or an arrayJSON.
null or undefinedAn empty 204.

A Response that your code made goes out as it is, also a subclass of Response and a clone of one. A Response from fetch() or its clone, Response.error(), and one whose body is read or locked are refused with a TypeError, and the request answers 500. fetch() has already decoded a compressed body, so build a Response of your own from its body and the headers you choose to pass on, and leave out Content-Encoding and Content-Length. The refusal applies to what a route, a table action and the error handler return. A middleware that returns such a Response sends it as it is, every header included, so a middleware builds a Response of its own from the body and the headers it chooses, without Content-Encoding and Content-Length.

HTML you write yourself

The html template of @marmeon/core escapes every value it interpolates, so a name like <script> arrives as text:

modules/notes/controllers/ShowNoteSnippetController.ts
import type { Row } from '@marmeon/database';
import { html } from '@marmeon/core';
import { Controller, type HttpContext } from '@marmeon/http';

export class ShowNoteSnippetController extends Controller {
  handle(ctx: HttpContext<{}, { note: Row<'notes'> }>) {
    const { note } = ctx.params;
    return html`<article><h1>${note.title}</h1><p>${note.body}</p></article>`;
  }
}

Its result goes out as text/html; a plain string with the same characters goes out as text. Nested templates and lists of them stay markup, and null, undefined and false vanish. raw(markup) marks markup you trust, never input. The escaping covers text and quoted attributes, not URLs: put only links you built yourself into an href. A script tag in such HTML needs the response's nonce, ctx.nonce(), under a Content-Security-Policy.

Headers

A redirect takes headers with .header(name, value). A page or JSON takes them, and its status, in a last argument of options: this.view(name, props, { status, headers }) and this.json(data, { status, headers }). The functions view() and json() of @marmeon/http take the same options:

modules/notes/controllers/ShowDraftController.ts
import type { Authenticated } from '@marmeon/auth';
import type { Row } from '@marmeon/database';
import { Controller, type HttpContext } from '@marmeon/http';

export class ShowDraftController extends Controller {
  handle(ctx: HttpContext<Authenticated, { note: Row<'notes'> }>) {
    return this.view('notes/Show', { note: ctx.params.note }, { headers: { 'x-robots-tag': 'noindex' } });
  }
}

The view's props are typed from this controller the same way. A header that every response of some routes needs belongs in a middleware, which the middleware page shows.

Pages of a signed-in user go out with Cache-Control: no-store, private, so the browser does not show them again after a sign-out. A route that may be kept sets its own header, for example with the cacheControl() middleware:

Route.middleware(authenticate()).middleware(cacheControl('private, max-age=60')).authorize(everyone).get('/notes/report', ShowReportController);

Never use public for anything that depends on the user: a shared cache would hand it to the next visitor. A page whose URL is a credential takes the credentialPage() middleware instead; it also sets Referrer-Policy: no-referrer, so the token does not leave in a Referer. That leaves back() without a Referer on such a page: a form on it returns by an explicit redirect. See a link that is a credential.

A response that sets a cookie, or belongs to a session, is never shared: the framework turns public into private (dropping s-maxage, proxy-revalidate, CDN-Cache-Control and Surrogate-Control) and logs a warning once per route. Cache public pages in a group without the session. Such a page's islands run without the visitor's cookies, and an island whose route starts the session loads in the browser instead (how islands load).

Since that answer stays in the browser's cache, the app signs out with history.clear({ siteData: ['cache', 'storage'] }) after signOut(); see the browser's storage on sign-out.

Protocol headers

A page and its JSON are the same URL: the client sends request headers that change the answer, so a shared cache in front of the app must keep one copy per combination. @marmeon/http/protocol exports their names: PAGE_HEADER (x-marmeon, the client wants the page object as JSON; its value is PROTOCOL_VERSION), REGION_HEADER (an island or a layer), PARTIAL_COMPONENT_HEADER, PARTIAL_DATA_HEADER and PARTIAL_EXCEPT_HEADER (a partial reload), PURPOSE_HEADER (a prefetch, with the browser's own sec-purpose), ONCE_HEADER and ONCE_SCOPE_HEADER (the once props the tab holds) and VERSION_HEADER (the build the client runs). A middleware that caches publicly names all of them in Vary; leaving one out lets the cache serve an island, a partial reload or a page without its once props to a request that asked for another:

modules/site/middleware/CachePublicly.ts
import {
  ONCE_HEADER,
  ONCE_SCOPE_HEADER,
  PAGE_HEADER,
  PARTIAL_COMPONENT_HEADER,
  PARTIAL_DATA_HEADER,
  PARTIAL_EXCEPT_HEADER,
  PURPOSE_HEADER,
  REGION_HEADER,
  VERSION_HEADER,
} from '@marmeon/http/protocol';

export const PAGE_VARY = [
  PAGE_HEADER,
  REGION_HEADER,
  PARTIAL_COMPONENT_HEADER,
  PARTIAL_DATA_HEADER,
  PARTIAL_EXCEPT_HEADER,
  PURPOSE_HEADER,
  'sec-purpose',
  ONCE_HEADER,
  ONCE_SCOPE_HEADER,
  VERSION_HEADER,
];

An app with package entries adds ENTRY_HEADER (x-marmeon-entry, the document the tab runs in) to that list: the same URL is a page for one document and a 409 for another.

The same entry has the PageObject and RegionObject types of the answer, and the checks isPrefetch(request), isActionRequest(request) and regionOf(request). The header names and the page object are public API, so a change to them is a breaking change of the framework. The types you augment (Views, SharedProps, FlashData) are in @marmeon/http/page.

Cookies

ctx.cookies.set(name, value, options) queues a cookie for whatever response the request ends with, a page, a redirect or an error page alike. The requests page covers the options and their defaults.

Downloads

serveFile() of @marmeon/storage answers with a file of a disk:

modules/notes/controllers/DownloadAttachmentController.ts
import type { Authenticated } from '@marmeon/auth';
import type { Row } from '@marmeon/database';
import { Controller, type HttpContext } from '@marmeon/http';
import { serveFile, Storage } from '@marmeon/storage';

export class DownloadAttachmentController extends Controller {
  readonly #storage: Storage;

  constructor(storage: Storage) {
    super();
    this.#storage = storage;
  }

  handle(ctx: HttpContext<Authenticated, { attachment: Row<'attachments'> }>) {
    const { attachment } = ctx.params;
    return serveFile(this.#storage.disk('local'), attachment.path, ctx.request, { cacheControl: 'private, no-store', filename: attachment.name });
  }
}

The file streams from the disk with X-Content-Type-Options: nosniff and Content-Security-Policy: sandbox. Everything but raster images goes out as an attachment, so HTML, SVG or a PDF is downloaded instead of shown on your app's origin. A missing file is a 404. The route's middleware and policy decide who may download: check them as for any other route.

A file your code makes, a JSON export say, goes out as a Response of its own. contentDisposition() of @marmeon/http names it (@marmeon/storage exports the same function): the encoder serveFile() and the table exports use, safe for any name, even one made from what a person typed. The header gets an ASCII fallback in which quotes, backslashes, slashes, percent signs, control characters and non-ASCII characters are _ (a line break cannot split the header), and the real name as filename* (UTF-8, RFC 8187). Use 'inline' instead of 'attachment' only for a type a browser may show on your app's origin, a raster image.

modules/account/controllers/ExportProfileController.ts
import type { Authenticated } from '@marmeon/auth';
import { contentDisposition, Controller, type HttpContext } from '@marmeon/http';

export class ExportProfileController extends Controller {
  handle(ctx: HttpContext<Authenticated>) {
    return new Response(JSON.stringify({ name: ctx.user.name, email: ctx.user.email }, null, 2), {
      headers: {
        'content-type': 'application/json; charset=utf-8',
        'content-disposition': contentDisposition('attachment', `${ctx.user.name}-profile.json`),
        'cache-control': 'private, no-store',
        'x-content-type-options': 'nosniff',
      },
    });
  }
}

private, no-store keeps a shared cache from holding one account's data. The name keeps the characters of the person's name (Zoë-profile.json downloads as written); the length is not limited, so cut a long one yourself.

A generated image of a one-time link, say a QR code, is as secret as the link, so its route takes credentialPage():

Route.middleware(credentialPage()).authorize(everyone).get('/invites/:token/code.png', ShowInviteCodeController);

A test reads the image with bytes():

const image = await app.get(`/invites/${token}/code.png`).assertOk().assertHeader('content-type', 'image/png');
expect(Array.from(image.bytes().slice(0, 4))).toEqual([0x89, 0x50, 0x4e, 0x47]);

A file the browser should fetch later, say from a mail, gets a signed link instead: await this.#storage.disk('local').temporaryUrl(key, { expiresIn: { minutes: 5 } }). Redirect to it, or send it along. The file storage page covers disks and their URLs.

Testing

A test asserts what a controller answered:

modules/notes/notes.test.ts
import { createTestApp, type TestApp } from '@marmeon/testing';
import { beforeEach, it } from 'vitest';
import application from '../../bootstrap/app.ts';
import { UserFactory } from '#modules/auth';
import type { ShowNoteController } from './controllers/ShowNoteController.ts';
import { NoteRepository } from './NoteRepository.ts';

let app: TestApp;
beforeEach(async () => {
  app = await createTestApp(application, { database: 'refresh' });
});

it('shows a note to its author', async () => {
  const ada = await app.factory(UserFactory).create();
  const note = await app.make(NoteRepository).insert({ user_id: ada.id, title: 'Draft', body: '' });
  await app.actingAs(ada).get(`/notes/${note.id}`).assertOk().assertPage<ShowNoteController>('notes/Show', { note: { title: 'Draft' } });
});

assertRedirect(url), assertJson(data), assertFlash(key, data) and assertHeader(name, value) check the other kinds of answer. The HTTP tests page covers every assertion.