Setup and Configuration

The Aurelia Fetch Client provides multiple ways to create and configure HTTP clients. You can create instances directly, use dependency injection, or configure shared instances for your application.

Quick Start

The simplest way to get started is by resolving the fetch client through Aurelia's dependency injection:

import { IHttpClient } from '@aurelia/fetch-client';
import { resolve } from '@aurelia/kernel';

export class ApiService {
  private http = resolve(IHttpClient);
  
  async getUsers() {
    const response = await this.http.get('/api/users');
    return response.json();
  }
}

Creating Instances

Important: By default, IHttpClient is registered as a singleton. This means all services that resolve IHttpClient will share the same instance and configuration. If you configure the client in one service (e.g., setting a base URL), that configuration will affect all services using IHttpClient. If you need service-specific configurations with different base URLs or settings, use newInstanceOf(IHttpClient) as shown in the "Multiple Configured Instances" section below.

Creating New Instances

Multiple Configured Instances

For applications that need to communicate with different APIs, each with its own base URL or configuration, use newInstanceOf(IHttpClient) to create separate instances:

Each service above gets its own HttpClient instance with its own configuration. The UserApi will use base URL https://api.example.com/users/ while TodoApi uses https://api.example.com/todos/, and their configurations won't interfere with each other.

You can also combine multiple instances in a single service:

Best Practice: Use newInstanceOf(IHttpClient) when you need service-specific configurations (different base URLs, headers, or interceptors). For simple cases where all requests share the same configuration, the singleton IHttpClient is more efficient.

Configuration Options

The Aurelia Fetch Client supports all native Fetch API options plus additional convenience methods for common scenarios.

Basic Configuration

Configuration Methods

withBaseUrl(url: string)

Sets the base URL for all relative requests:

withDefaults(options: RequestInit)

Sets default options merged with every request:

withInterceptor(interceptor: IFetchInterceptor)

Adds request/response interceptors for cross-cutting concerns:

useStandardConfiguration()

Applies common defaults for typical applications:

rejectErrorResponses()

Makes the client reject promises for HTTP error status codes (4xx, 5xx):

withRetry(options: IRetryConfiguration)

Enables automatic retries for failed requests:

Advanced Configuration

Dynamic Headers

Headers can be functions that are evaluated for each request:

Request Event Dispatcher

Enable events for request lifecycle monitoring:

Making Requests

HTTP Methods

The fetch client provides convenient methods for all standard HTTP verbs:

JSON Helper

The json() helper automatically stringifies objects and sets the correct content-type:

Request Options

All methods accept standard Fetch API options:

Response Handling

Error Handling Strategies

Basic Error Handling

The native Fetch API only rejects promises for network errors, not HTTP error status codes. Use rejectErrorResponses() to change this behavior:

Centralized Error Handling

Use interceptors to handle errors globally:

Recovery Patterns

Implement automatic recovery for common scenarios:

Automatic Retries

The fetch client includes built-in retry functionality for handling transient network failures:

Basic Retry Configuration

Retry Strategies

Fixed Interval

Retries with the same delay between attempts:

Incremental Backoff

Increases delay with each retry:

Exponential Backoff

Doubles the delay with each retry:

Random Interval

Random delay within specified bounds:

Custom Strategy

Provide your own retry timing logic:

Conditional Retries

Control which requests should be retried:

Complete Retry Configuration

Real-world Example

Important: Only one retry interceptor can be configured per client, and it must be the last interceptor in the chain.

Last updated

Was this helpful?