V2 fetch-client configuration

I have an application with several services and plugins that use the HttpClient from @aurelia/fetch-client.

I would like to add a configuration to the fetch-client globally, a baseUrl and some interceptors.

How can I override the HttpClient settings globally?

In v1 I could do something like this within the aurelia configuration function:

  let http = new HttpClient();
  http.configure(configure => {
    configure
      .withBaseUrl('')
      .withHeader("X-CSRFToken", getCookie("csrftoken"))
      .withHeader('Accept', 'application/json')
      .withHeader('Content-Type', 'application/json')
      .withInterceptor({
        request: (request) => {
          return request;
        },
        response: (response) =>  {
          return response;
        }
      })
  });

  aurelia.container.registerInstance(HttpClient, http);

in v2 there does not seem to be a way to do this with the fetch-client.

Hi @aGustafson! You can do the similar configuration in Au2 as well. Here is the doc for that: Fetch Client - The Aurelia 2 Docs. The example demonstrates that using a @newInstanceOf decorator. However, if you prefer doing that in bootstrapping phase you can instead create a new instance of HttpClient using simply new HttpClient(); and then apply the configuration as sown in docs.

If you then want to register the instance to the DI, you need to do something like this:

const au = new Aurelia() // or use the static API, as per your preference
  .register(Registration.instance(IHttpClient, yourConfiguredHttpClient));

In case that does not work, please share a reproduction. You can easily do so by forking this StackBlitz project.

1 Like

Hi @Sayan751 , thanks!

I will try that.
I have been trying to register using the DI directly in main.ts. That was not working. I did not know you could use the Registration.instance in the Aurelia().register() methods.