Open in a new tab

POST JSON to an API with a bearer token and a timeout, retry when the server is busy, give up at once on the caller's own mistakes, and show the error message the server sent back.

Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

Any page that writes to your backend: a form that saves, a button that creates something. A busy or restarting server (429, 503) or a dropped connection deserves a few retries with a growing delay; a wrong token (401) or invalid data (422) never does, and the user should read the server's reason, not "something went wrong".

Copy-paste steps

  1. npm install @awacloud/fw
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html, main.js and stand-in-api.js next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link.
  4. In your app, delete stand-in-api.js and its import, point api at your API base, and read the token from your sign-in flow, never from the page.

What it shows

  • ajax(base, { timeout }) gives a client; api.post(path, body, { headers }) sends a plain object as JSON with Content-Type: application/json and parses the JSON answer. Per-request headers add to the client's defaults, which is where an Authorization: Bearer … header goes.
  • A failed status rejects with api.HttpError: status, and the raw response, whose JSON body carries the server's own message.
  • withRetry(call, { attempts, baseMs }): retries when there was no answer (network, timeout) or the answer was 429 or 5xx, with a delay that doubles each time; any other 4xx, or an abort, fails at once. Each retry is logged, so the user sees why the save took longer.
  • stand-in-api.js answers POST ./api/notes inside the page, like a server would (401 without the right token, 422 for an empty note, 503 on a first try while "busy", 201 with the new note), so the example runs anywhere. Every other request goes to the real fetch.

Code

main.js

javascriptApache-2.077 lines

// SPDX-License-Identifier: Apache-2.0
// The stand-in answers ./api/notes in the page itself; in your app, delete this import and the file.
import { standIn } from './stand-in-api.js';
import fw from '@awacloud/fw';
import { ajax } from '@awacloud/fw/dom/net/ajax.js';

fw.runtime.registerAllDeep([ajax]);
export { standIn };

// One client for the API: its base is resolved from the page URL, never an absolute literal.
export const api = fw.runtime.resolve('ajax')(new URL('./api/', location.href).href, { timeout: 5000 });

/**
 * Retry what is worth retrying: no answer (network, timeout), 429 and 5xx.
 * Other 4xx are the caller's mistake and fail at once. Backoff doubles.
 * @template T
 * @param {() => Promise<T>} call
 * @param {{ attempts?: number, baseMs?: number,
 *   onRetry?: (r: { attempt: number, delay: number, error: any }) => any }} [o]
 * @returns {Promise<T>}
 */
export async function withRetry(call, { attempts = 3, baseMs = 300, onRetry = () => {} } = {}) {
    for (let attempt = 1; ; attempt++) {
        try {
            return await call();
        } catch (/** @type {any} */ error) {
            const status = error?.status;
            const transient = status === undefined ? error?.name !== 'AbortError' : status === 429 || status >= 500;
            if (!transient || attempt >= attempts) throw error;
            const delay = baseMs * 2 ** (attempt - 1);
            await onRetry({ attempt, delay, error });
            await new Promise((resolve) => setTimeout(resolve, delay));
        }
    }
}

const logList = /** @type {HTMLElement} */ (document.getElementById('log'));
/** @param {string} line */
const log = (line) => { logList.appendChild(document.createElement('li')).textContent = line; };

/** An HttpError's status and the `error` field of its JSON body, or a network message. @param {any} error */
async function describe(error) {
    if (!(error instanceof api.HttpError)) return /** @type {Error} */ (error).message;
    const body = await error.response.clone().json().catch(() => ({}));
    return `HTTP ${error.status}${body.error ? ` (${body.error})` : ''}`;
}

/**
 * POST one note as JSON with a bearer token, retried when the server is busy.
 * @param {string} text @param {string} token @param {Parameters<typeof withRetry>[1]} [retry]
 * @returns {Promise<{ id: number, text: string } | null>} the created note, or null when it failed
 */
export async function saveNote(text, token, retry) {
    logList.replaceChildren();
    const post = () => api.post('notes', { text }, { headers: { Authorization: `Bearer ${token}` } });
    try {
        const note = await withRetry(post, {
            ...retry,
            onRetry: async ({ attempt, delay, error }) => {
                log(`attempt ${attempt} failed: ${await describe(error)}, retrying in ${delay} ms`);
            },
        });
        log(`saved as note #${note.id}`);
        return note;
    } catch (error) {
        log(`not saved: ${await describe(error)}`);
        return null;
    }
}

const busy = /** @type {HTMLInputElement} */ (document.getElementById('busy'));
busy.addEventListener('change', () => { standIn.busy = busy.checked; });
document.getElementById('save')?.addEventListener('submit', (event) => {
    event.preventDefault();
    const field = (/** @type {string} */ id) => /** @type {HTMLInputElement} */ (document.getElementById(id)).value;
    saveNote(field('text'), field('token'));
});

index.html

htmlApache-2.031 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>fw · Call a JSON API with auth, timeouts and retries</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Call a JSON API with auth, timeouts and retries</h1>
    <p>The API here is a stand-in that runs in the page: <code>POST ./api/notes</code> with a bearer token
      <code>demo-token</code>.</p>
    <form id="save">
      <p><label for="token">Token</label> <input id="token" type="text" value="demo-token" autocomplete="off"></p>
      <label for="text">Note</label>
      <textarea id="text" rows="3">Buy milk</textarea>
      <p><label><input id="busy" type="checkbox" checked> Server busy on the first try (answers 503)</label></p>
      <p><button type="submit">Save the note</button></p>
    </form>
    <h2>What happened</h2>
    <ol id="log" aria-live="polite"></ol>
  </main>
</body>
</html>

stand-in-api.js

javascriptApache-2.038 lines

// SPDX-License-Identifier: Apache-2.0
// A stand-in for YOUR server, so this page runs anywhere, also with no backend:
// it answers POST …/api/notes the way a JSON API would. Delete this file and
// its import in your app; every other request goes to the real fetch.

export const standIn = {
    /** Answer the first try of each save with 503, so the retry shows. */
    busy: true,
    /** What each request carried, newest last. @type {object[]} */
    calls: [],
};
const notes = [];
let refusedLast = false;
const realFetch = globalThis.fetch.bind(globalThis);
/** @param {number} status @param {object} body */
const json = (status, body) => new Response(JSON.stringify(body), {
    status, headers: { 'Content-Type': 'application/json' },
});

/** @param {RequestInfo | URL} input @param {RequestInit} [init] */
globalThis.fetch = async (input, init = {}) => {
    const url = new URL(input instanceof Request ? input.url : String(input), location.href);
    if (!url.pathname.endsWith('/api/notes')) return realFetch(input, init);
    const headers = new Headers(init.headers);
    const body = typeof init.body === 'string' ? init.body : '';
    standIn.calls.push({
        method: init.method, body,
        authorization: headers.get('Authorization'), contentType: headers.get('Content-Type'),
    });
    await new Promise((resolve) => setTimeout(resolve, 30)); // a little latency
    if (headers.get('Authorization') !== 'Bearer demo-token') return json(401, { error: 'unknown token' });
    refusedLast = standIn.busy && !refusedLast;
    if (refusedLast) return json(503, { error: 'busy, try again' });
    const text = String(JSON.parse(body || '{}').text ?? '').trim();
    if (!text) return json(422, { error: 'text is required' });
    notes.push(text);
    return json(201, { id: notes.length, text });
};