Skip to content

Recipes ​

A complete JSON API that reads its bodies with @routup/body is the REST API example on routup.dev.

JSON With a Size Limit ​

limit caps the body size: for a larger body, readRequestBody() throws and the request answers 413.

ts
import { App, defineCoreHandler } from 'routup';
import { body, readRequestBody } from '@routup/body';

export const app = new App();

// JSON only, up to 10 kB; URL-encoded bodies are not parsed
app.use(body({ json: { limit: '10kb' } }));

app.post('/notes', defineCoreHandler(async (event) => {
    const note = await readRequestBody(event);

    event.response.status = 201;

    return note;
}));
bash
curl -i -X POST http://localhost:3000/notes \
    -H 'content-type: application/json' \
    -d "{\"text\":\"$(head -c 20000 /dev/zero | tr '\0' x)\"}"
# HTTP/1.1 413 Payload Too Large
#
# {"status":413,"message":"request entity too large"}

Since only json is set, a form body is not parsed and readRequestBody() returns {}.

HTML Form ​

A form posts application/x-www-form-urlencoded. A field sent more than once, such as a group of checkboxes, arrives as an array.

ts
import { App, defineCoreHandler } from 'routup';
import { body, readRequestBody } from '@routup/body';

export const app = new App();

app.use(body({ urlEncoded: { parameterLimit: 20 } }));

// <form method="post" action="/subscribe"> with an email field and tag checkboxes
app.post('/subscribe', defineCoreHandler(async (event) => {
    const email = await readRequestBody(event, 'email');
    const tags = await readRequestBody(event, 'tags');

    return {
        email,
        // one checked box gives a string, several give an array
        tags: typeof tags === 'string' ? [tags] : (tags ?? []),
    };
}));
bash
curl -X POST http://localhost:3000/subscribe -d 'email=ada@example.com&tags=news&tags=releases'
# {"email":"ada@example.com","tags":["news","releases"]}

More than 20 fields answer 413 (too many parameters).

Verify a Webhook Signature ​

A signature is computed over the exact bytes the sender posted, so the route reads them before parsing. With cache: true on raw, the JSON parser reuses the cached bytes instead of reading the consumed body again.

ts
import { App, defineCoreHandler } from 'routup';
import { body, readRequestBody, readRequestBodyArrayBuffer } from '@routup/body';

export const app = new App();

const key = crypto.subtle.importKey(
    'raw',
    new TextEncoder().encode('webhook-secret'),
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['verify'],
);

function fromHex(input: string): Uint8Array<ArrayBuffer> {
    // Uint8Array.fromHex() is not available on Node.js 24
    // eslint-disable-next-line unicorn/prefer-uint8array-hex
    return new Uint8Array((input.match(/../g) ?? []).map((byte) => Number.parseInt(byte, 16)));
}

// keep the raw bytes, so the JSON parser reuses them
app.use(body({ json: true, raw: { limit: '1mb', cache: true } }));

app.post('/webhook', defineCoreHandler(async (event) => {
    const bytes = await readRequestBodyArrayBuffer(event);
    const signature = fromHex(event.headers.get('x-signature') ?? '');

    if (!await crypto.subtle.verify('HMAC', await key, signature, bytes)) {
        event.response.status = 401;

        return { error: 'invalid signature' };
    }

    const payload = await readRequestBody(event);

    return { received: payload.type };
}));
bash
payload='{"type":"invoice.paid"}'
signature=$(printf '%s' "$payload" | openssl dgst -sha256 -hmac webhook-secret | sed 's/^.* //')
curl -X POST http://localhost:3000/webhook \
    -H 'content-type: application/json' \
    -H "x-signature: $signature" \
    -d "$payload"
# {"received":"invoice.paid"}

crypto.subtle.verify() compares in constant time, and Web Crypto runs on every runtime routup supports.

Plain Text Upload ​

readRequestBodyText() reads the body as a string whatever its content-type, here a CSV file.

ts
import { App, defineCoreHandler } from 'routup';
import { body, readRequestBodyText } from '@routup/body';

export const app = new App();

app.use(body({ text: { limit: '100kb' } }));

// POST a CSV file: one "name,email" line per contact
app.post('/contacts/import', defineCoreHandler(async (event) => {
    const csv = await readRequestBodyText(event);
    const contacts = csv
        .split('\n')
        .filter((line) => line.trim() !== '')
        .map((line) => {
            const [name, email] = line.split(',');

            return { name, email };
        });

    return { imported: contacts.length, contacts };
}));
bash
printf 'Ada,ada@example.com\nAlan,alan@example.com\n' | \
    curl -X POST http://localhost:3000/contacts/import -H 'content-type: text/csv' --data-binary @-
# {"imported":2,"contacts":[{"name":"Ada","email":"ada@example.com"},{"name":"Alan","email":"alan@example.com"}]}

A Different Limit per Path ​

Each body() stores its options on the request, and the last one to run wins. A second body() mounted under a path raises the limit for the routes below it only.

ts
import { App, defineCoreHandler } from 'routup';
import { body, readRequestBody } from '@routup/body';

export const app = new App();

app.use(body({ json: { limit: '10kb' } }));
// registered later, so its options win below /import
app.use('/import', body({ json: { limit: '1mb' } }));

app.post('/notes', defineCoreHandler(async (event) => readRequestBody(event)));

app.post('/import/notes', defineCoreHandler(async (event) => {
    const notes = await readRequestBody(event);

    return { imported: Array.isArray(notes) ? notes.length : 0 };
}));

An array of notes of 24 kB is imported under /import/notes and answers 413 under /notes. To parse bodies only below a path and not at all elsewhere, mount a single body() with that path (Combining Plugins).