API Client

A fetch-based HTTP client with automatic JSON handling, configurable timeouts, retry logic with exponential backoff, request/response interceptors, file uploads with progress tracking, and abort controller support.

Quick Start

Configure a base URL, set default headers, then make requests using the standard HTTP method helpers.

js
import Aura from 'aurajs';

// Configure the API client
Aura.api.configure({
  baseURL: 'https://api.example.com',
  headers: { 'Authorization': 'Bearer my-token' },
  timeout: 10000,
  retry: 2
});

// GET request
const users = await Aura.api.get('/users');

// POST request
const newUser = await Aura.api.post('/users', {
  name: 'Alice',
  email: 'alice@example.com'
});

Types

ApiConfig

Configuration object accepted by configure(). All fields are optional (partial).

PropertyTypeDescription
baseURLstringBase URL prepended to all request paths. Default: ''.
headersRecord<string, string>Default headers sent with every request. Default: { 'Content-Type': 'application/json' }.
timeoutnumberRequest timeout in milliseconds. Default: 30000.
retrynumberNumber of retry attempts on failure. Default: 0.
retryDelaynumberBase delay between retries in ms (multiplied by attempt number). Default: 1000.

RequestOptions

Per-request options passed as the last argument to HTTP method helpers.

PropertyTypeDescription
paramsRecord<string, string | number>Query string parameters appended to the URL.
headersRecord<string, string>Extra headers merged with the defaults for this request.
interceptorsstring[]Names of specific request interceptors to run (default: all).
timeoutnumberOverride the global timeout for this request.
retrynumberOverride the global retry count for this request.
signalAbortSignalAn AbortSignal to cancel the request.

configure() core

Merge partial configuration into the current API client settings. Any provided fields override the existing values.

Aura.api.configure(config: Partial<ApiConfig>): void
ParamTypeDescription
configPartial<ApiConfig>Object with optional baseURL, headers, timeout, retry, and retryDelay fields.
js
Aura.api.configure({
  baseURL: 'https://api.example.com/v2',
  timeout: 15000,
  retry: 3,
  retryDelay: 500
});

get() core

Send a GET request. Automatically parses JSON responses when the Content-Type header is application/json.

Aura.api.get<T>(url: string, opts?: RequestOptions): Promise<T>
ParamTypeDescription
urlstringRequest path appended to baseURL.
optsRequestOptionsOptional per-request settings (query params, headers, timeout, etc.).
js
// Simple GET
const users = await Aura.api.get('/users');

// With query parameters
const results = await Aura.api.get('/search', {
  params: { q: 'aura', page: 1, limit: 20 }
});

// With custom timeout
const data = await Aura.api.get('/slow-endpoint', {
  timeout: 60000
});

post() core

Send a POST request with a JSON body. The body is automatically serialized with JSON.stringify().

Aura.api.post<T>(url: string, body?: unknown, opts?: RequestOptions): Promise<T>
ParamTypeDescription
urlstringRequest path appended to baseURL.
bodyunknownOptional request body, serialized as JSON.
optsRequestOptionsOptional per-request settings.
js
const user = await Aura.api.post('/users', {
  name: 'Alice',
  email: 'alice@example.com',
  role: 'admin'
});

console.log('Created user:', user.id);

put() core

Send a PUT request with a JSON body. Typically used for full resource replacement.

Aura.api.put<T>(url: string, body?: unknown, opts?: RequestOptions): Promise<T>
ParamTypeDescription
urlstringRequest path appended to baseURL.
bodyunknownOptional request body, serialized as JSON.
optsRequestOptionsOptional per-request settings.
js
await Aura.api.put('/users/42', {
  name: 'Alice Updated',
  email: 'alice.new@example.com',
  role: 'superadmin'
});

patch() core

Send a PATCH request with a JSON body. Typically used for partial resource updates.

Aura.api.patch<T>(url: string, body?: unknown, opts?: RequestOptions): Promise<T>
ParamTypeDescription
urlstringRequest path appended to baseURL.
bodyunknownOptional request body, serialized as JSON.
optsRequestOptionsOptional per-request settings.
js
// Update only specific fields
await Aura.api.patch('/users/42', {
  role: 'moderator'
});

delete() destructive

Send a DELETE request. No body is sent by default.

Aura.api.delete<T>(url: string, opts?: RequestOptions): Promise<T>
ParamTypeDescription
urlstringRequest path appended to baseURL.
optsRequestOptionsOptional per-request settings.
js
await Aura.api.delete('/users/42');

// With custom headers
await Aura.api.delete('/posts/99', {
  headers: { 'X-Confirm': 'true' }
});

upload() file

Upload a file using FormData. The Content-Type header is automatically removed so the browser can set the correct multipart boundary. Supports optional progress tracking via XMLHttpRequest.

Aura.api.upload<T>(url: string, formData: FormData, opts?: RequestOptions & { onProgress?: (pct: number) => void }): Promise<T>
ParamTypeDescription
urlstringUpload endpoint path appended to baseURL.
formDataFormDataA FormData object containing the file(s) and any additional fields.
optsRequestOptions & { onProgress? }Optional settings. onProgress receives a percentage (0–100) during upload.
js
const form = new FormData();
form.append('avatar', fileInput.files[0]);
form.append('userId', '42');

const result = await Aura.api.upload('/upload/avatar', form, {
  onProgress(pct) {
    progressBar.style.width = pct + '%';
    console.log(`Uploading: ${pct}%`);
  }
});

console.log('Uploaded:', result.url);

createAbortController() utility

Create a new AbortController instance. Pass its signal to any request's opts.signal to enable cancellation.

Aura.api.createAbortController(): AbortController

This method takes no parameters.

js
const ctrl = Aura.api.createAbortController();

// Start a request with the signal
const promise = Aura.api.get('/long-running', {
  signal: ctrl.signal
});

// Cancel the request after 5 seconds
setTimeout(() => ctrl.abort(), 5000);

try {
  const data = await promise;
} catch (e) {
  console.log('Request cancelled');
}

addInterceptor() interceptor

Register a named request interceptor. Interceptors run before every request (unless overridden by opts.interceptors). They receive the request config and can modify it, or return false to block the request entirely.

Aura.api.addInterceptor(name: string, interceptor: (config: ReqConfig) => ReqConfig | false | Promise<ReqConfig | false>): void
ParamTypeDescription
namestringUnique name for the interceptor (used with removeInterceptor() and opts.interceptors).
interceptorFunctionReceives ReqConfig ({ url, method, headers, body, params }). Return modified config or false to block.
js
// Auth interceptor: attach token to every request
Aura.api.addInterceptor('auth', (config) => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`;
  }
  return config;
});

// Rate-limit interceptor: block if too many requests
Aura.api.addInterceptor('rateLimit', (config) => {
  if (requestCount > 100) return false; // blocks the request
  return config;
});

// Run only specific interceptors for one request
await Aura.api.get('/public', {
  interceptors: ['rateLimit'] // skip 'auth'
});

removeInterceptor() interceptor

Remove a previously registered request interceptor by name.

Aura.api.removeInterceptor(name: string): void
ParamTypeDescription
namestringThe name of the interceptor to remove.
js
Aura.api.removeInterceptor('auth');

addResponseInterceptor() interceptor

Register a named response interceptor. Response interceptors run after every successful fetch, before the response is parsed. They receive the raw Response object and the original request config, and must return a Response.

Aura.api.addResponseInterceptor(name: string, interceptor: (response: Response, config: ReqConfig) => Response | Promise<Response>): void
ParamTypeDescription
namestringUnique name for the response interceptor.
interceptorFunctionReceives the raw Response and ReqConfig. Must return a Response (can be the same or a new one).
js
// Log all response statuses
Aura.api.addResponseInterceptor('logger', (response, config) => {
  console.log(`[${config.method}]`, config.url, response.status);
  return response;
});

// Handle token refresh on 401
Aura.api.addResponseInterceptor('tokenRefresh', async (response, config) => {
  if (response.status === 401) {
    await refreshToken();
    // The retry logic will handle re-sending
  }
  return response;
});

removeResponseInterceptor() interceptor

Remove a previously registered response interceptor by name.

Aura.api.removeResponseInterceptor(name: string): void
ParamTypeDescription
namestringThe name of the response interceptor to remove.
js
Aura.api.removeResponseInterceptor('logger');