Shopify App React / Node [Script Tag] The script tag is loaded in the frontend but not executed.

fotimo
New Member
1 0 0

Hello all,

I have a problem with the script tag. My app is basically based on the script https://shopify.dev/tutorials/build-a-shopify-app-with-node-and-react.

The script tag is initiated in server.js.

[server.js]

 

require('isomorphic-fetch');
const dotenv = require('dotenv');
const Koa = require('koa');
const next = require('next');
const {default: createShopifyAuth} = require('@shopify/koa-shopify-auth');
const {verifyRequest} = require('@shopify/koa-shopify-auth');
const {default: Shopify, ApiVersion} = require('@shopify/shopify-api');
const Router = require('koa-router');

dotenv.config();

Shopify.Context.initialize({
    API_KEY: process.env.SHOPIFY_API_KEY,
    API_SECRET_KEY: process.env.SHOPIFY_API_SECRET,
    SCOPES: process.env.SHOPIFY_API_SCOPES.split(","),
    HOST_NAME: process.env.SHOPIFY_APP_URL.replace(/https:\/\//, ""),
    API_VERSION: ApiVersion.October20,
    IS_EMBEDDED_APP: true,
    SESSION_STORAGE: new Shopify.Session.MemorySessionStorage(),
});

const port = parseInt(process.env.PORT, 10) || 300;
const dev = process.env.NODE_ENV !== 'production';
const app = next({dev: dev});
const handle = app.getRequestHandler();

const ACTIVE_SHOPIFY_SHOPS = {};

app.prepare().then(() => {
    const server = new Koa();
    const router = new Router();
    server.keys = [Shopify.Context.API_SECRET_KEY];

    server.use(
        createShopifyAuth({
            afterAuth(ctx) {
                const {shop, scope, accessToken} = ctx.state.shopify;
                console.log(ctx.state.shopify);
                console.log(accessToken);
                ACTIVE_SHOPIFY_SHOPS[shop] = scope;
                //ACTIVE_SHOPIFY_SHOPS[shop] = 'write_script_tags,read_script_tags';

                fetch(`https://${shop}/admin/api/2021-01/script_tags.json`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-Shopify-Access-Token': accessToken,
                    },
                    body: JSON.stringify({
                        "script_tag": {
                            "event": "onload"
                            , "src": "https://da00a95*****.ngrok.io/public/scripttag.js"
                            , "display_scope": "all"
                            , 'cache': false
                        }
                    })
                }).then(async response => {
                    const data = await response.json();
                    // check for error response
                    console.log(response);
                    try {
                        if (response.ok) {
                            // get error message from body or default to response status
                            //    const error = (data && data.message) || response.status;
                            //   return Promise.reject(error);
                            console.log(`no errorr!!!`);
                        }
                    } catch (error) {
                        this.setState({errorMessage: error.toString()}).bind(this);
                        console.error('There was an error!', error);
                    }

                });

                ctx.redirect(`/?shop=${shop}`);
            },
        }),
    );

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

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

    router.get("/", async (ctx) => {
        const shop = ctx.query.shop;

        if (ACTIVE_SHOPIFY_SHOPS[shop] === undefined) {
            ctx.redirect(`/auth?shop=${shop}`);
        } else {
            await handleRequest(ctx);
        }
    });

    router.get("(/_next/static/.*)", handleRequest);
    router.get("/_next/webpack-hmr", handleRequest);
    router.get("(.*)", verifyRequest(), handleRequest);

    server.use(router.allowedMethods());
    server.use(router.routes());

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

});

 

[scripttag.js]

console.log('this is me script tag!!!!!!!!')
const header = $('header.site-header').parent();

header.prepend('<div>Hello this is coming from the public folder </div>').css({'background-color':'orange', 'text-align': 'center'})

 

Frontent Browser Output

scripttag.js is loaded

Bildschirmfoto 2021-06-05 um 14.07.50.png

Console:

Bildschirmfoto 2021-06-05 um 14.12.08.png

Does anyone here have an idea what the Problem is or can help me?


Best regards and many thanks in advance

Replies 2 (2)
Svenson
Shopify Partner
2 0 1

Hi @fotimo,

I see two potential issues here:

  1. You get a 302-Redirect when requesting the scripttag.js. This way, the script is not loaded, but the browser-request is redirected to your auth-page (see the “location” in the response header of your screenshot).
  2. It looks like the content-type for your scripttag.js is “text/html”, but it should be served as “text/javascript” (also see the response header in your screenshot). This way, the browser interprets the content as HTML, but not as a script, even though it has “.js” as ending.

Hope that helps to find a solution.

MarkZhang123
Shopify Partner
1 0 0

Did you figure it out? I am stuck at the same point.