Skip to main content
Login

Sign in to access your account

Request - National Design System

A fetch wrapper that adds a timeout, a response size cap and an error on a failed status, then returns the body as JSON or text

Overview

NDS.request(url, options) calls fetch and returns a promise of { isJson, data }. It handles the response only. Your code builds the request, shows the loading state and writes the result into the page. It does not return the response headers or the final URL after a redirect. Call fetch yourself when you need them.

It is in the main bundle, so every page has it, with no init call. Every NDS component that loads data uses it, except File Upload.

Pick another component when:

  • the user uploads a file and needs a progress bar: File Upload

Usage

Read JSON from an endpoint. A failed status rejects the promise, so a 404 reaches the catch.

async function loadServices() { try { const { data } = await NDS.request('/api/services', { json: true }); renderServices(data); } catch (error) { if (error.status === 404) return showEmptyState(); showError(); } }

Cancel a search when a newer search replaces it.

let controller; async function search(term) { if (controller) controller.abort(); controller = new AbortController(); const { signal } = controller; setLoading(true); try { const { data } = await NDS.request(`/api/search?q=${encodeURIComponent(term)}`, { signal, json: true }); renderResults(data); } catch (error) { // A newer search aborted this one. if (error.name === 'AbortError') return; showError(); } finally { // A newer search owns the loading state: clear it only from the latest one. if (controller.signal === signal) setLoading(false); } }

Built-in Features

  • Timeout by Default

    A request aborts after 15 seconds unless you set timeout. When a server never answers, the promise rejects with a TimeoutError.

  • Response Size Cap

    The body is read as a stream and cancelled once it passes maxBytes. When the Content-Length header is already over the cap, the body is refused unread.

  • Combined Abort Signals

    Your signal and the timeout control the same request. Either one aborts it, and the error name says which.

  • JSON or Text

    The Content-Type header decides how the body is read. json: true parses it as JSON whatever the header says.

  • Errors With a Status

    A failed status rejects with an error that holds the HTTP code, the URL and the start of the response body.

  • Fetch Options

    Every other option goes to fetch unchanged, such as method, headers, body and credentials.

  • Older Safari

    Safari before 17.4 has no AbortSignal.any. There, NDS.request combines the signals itself, and the error names stay the same.

Best Practices

  • Use NDS.request wherever you would call fetch to read a response.
  • Pass json: true when you know the endpoint returns JSON. Some servers label JSON as text/plain, and data is then a string.
  • Raise maxBytes for an HTML fragment. A full page of markup can pass 1 MB.
  • Set timeout: 0 only for a connection that stays open on purpose, such as a long poll.
  • Branch on error.status and error.name, not on the message. Only the size error needs its message.
  • Ignore an AbortError in the catch. It comes from your own abort() call, so the user saw no failure.
  • Log error.body with the status. It shows what the server said.
  • For a fallback value instead of an error on a failed status, wrap the call: const optional = (url, opts) => NDS.request(url, opts).catch(err => err.status ? null : Promise.reject(err));
  • Write retry, caching or interceptors in your own code: NDS.request has none. The browser’s HTTP cache still works, as it does for fetch.
  • Check that a request is safe to send twice before you retry it. A form submission may not be.

API

Options

Option Default Effect
timeout 15000 Milliseconds before the request aborts with a TimeoutError. 0 turns the timeout off
maxBytes 1048576 (1 MB) The largest response body, in bytes. A larger body rejects the promise
json the Content-Type header true parses the body as JSON, and false returns it as text. Without it, the body is parsed only when Content-Type holds application/json
signal none Your own AbortSignal. It aborts the request together with the timeout: the first one to fire wins
any other option — Passed to fetch unchanged, such as method, headers, body, credentials and cache. A JSON body needs JSON.stringify() and its own Content-Type header, as with fetch

Result

Property Holds
isJson true when the body was parsed as JSON
data The parsed JSON, or the body as text. An empty body gives '', also with json: true

Failures

The promise rejects with an error. Tell the failures apart by these tests:

Failure Test Detail
A status outside 200 to 299 error.status is set status is the HTTP code, and url is the URL you passed. body holds up to 512 characters of the response, or undefined when they cannot be read
Timeout error.name === 'TimeoutError' The request passed timeout
Your signal aborted error.name === 'AbortError' The name is AbortError only when you call abort() with no reason. A reason you pass to abort() becomes the error
Body too large error.message === 'Response too large' The Content-Length header, or the body read so far, passed maxBytes
Network failure error.name === 'TypeError' fetch got no response: the network is down, or the browser blocked the request
Invalid JSON error.name === 'SyntaxError' The body was parsed as JSON and was not valid JSON

JavaScript

Method Effect
NDS.request(url, options) Sends the request. Returns a promise of { isJson, data }
// Post a form and read the HTML fragment it returns. // A page of markup can pass 1 MB, so raise the cap to 4 MB. const form = document.querySelector('#search-form'); const { data } = await NDS.request(form.action, { method: 'POST', body: new FormData(form), maxBytes: 4194304 }); // data holds the HTML as text.

The full API is in the banner of _js/nds-core.js, and in the comment above NDS.request there.

Last Modified Date: 20/10/2026 - 07:46 AM
Was this page useful?
60% of users said Yes from 2843 Feedbacks