Replace koa-shopify-graphql-proxy When Going Cookieless
How to replace koa-shopify-graphql-proxy with shopify-api when migrating from cookie based authentication to session tokens in embedded Shopify app.
Self taught web developer from Canada interested in Next and Node. Learning as I go, and sharing the knowledge I find along the way.
Recently I was migrating an embedded Shopify app from using cookie based authentication to use session tokens. The app was using koa-shopify-graphql-proxy to proxy requests from the frontend, to Shopify's GraphQL API. I wanted to use shopify-api instead.
On the frontend I had Apollo Client setup to use authenticatedFetch to send requests to the backend. I needed to use verifyRequest to check the incoming session tokens in the authorization header.
The following were required;
const Koa = require('koa');
const { default: createShopifyAuth } = require('@shopify/koa-shopify-auth');
const { verifyRequest } = require('@shopify/koa-shopify-auth');
const Router = require('koa-router');
const koaBody = require('koa-body');
const Shopify = require('@shopify/shopify-api').Shopify;
Initialized server and router;
const server = new Koa()
const router = new Router()
You will need to have implemented OAuth with Shopify. Shopify App Bridge is used to make authenticated requests from the frontend, attaching valid session tokens in the authorization header.
For the incoming requests to /graphql;
router.post('/graphql', koaBody(), verifyRequest({returnHeader: true}), async (ctx) => {
const session = await Shopify.Utils.loadCurrentSession(ctx.request, ctx.response, false);
const { shop, accessToken } = session;
const options = {
data: ctx.request.body,
};
const client = new Shopify.Clients.Graphql(shop, accessToken);
const response = await client.query(options);
ctx.status = 200;
ctx.body = response.body
}
);
I used koaBody from koa-body to parse the request body, and then pass it to the shopify-api GraphQL client.