Skip to content

Instantly share code, notes, and snippets.

@WajahatAnwar
Last active May 27, 2021 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WajahatAnwar/5726d13a7ef23a2acb3c1ccd0956d0a8 to your computer and use it in GitHub Desktop.
Save WajahatAnwar/5726d13a7ef23a2acb3c1ccd0956d0a8 to your computer and use it in GitHub Desktop.
Implementation of session tokens using App Bridge
import React, { useState } from "react"
import ApolloClient from "apollo-client";
import { AppProvider } from "@shopify/polaris"
import { usePage } from "@inertiajs/inertia-react"
import { Provider, Toast } from "@shopify/app-bridge-react"
import { authenticatedFetch, getSessionToken } from "@shopify/app-bridge-utils";
import deepMerge from "@shopify/app-bridge/actions/merge";
import { HttpLink } from "apollo-link-http";
import { InMemoryCache } from "apollo-cache-inmemory";
import { Base64 } from 'js-base64'; //For encoding & decoding to base64
import enTranslations from "@shopify/polaris/locales/en.json"
//Get store-url on which app is installed
const shop = document.getElementById("shopOrigin").value+"/admin";
export default function AppLayout({ children }) {
const config = {
apiKey: document.getElementById("apiKey").value,
shopOrigin: document.getElementById("shopOrigin").value,
host: Base64.encode(shop), //Adding host name
forceRedirect: true
};
// Sample custom fetch wrapper
const yourCustomFetchWrapper = (uri, options) => {
const aggregateOptions = deepMerge(options, {
method: "POST",
headers: { "Content-Type": "application/json" },
});
return fetch(uri, aggregateOptions);
};
const app = createApp({
apiKey: document.getElementById("apiKey").value,
shopOrigin: document.getElementById("shopOrigin").value,
host: Base64.encode(shop),
// forceRedirect: true
});
const client = new ApolloClient({
link: new HttpLink({
credentials: "same-origin",
fetch: authenticatedFetch(app, yourCustomFetchWrapper), // ensures your custom fetch wrapper is authenticated
}),
cache: new InMemoryCache(),
});
// const sessionToken = await getSessionToken(config);
console.log(client);
return (
<AppProvider i18n={enTranslations}>
<Provider config={config}>
{children}
</Provider>
</AppProvider>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment