All Tutorials

Use session tokens with Axios

All Tutorials

Use session tokens with Axios

Use session tokens with Axios

Axios is a popular promise-based HTTP client. It can be used to transform and intercept HTTP request and response data asynchronously.

To make authenticated requests using Axios, you can use Axios interceptors to append an authenticated session token header prior to each request.

Requirements

Steps

  1. Install an interceptor to your instance of Axios.
  2. Define a function that your Axios instance calls prior to each request.

    The function takes a config object as parameter and returns a config object that's used as configuration for all subsequent requests.

  3. In the function, call getSessionToken() and resolve the token it returns.

  4. Modify the config object to append an “Authorization”: “Bearer token” header to your requests, like in the following example:

       import axios from "axios";
       import { getSessionToken } from "@shopify/app-bridge-utils";
    
       const instance = axios.create();
       // intercept all requests on this axios instance
       instance.interceptors.request.use(function (config) {
         return getSessionToken(window.app) // requires an App Bridge instance
           .then((token) => {
             // append your request headers with an authenticated token
             config.headers["Authorization"] = `Bearer ${token}`;
             return config;
           });
       });
       // export your axios instance to use within your app
       export default instance;

Next steps

  • Learn how to use helper functions to fetch a session token from App Bridge and include them in requests being made to the app backend.
  • Convert a multi-page, server-side rendered (SSR) app to use App Bridge authentication with Turbolinks.
  • Learn how to build a Shopify app with Rails 6, React, and App Bridge authentication.