If you’re like me, in Aurelia 1 you configured the Fetch client with some defaults, usually inside of your main bootstrap code (main.js/main.ts) where you might have added an authorization header, set up a default base URL and other configuration options you wanted to be global for the fetch client.
While there are other ways you can approach configuring the fetch client globally, I wanted to approach it in the same way you would if you were creating an Aurelia 2 plugin. This approach will also allow us to test it easier (testing is beyond the scope of this post).
To do this, we will take a middleware approach. Inside of your source directory, create a new folder called middleware
and a new file called fetch-client.ts
— I am using TypeScript, so change the applicable parts to work with Javascript.
import { HttpClient, IContainer } from 'aurelia'; import { StartTask } from '@aurelia/runtime'; export const FetchClientMiddleware = { register(container: IContainer): IContainer { container.register(StartTask.with(HttpClient).beforeCreate().call(FetchConfiguration)); return container; } }; const FetchConfiguration = (http: HttpClient): void => { http.configure(c => { c.useStandardConfiguration(); c.withBaseUrl('http://localhost:3000/api/'); c.withInterceptor({ request: (request) => { const bearerToken = sessionStorage.getItem('_loginTokenString'); if (bearerToken) { request.headers.set('Authorization', `Bearer ${bearerToken}`); } return request; } }) return c; }); };
Because this will be passed into the register
method inside of our main.ts
file, we can create an object and define a register
method which the container itself will call.
You might have noticed we are using a StartTask
which will allow us to tell Aurelia to run our code at certain points in the lifecycle. We then pass the dependency we want to instantiate to the with
method, specify we want to call it before create and then pass in a callback which gets the instance on the call
method.
When using this approach, it is important to note that it should be the first thing passed to the register
method inside of your main.ts
file.
import Aurelia, { RouterConfiguration } from 'aurelia'; import { MyApp } from './my-app'; import { FetchClientMiddleware } from './middleware/fetch-client'; Aurelia .register(FetchClientMiddleware, RouterConfiguration.customize({ useUrlFragmentHash: false })) .app(MyApp) .start();
We have just created a Fetch Client middleware which will allow us to override the global settings for each instance of the fetch client that gets injected into our components and services.