How to use getSessionToken() in frontend Javascript

Solved

How to use getSessionToken() in frontend Javascript

df0
Shopify Partner
3 1 2

I'm struggling to get getSessionToken() working in my app frontend using vanilla Javascript. Here's what I have so far:

 

 

<script src="https://cdn.shopify.com/shopifycloud/app-bridge.js?apiKey=xxxxxx"></script>
<script src="https://unpkg.com/@shopify/app-bridge@3"></script>

    <script>
        const AppBridge = window['app-bridge'];

        const app = AppBridge.createApp({
            apiKey:'xxxxxxx',
        });

        var sessionToken = await AppBridge.utilities.getSessionToken(app);
        console.log(sessionToken);
    </script>

 

 

 

This is running on a page on my app domain appearing as an iFrame in the Shopify admin. This code produces nothing in the browser console log.

 

If I manually type the commands into the browser console, I can create the app with my API key (AppBridge.createApp()) but the getSessionToken() call is never fulfilled.

 

I have tried using versions 2 and 3 of the App Bridge but can't make any of them work. Can anybody help?

Accepted Solution (1)

df0
Shopify Partner
3 1 2

This is an accepted solution.

To answer my own question, the solution was to ensure the app is created with the base64 encoded host parameter as provided by Shopify in the iFrame src like this:

 

<script src="https://cdn.shopify.com/shopifycloud/app-bridge.js?apiKey=xxxxxx"></script>
<script src="https://unpkg.com/@shopify/app-bridge@3"></script>

    <script>
        const AppBridge = window['app-bridge'];

        const app = AppBridge.createApp({
            apiKey:'xxxxxxx',
            host:'YWRtaW4uc2hvcGlmeS5jb20vc3RvcmUvd2hhdGV2ZXIteW91ci1zdG9yZS1pcy1jYWxsZWQ='
        });

        var sessionToken = await AppBridge.utilities.getSessionToken(app);
        console.log(sessionToken);
    </script>

View solution in original post

Reply 1 (1)

df0
Shopify Partner
3 1 2

This is an accepted solution.

To answer my own question, the solution was to ensure the app is created with the base64 encoded host parameter as provided by Shopify in the iFrame src like this:

 

<script src="https://cdn.shopify.com/shopifycloud/app-bridge.js?apiKey=xxxxxx"></script>
<script src="https://unpkg.com/@shopify/app-bridge@3"></script>

    <script>
        const AppBridge = window['app-bridge'];

        const app = AppBridge.createApp({
            apiKey:'xxxxxxx',
            host:'YWRtaW4uc2hvcGlmeS5jb20vc3RvcmUvd2hhdGV2ZXIteW91ci1zdG9yZS1pcy1jYWxsZWQ='
        });

        var sessionToken = await AppBridge.utilities.getSessionToken(app);
        console.log(sessionToken);
    </script>