How to use Axios with App Bridge React?

Shopify Expert
4320 35 445

In my Rails App, running Polaris, I want to call my API with Axios, via axios.get('/api/shop') to get some good JSON.

I want that to be an authenticated call, so I will let the JWT business do its thing. To that end I see I can use Axios and App Bridge, but it is using a different way of dealing with App Bridge. I use React, so typically I get the Context of App Bridge from the package.

 import { Provider, Context, TitleBar, Loading } from '@shopify/app-bridge-react';

And then when I want an App Bridge I just use

const appBridge = useContext(Context);

The Axios code from Shopify is a little different. It attaches some App Bridge object to the window... as, and then the Axios code uses an interceptor to inject a token into my Axios calls from the getSessionToken call. Long story short, how do I use this Axios hack using the interceptor AND the Context? React complains I cannot use Context in this interceptor as it is not a React Component. So am I supposed to use React Axios and that la-dee-da, or is there another way to leverage App Bridge here?


import axios from 'axios';
import { getSessionToken } from '@shopify/app-bridge-utils';
const instance = axios.create();
  function (config) {
    const appBridge = useContext(Context);  // this is verboten!!
    return getSessionToken(appBridge)  // requires an App Bridge instance
      .then((token) => {
        config.headers['Authorization'] = `Bearer ${token}`;
        return config;
export default instance;





Custom Shopify Apps built just for you!
Shopify Expert
4320 35 445

I solved this by adding the version of App Bridge to my code and that worked. Probably the most clunky use of JS ever, but it works.



Custom Shopify Apps built just for you!