I’m using Axios this way:
const axios = userLoggedInAxios(app);
axios('url', {/* your options */}
This has identical behavior as userLoggedInFetch, showcased in shopify-app-template-node
Here the required module:
/**
* Adds Shopifys Authorization Header to Axios requests through the use of a request interceptor
* app Shopify app instance
* @returns AxiosInstance
*/
function authenticatedAxios(app) {
const axiosShopify = axios.create();
axiosShopify.interceptors.request.use((config) =>
getSessionToken(app) // requires a Shopify App Bridge instance
.then((token) => {
// Append your request headers with an authenticated token
config.headers["Authorization"] = `Bearer ${token}`;
return config;
})
);
return axiosShopify;
}
/**
* Assures that Shopify Request is made for a logged-in user through the use of a response interceptor
* It uses Shopifys redirect mechanism to redirect unauthenticated user-requests to the '/auth' endpoint
* app Shopify app instance
* @returns AxiosInstance
*/
export function userLoggedInAxios(app) {
const authAxios = authenticatedAxios(app);
authAxios.interceptors.response.use((response) => {
if (
response.headers.get("X-Shopify-API-Request-Failure-Reauthorize") === "1"
) {
const authUrlHeader = response.headers.get(
"X-Shopify-API-Request-Failure-Reauthorize-Url"
);
const redirect = Redirect.create(app);
redirect.dispatch(Redirect.Action.APP, authUrlHeader || "/auth");
return null;
}
return response;
});
return authAxios;
}