Getting session token in axios intercept

Topic summary

Core Issue:
Developers are struggling to implement JWT session token authentication in axios interceptors for Shopify embedded apps, encountering “Cannot read property ‘subscribe’ of undefined” errors when trying to access the app instance.

Root Cause:
The useAppBridge() hook cannot be used outside React functional components, making it unavailable in axios interceptor setup code.

Working Solutions:

  1. Pass authAxios instance down from _app.js:

    • Create the axios instance with interceptor in _app.js using useAppBridge()
    • Pass the configured instance to child components as props
    • Use getSessionToken(app) to append Bearer token to request headers
  2. Custom hook approach:

    • Create a useFetchDataApiShopify hook that calls useAppBridge() within the component
    • Manually add JWT token to headers before each request
    • Avoids interceptor pattern entirely
  3. Response interceptor for re-authentication:

    • Add response interceptor to detect X-Shopify-API-Request-Failure-Reauthorize header
    • Redirect to /auth endpoint when re-authentication is needed

Alternative:
Some developers opted to use Shopify’s built-in authenticatedFetch function instead of axios, though many prefer axios for consistency.

Status: Multiple working solutions exist, but no single “best practice” has emerged. The discussion remains relevant for developers facing similar authentication challenges.

Summarized with AI on November 25. AI used: claude-sonnet-4-5-20250929.

Thank you for your answer! Will this also work outside of a react component?