Shopify Script Tag: Cross-Origin Read Blocking (CORB) blocked cross-origin response

therahulissar
Tourist
6 0 1

Currently working on a shopify app which uses script tags to add a section on the thank you page (order status page). 

It loads the image and text perfectly fine on the thank you page but 5 minutes later I get a CORB error which stops my code from being displayed on the thank you page. 

This is the basic structure of my js file which does the main handling of the script tag. 

 

console.log('this is coming from script tag api!')

const header = $('div.section__content').parent('.section');
 
var myContent = function($) {

//content box contains some basic styling with divs and an image which I haven't included
const contentBox = $( ....).css(....)

header.prepend(contentbox)
}
Replies 16 (16)
Bunty
Shopify Partner
133 39 80

Interesting, are you able to share your browser network log and the exact error?

Script Tags are a predominant mechanism to load scripts on the thank you page, so I'm curious as to what's happening.

therahulissar
Tourist
6 0 1

It's a tricky one to show currently - as when I add the script tag it works for about an hour and then when I come back it's no longer there and shows the CORB error. This is the landing page: https://www.littos.co.nz/11812208736/orders/4d2b6faa0b63a59c3e1d95908528fd40

I will try record the error once it happens again, for the moment I've removed the script tag and added it back in. 

therahulissar
Tourist
6 0 1

Do you think it could be due to a mime type? I've currently got it on my code as script.type = "text/javascript" 

Bunty
Shopify Partner
133 39 80

If it was the mime type, it would not have worked at all.

Looking at the order confirmation link, all looks fine. So yeah when you are able to capture more info, please do share.

therahulissar
Tourist
6 0 1
Bunty
Shopify Partner
133 39 80

Ok, so this is weird, and I think I know the problem now

<script type="text/javascript" async="" src="https://arcane-spire-11260.herokuapp.com/thanks-script.js?shop=littosnz.myshopify.com"></script>

This is what is included as a script tag. If I paste that src link in an incognito window, it redirects me to 

/auth?shop=littosnz.myshopify.com

which further redirects me to

https://littosnz.myshopify.com/admin/oauth/authorize?client_id=5cfb517c172af6c170f4c4fac3c09996&scope=write_script_tags&redirect_uri=https%3A%2F%2Farcane-spire-11260.herokuapp.com%2Fauth%2Fcallback&state=210481837313155&grant_options%5B%5D=per-user

which seems like the app install URL

and since I don't have an active Shopify session, I get redirect to the Store login page, no wonder you get a block on these 302s

You probably don't always get this block because sometimes when you are testing, you are in the same session as your store admin

 

So, you need to check your auth routine in the app and change it so that it doesn't do that when an unauthenticated user opens that link

 

 

EugeneCXY
Excursionist
16 3 4

Hey Bunty, 

Thanks for the fast replies and pointers. 

Where do we find the auth routine in the app. Is this a codebase change or a Shopify partner setting change?

 

 

Bunty
Shopify Partner
133 39 80
https://arcane-spire-11260.herokuapp.com/thanks-script.js?shop=littosnz.myshopify.com

Fundamentally, if you add something to a script tag, it should be publicly accessible. I believe it is your app that's adding it, so it is your code base that needs to be looked into.

I can not access this publicly, and it returns a JS and I no longer see a 302 or the block, have you fixed it?

EugeneCXY
Excursionist
16 3 4

EugeneCXY_0-1626907678888.png

This is built as a custom app and has gone live on one site. It seems like I am already doing it correctly, is there anything I'm missing here?

 

Bunty
Shopify Partner
133 39 80

@EugeneCXY I' not sure what that screenshot represents, is that a code to add a script tag to the store? I don't think that is a problem

Problem is in this URL 

https://arcane-spire-11260.herokuapp.com/thanks-script.js?shop=littosnz.myshopify.com

 If you open it in an incognito window, sometimes it redirects, and sometimes it renders a JavaScript. Whatever is happening in the GET request of that endpoint is the problem

EugeneCXY
Excursionist
16 3 4

Could it be the session? I am using shopify App cli out of the box.

I am not too sure why it keeps redirecting me to log in with the shopify shop. 

Here is the server file. 

 

import "@babel/polyfill";
import dotenv from "dotenv";
import "isomorphic-fetch";
import createShopifyAuth, { verifyRequest } from "@shopify/koa-shopify-auth";
import Shopify, { ApiVersion } from "@shopify/shopify-api";
import Koa from "koa";
import next from "next";
import Router from "koa-router";

dotenv.config();
const port = parseInt(process.env.PORT, 10) || 8081;
const dev = process.env.NODE_ENV !== "production";
const app = next({
  dev,
});
const handle = app.getRequestHandler();

Shopify.Context.initialize({
  API_KEY: process.env.SHOPIFY_API_KEY,
  API_SECRET_KEY: process.env.SHOPIFY_API_SECRET,
  SCOPES: process.env.SCOPES.split(","),
  HOST_NAME: process.env.HOST.replace(/https:\/\//, ""),
  API_VERSION: ApiVersion.October20,
  IS_EMBEDDED_APP: true,
  // This should be replaced with your preferred storage strategy
  SESSION_STORAGE: new Shopify.Session.MemorySessionStorage(),
});

// Storing the currently active shops in memory will force them to re-login when your server restarts. You should
// persist this object in your app.
const ACTIVE_SHOPIFY_SHOPS = {};

app.prepare().then(async () => {
  const server = new Koa();
  const router = new Router();
  server.keys = [Shopify.Context.API_SECRET_KEY];
  server.use(
    createShopifyAuth({
      async afterAuth(ctx) {
        // Access token and shop available in ctx.state.shopify
        const { shop, accessToken, scope } = ctx.state.shopify;
        const host = ctx.query.host;
        ACTIVE_SHOPIFY_SHOPS[shop] = scope;

        const response = await Shopify.Webhooks.Registry.register({
          shop,
          accessToken,
          path: "/webhooks",
          topic: "APP_UNINSTALLED",
          webhookHandler: async (topic, shop, body) =>
            delete ACTIVE_SHOPIFY_SHOPS[shop],
        });

        if (!response.success) {
          console.log(
            `Failed to register APP_UNINSTALLED webhook: ${response.result}`
          );
        }

        // Redirect to app with shop parameter upon auth
        ctx.redirect(`/?shop=${shop}&host=${host}`);
      },
    })
  );

  const handleRequest = async (ctx) => {
    await handle(ctx.req, ctx.res);
    ctx.respond = false;
    ctx.res.statusCode = 200;
  };

  router.post("/webhooks", async (ctx) => {
    try {
      await Shopify.Webhooks.Registry.process(ctx.req, ctx.res);
      console.log(`Webhook processed, returned status code 200`);
    } catch (error) {
      console.log(`Failed to process webhook: ${error}`);
    }
  });

  router.post(
    "/graphql",
    verifyRequest({ returnHeader: true }),
    async (ctx, next) => {
      await Shopify.Utils.graphqlProxy(ctx.req, ctx.res);
    }
  );

  router.get("(/_next/static/.*)", handleRequest); // Static content is clear
  router.get("/_next/webpack-hmr", handleRequest); // Webpack content is clear
  router.get("(.*)", async (ctx) => {
    const shop = ctx.query.shop;

    // This shop hasn't been seen yet, go through OAuth to create a session
    if (ACTIVE_SHOPIFY_SHOPS[shop] === undefined) {
      ctx.redirect(`/auth?shop=${shop}`);
    } else {
      await handleRequest(ctx);
    }
  });

  server.use(router.allowedMethods());
  server.use(router.routes());
  server.listen(port, () => {
    console.log(`> Ready on http://localhost:${port}`);
  });
});

 

 

keerti123
New Member
2 0 0

Hey @EugeneCXY  @therahulissar 

Did you find any solution for this? I am also facing the same issue.

EugeneCXY
Excursionist
16 3 4

Upload your script tag to a website domain and call it there. If you use Heroku, it times out

MarcoSol
New Member
2 0 0

Hi, but in development, using ngrok, how did you get over this problem?

EugeneCXY
Excursionist
16 3 4

You shouldnt be getting this error if you are using ngrok. This error only occurs when heroku sleeps and if your script is served on heroku. If you're ngrok is running then it shouldn't occur

MarcoSol
New Member
2 0 0

Hello! I've solved my previous problem, but now I understand which one was yours.
May I ask if you have tried to subscribe to heroku's "Hobby" plan so that it doesn't go to sleep after 30 minutes?
In this way the scriptTag should stay online

let me know

thanks