Get session tokens using Shopify App Bridge utilities

The app-bridge-utils library provides helper functions to handle using session tokens for your application.

This tutorial shows you how to use helper functions to fetch a session token from Shopify App Bridge and include them in requests being made to the app backend.

Requirements

You must meet the following requirements to complete this tutorial:

Get a session token

The getSessionToken helper retrieves a session token from Shopify. It sets up a subscription on the Shopify App Bridge client to listen for the APP::SESSION_TOKEN_RESPOND action and then immediately dispatches the APP::SESSION_TOKEN_REQUEST action.

In your app, set up the Shopify App Bridge client and import getSessionToken using the following code:

Where your app requires a session token, specify the following code:

getSessionToken returns a Promise, which either resolves with the session token, or rejects with an APP::ERROR::FAILED_AUTHENTICATION error when the session token is undefined.

Authenticate your requests

The authenticatedFetch helper function authenticates your requests using the session token. The function internally gets the session token from Shopify App Bridge and passes in the Authorization header to your subsequent fetch requests.

Parameters

  • app: The App Bridge instance.
  • fetchOperation: Optional: Lets you define your own custom fetch wrapper.

The following example shows how to use authenticatedFetch with a custom ApolloLink:

Use your own custom fetch wrapper

If you want to add custom headers, caching, or special treatment of requests, then you can optionally pass in your own custom fetch wrapper function to the fetchOperation parameter.

The app-bridge-utils function (authenticatedFetch) returns your custom fetch wrapper function along with an authenticated Authorization header appended to the request options provided.

Any custom fetch function that you provide needs to append all appropriate options, including headers. The following example shows how to append options:

Next steps

  • Make authenticated requests using Axios.
  • 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 Shopify App Bridge authentication.