Setting Access Token in header through Koa?

seandz
Excursionist
52 3 8

Hi, I'm mostly a front end dev, I know some Express and Koa is totally new to me. Is this how one gives all users, authenticated and not authenticated, an access token for the front end shopify APIs (I want to send .js files through the ScriptTag Api and maybe modify theme assets with my app using the Asset Api)?

 

      async afterAuth(ctx) {
        const { shop, accessToken } = ctx.session;
        
        ctx.set({
          "X-Shopify-Access-Token" : accessToken
        });
        
        ctx.cookies.set("shopOrigin", shop, {
          httpOnly: false
        });
        ctx.redirect("/");
      }
    })

I was using the shopify cli scaffolded server.js file The above code was inside: 

app.prepare().then(() => {
// more boilerplate removed
server.use(
createShopifyAuth({

 

One point I do not have clear in my mind is, how exactly does a response header give a cookie to a client?

 

I have heard of setting cookies by sending them as res.cookie or similar in Express.js. But I'm not clear on what a mere response header does, particularly how it allows an access token to persist on the client or what it even does in terms of security or session management without being in a cookie.

0 Likes
hassain
Shopify Staff (Retired)
Shopify Staff (Retired)
624 103 135

Hey @seandz ,

 

If you are new to Koa and building a Shopify App, this tutorial is a good resource to go through on how to use Node.js, React, and this Koa middle-ware to set-up your server for your Shopify App. Here is the code base for this tutorial.

 

The shopOrigin cookie is set only during the authentication of the app. So if you have added the `ctx.cookies.set("shopOrigin", shop, {httpOnly: false });` line of code after your app was authenticated on your store, you will need to re-authenticate your app by going to https://YOUR_APPS_ADDRESS.io/auth?shop=YOUR_SHOPIFY_STORE.myshopify.com in your web browser. 

 

If your question is more along the lines of "how does Koa specifically set cookies", from their API docs on the Koa Context  it appears that Koa uses this module for the getting and setting of cookies. 

 

Hassain | Developer Support Specialist @ Shopify
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Click Accept as Solution 

0 Likes