Skip to content
Himanshu Patil
TwitterInstagramGithubLinkedin

How to use axios in service worker

Axios, XMLHttpRequest1 min read

Potions Class

Photo by 

JJ Ying

 on 

Unsplash

Axios has become the go to use http library for javascript. Under the hood axios uses XMLHttpRequest for browser environment and http for nodejs to make http network request.

While this all works perfectly it fails to work in service worker. With chromium enforcing manifest version 3 for extension, Background pages are replaced by service workers. So use of axios in service worker is not possible. To overcome this you can pass custom adapter to axios to override XMLHttpRequest/http.

In this case we can use fetch api to make http request. There is an NPM package @vespaiach/axios-fetch-adapter which is a fetch adapter for axios.

npm install @vespaiach/axios-fetch-adapter

Then add it to axios config.

import fetchAdapter from '@vespaiach/axios-fetch-adapter';
const instance = axios.create({
adapter: fetchAdapter
....
});

Voila! it works!