Quick start
Install Relay, make a request, handle errors and share defaults across your app. This takes about five minutes.
On this page
Steps
#Install the package
Relay is published to npm as
@relayhttp/relay. Use whichever package manager your project already uses:npm install @relayhttp/relaypnpm add @relayhttp/relayyarn add @relayhttp/relaybun add @relayhttp/relay#Make your first request
Import the default export and call one of the method helpers. Chain
.json(),.text()or.blob()to read the body.posts.jsimport relay from '@relayhttp/relay'; const posts = await relay.get('https://api.example.com/posts', { searchParams: { limit: 10, sort: 'newest' }, }).json(); console.log(posts.length); // 10#Handle errors
Unlike
fetch, Relay rejects when the server answers with a 4xx or 5xx status, so you can't accidentally treat an error page as data.errors.jsimport relay, { RelayError } from '@relayhttp/relay'; try { await relay.get('https://api.example.com/missing').json(); } catch (error) { if (error instanceof RelayError) { console.log(error.status); // 404 console.log(error.code); // 'HTTP_ERROR' } }#Share defaults with an instance
Most apps talk to one API. Create an instance with a base URL, headers and timeout once, then import it everywhere.
api.js// api.js import relay from '@relayhttp/relay'; export const api = relay.create({ baseUrl: 'https://api.example.com/v2', headers: { 'x-client': 'web' }, timeout: 8000, }); // elsewhere const me = await api.get('me').json();
#Next steps
- Installation covers TypeScript, Deno, Bun and using Relay without a bundler.
- Examples has recipes for auth tokens, file uploads and polling.
- API reference lists every option.
Was this page helpful?
Last updated