Node Remix ScriptTag

eagleto
Visitor
3 0 0

I am trying to create a Shopify app using remix node js in which i want to store javascript file in merchant store can anyone guide how i can store it using ScriptTag in hooks of Shopify-server.js file in app can store that file to merchant, i had tried way shown in docs but didn't succeed.

Replies 5 (5)

Liam
Shopify Staff
2731 299 769

HI Eagleto,

 

Creating a Shopify app using Remix Node.js and storing a JavaScript file in the merchant store via ScriptTag can be a bit challenging, but it's definitely doable. Here is a basic guideline on how you can do it:

  1. Set up Shopify Server: Ensure you have set up your Shopify server correctly. You need to include your API key and secret key in the server configuration.

  2. Create ScriptTag in Shopify Server: In your Shopify server's hooks, create a ScriptTag. The ScriptTag API allows you to add, retrieve, count, and delete script tags from a shop's theme templates.

  1. Use the ScriptTag in your App: Once the ScriptTag is created, you can use it in your app. You need to call the ScriptTag in the server.js file and attach it to the Shopify store when the app is installed.

Remember, you need to make sure your JavaScript file is hosted somewhere accessible on the web because you can't upload a JavaScript file directly to Shopify.

 

Hope this helps!

Liam | Developer Advocate @ Shopify 
 - Was my reply helpful? Click Like to let me know! 
 - Was your question answered? Mark it as an Accepted Solution
 - To learn more visit Shopify.dev or the Shopify Web Design and Development Blog

eagleto
Visitor
3 0 0

I had done this check it

 

import https from 'https';

 

 

const addScriptTag = async (session) => {

  const data = JSON.stringify({

    "script_tag": {

      "event": "onload",

      "src": "https://filesamples.com/samples/code/js/sample1.js"

    }

  });

 

  const options = {

    hostname: session.shop,

    path: '/admin/api/2023-07/script_tags.json',

    method: 'POST',

    headers: {

      'X-Shopify-Access-Token': session.accessToken,

      'Content-Type': 'application/json',

      'Content-Length': data.length

    }

  };

 

  const req = https.request(options, (res) => {

    let response = '';

 

    res.on('data', (chunk) => {

      response += chunk;

    });

 

    res.on('end', () => {

      console.log('Response:', response);

    });

  });

 

  req.on('error', (error) => {

    console.error('Error:', error);

  });

 

  req.write(data);

  req.end();

 

};

 

export default addScriptTag;

 

Server js

import "@shopify/shopify-app-remix/adapters/node";

import {

  AppDistribution,

  DeliveryMethod,

  shopifyApp,

  LATEST_API_VERSION,

} from "@shopify/shopify-app-remix/server";

import { PrismaSessionStorage } from "@shopify/shopify-app-session-storage-prisma";

import { restResources } from "@shopify/shopify-api/rest/admin/2023-07";

import addScriptTag from "./addScriptTag";

import prisma from "./db.server";

 

const shopify = shopifyApp({

  apiKey: process.env.SHOPIFY_API_KEY,

  apiSecretKey: process.env.SHOPIFY_API_SECRET || "",

  apiVersion: LATEST_API_VERSION,

  scopes: process.env.SCOPES?.split(","),

  appUrl: process.env.SHOPIFY_APP_URL || "",

  authPathPrefix: "/auth",

  sessionStorage: new PrismaSessionStorage(prisma),

  distribution: AppDistribution.AppStore,

  restResources,

  webhooks: {

    APP_UNINSTALLED: {

      deliveryMethod: DeliveryMethod.Http,

      callbackUrl: "/webhooks",

    },

  },

  hooks: {

    afterAuth: async ({ session }) => {

      // Register webhooks

      shopify.registerWebhooks({ session });

      addScriptTag(session);

      console.log(session);

    },

  },

  ...(process.env.SHOP_CUSTOM_DOMAIN

    ? { customShopDomains: [process.env.SHOP_CUSTOM_DOMAIN] }

    : {}),

});

// console.log(shopify);

 

export default shopify;

export const apiVersion = LATEST_API_VERSION;

export const addDocumentResponseHeaders = shopify.addDocumentResponseHeaders;

export const authenticate = shopify.authenticate;

export const unauthenticated = shopify.unauthenticated;

export const login = shopify.login;

export const registerWebhooks = shopify.registerWebhooks;

export const sessionStorage = shopify.sessionStorage;

DevMazdi
Shopify Partner
1 0 0
Just  destructure both admin and session from  afterAuth

add-scripts-tags.js

const addScriptTags = async(admin, session) => {
 try{
  let script_tag = new admin.rest.resources.ScriptTag({session: session});
  script_tag.event = "onload";
  script_tag.src = "https://example.com/my_script.js";
  await script_tag.save({
    update: true,
  });
 }catch(error){
  console.log(error);
 }
}

export default addScriptTags;


shopify.server.js  update 
hooks: {
    afterAuth: async ({admin, session}) => {
      shopify.registerWebhooks({ session });
      // add script tag
      await addScriptTags(admin, session);
    },
  },

======================================================================
 
shopify.server.js  full code

import "@shopify/shopify-app-remix/adapters/node";
import {
  AppDistribution,
  DeliveryMethod,
  shopifyApp,
  LATEST_API_VERSION,
} from "@shopify/shopify-app-remix/server";
import { PrismaSessionStorage } from "@shopify/shopify-app-session-storage-prisma";
import { restResources } from "@shopify/shopify-api/rest/admin/2024-01";
import prisma from "./db.server";
import addScriptTags from "./utils/add-scripts-tags";

const shopify = shopifyApp({
  apiKey: process.env.SHOPIFY_API_KEY,
  apiSecretKey: process.env.SHOPIFY_API_SECRET || "",
  apiVersion: LATEST_API_VERSION,
  scopes: process.env.SCOPES?.split(","),
  appUrl: process.env.SHOPIFY_APP_URL || "",
  authPathPrefix: "/auth",
  sessionStorage: new PrismaSessionStorage(prisma),
  distribution: AppDistribution.AppStore,
  restResources,
  webhooks: {
    APP_UNINSTALLED: {
      deliveryMethod: DeliveryMethod.Http,
      callbackUrl: "/webhooks",
    },
    CARTS_CREATE: {
      deliveryMethod: DeliveryMethod.Http,
      callbackUrl: "/webhooks",
    },  
  },
  hooks: {
    afterAuth: async ({admin, session}) => {
      shopify.registerWebhooks({ session });
      // add script tag
      await addScriptTags(admin, session);
    },
  },
  future: {
    v3_webhookAdminContext: true,
    v3_authenticatePublic: true,
  },
  ...(process.env.SHOP_CUSTOM_DOMAIN
    ? { customShopDomains: [process.env.SHOP_CUSTOM_DOMAIN] }
    : {}),
});
export default shopify;
export const apiVersion = LATEST_API_VERSION;
export const addDocumentResponseHeaders = shopify.addDocumentResponseHeaders;
export const authenticate = shopify.authenticate;
export const unauthenticated = shopify.unauthenticated;
export const login = shopify.login;
export const registerWebhooks = shopify.registerWebhooks;
export const sessionStorage = shopify.sessionStorage;
Tanveer95
Shopify Partner
1 0 0

Hi, I followed the way that you showed here to load the scripttag. it is loading on the store but at the same time getting blocked as well. Did you encounter this issue before? I will attach few screenshots of that error shortly.

eagleto
Visitor
3 0 0

I ahd done this check is working on every condition or not,

import https from 'https';

 

// const https = require('https'); // Import the 'https' module instead of 'http'

 

const addScriptTag = async (session) => {

  const data = JSON.stringify({

    "script_tag": {

      "event": "onload",

      "src": "https://filesamples.com/samples/code/js/sample1.js"

    }

  });

 

  const options = {

    hostname: session.shop,

    path: '/admin/api/2023-07/script_tags.json',

    method: 'POST',

    headers: {

      'X-Shopify-Access-Token': session.accessToken,

      'Content-Type': 'application/json',

      'Content-Length': data.length

    }

  };

 

  const req = https.request(options, (res) => {

    let response = '';

 

    res.on('data', (chunk) => {

      response += chunk;

    });

 

    res.on('end', () => {

      console.log('Response:', response);

    });

  });

 

  req.on('error', (error) => {

    console.error('Error:', error);

  });

 

  req.write(data);

  req.end();

};

 

 

export default addScriptTag;

 

Shopify.server.js

import "@shopify/shopify-app-remix/adapters/node";

import {

  AppDistribution,

  DeliveryMethod,

  shopifyApp,

  LATEST_API_VERSION,

} from "@shopify/shopify-app-remix/server";

import { PrismaSessionStorage } from "@shopify/shopify-app-session-storage-prisma";

import { restResources } from "@shopify/shopify-api/rest/admin/2023-07";

import addScriptTag from "./addScriptTag";

import prisma from "./db.server";

 

const shopify = shopifyApp({

  apiKey: process.env.SHOPIFY_API_KEY,

  apiSecretKey: process.env.SHOPIFY_API_SECRET || "",

  apiVersion: LATEST_API_VERSION,

  scopes: process.env.SCOPES?.split(","),

  appUrl: process.env.SHOPIFY_APP_URL || "",

  authPathPrefix: "/auth",

  sessionStorage: new PrismaSessionStorage(prisma),

  distribution: AppDistribution.AppStore,

  restResources,

  webhooks: {

    APP_UNINSTALLED: {

      deliveryMethod: DeliveryMethod.Http,

      callbackUrl: "/webhooks",

    },

  },

  hooks: {

    afterAuth: async ({ session }) => {

      // Register webhooks

      shopify.registerWebhooks({ session });

      addScriptTag(session);

      console.log(session);

    },

  },

  ...(process.env.SHOP_CUSTOM_DOMAIN

    ? { customShopDomains: [process.env.SHOP_CUSTOM_DOMAIN] }

    : {}),

});

// console.log(shopify);

 

export default shopify;

export const apiVersion = LATEST_API_VERSION;

export const addDocumentResponseHeaders = shopify.addDocumentResponseHeaders;

export const authenticate = shopify.authenticate;

export const unauthenticated = shopify.unauthenticated;

export const login = shopify.login;

export const registerWebhooks = shopify.registerWebhooks;

export const sessionStorage = shopify.sessionStorage;