How to update theme files using NodeJS + React?

How to update theme files using NodeJS + React?

d_tehrani
Shopify Partner
56 1 13

In my Shopify App which I'm building with NodeJS + React, I would like to insert liquid code into the theme files of the shop.
I found this tutorial, but it only shows how to do it "manually".

I thought about getting the theme file as a string using the Asset API, then inserting a liquid code using javascript native functions like .findIndex, .slice, etc etc. Is this the only way to insert code into theme files? Or is there an easier way?

Thanks.

Replies 9 (9)

diego_ezfy
Shopify Partner
2970 571 919

Hey,

You need to an API call to the theme. Please read all the instructions here. It's important that you already do have experience with Javascript.

https://shopify.dev/docs/admin-api/rest/reference/online-store/asset



d_tehrani
Shopify Partner
56 1 13

Hi.
Thanks for the reply.


I've read the instructions, but I don't think there is an explanation about updating an existing theme.

I would like to know how to insert a liquid code into (using the Asset API) an existing theme.

Thanks.

diego_ezfy
Shopify Partner
2970 571 919

Hello,

Yes, there is, you just need to grab the current theme's ID and make a PUT call to add create or update whatever file you wish.

diego_ezfy_0-1609634025645.png


I reckon that you're not very familiarized with Javascript itself since this is a fairly basic API call, therefore I'd highly suggest getting proficient in React before diving into Shopify App developement, it will save you a lot of headache and make your progress much more smooth.

Unfortunately app development for Shopify is not much beginner-friendly, I feel you there.
Consider taking a look in Udemy courses for React/Node to gain a bit more of understanding of how it works and I promise you it's going to be much more easy to understand!

Wishing you the best.

Kind regards,
Diego

d_tehrani
Shopify Partner
56 1 13

I apologize for my confusion question.
I really appreciate the explanation, but I have solid experience in React + NodeJS applications.

 

I understand that I have to make a PUT call to update the theme, but I not sure if my methodology is correct.

At first, I get the liquid code by calling
GET /admin/api/2021-01/themes/{theme_id}/assets.json?asset[key]=templates/index.liquid

And next, for example, if I want to insert <h1>Hello World</h1> right before {{ content_for_header }}, should I do something like below?

const str = "Liquid code as string"
const indexOfContentForHeader = str.search("{{ content_for_header }}");

const updatedLiquidCode = str.slice(0, indexOfContentForHeader) + "<h1>Hello World</h1>" + str.slice(indexOfContentForHeader)

 

then, 

PUT /admin/api/2021-01/themes/{theme_id}/assets.json
{
"asset": {
"key": "templates/index.liquid",
"value": updatedLiquidCode
}
}

 

or is there a "cleaner" way?  (Is there a library to do something like the JavaScript code above?)

 

Sincerely,
Daniel

diego_ezfy
Shopify Partner
2970 571 919

Oh, I see. 

Yes, as far as I am aware this would be the best way to do it.

Personally I'd do something like:

data.replace(`{{ content_for_header }}`, `<h1>hey</h1>
{{ content_for_header }}`);


Of course you'd need to use REGEX to target something like {{content_for_header             }} as well, but that's about it!

In Shopify dev-ing there's a lot of "non-conventional/ideal" ways to do things, unfortunately.
Shopify's support specifically for app developers is terrible as well, so feel free to reach out for anything you need, I'll be happy to help.

Kind regards,
Diego

d_tehrani
Shopify Partner
56 1 13

Thanks for the quick replay!
Yes, I think using the replace function and REGEX is great and necessary!

 

I've been feeling that too, so thank you so much for helping!


In Shopify dev-ing there's a lot of "non-conventional/ideal" ways to do things, unfortunately.

 

Best,
Daniel

maneamit023
Shopify Partner
1 0 0

hello Diego_ezfy

I hope you are doing well,

can you help me out with some sample code to make an api call 

I'm not able to do this.

using react and node for the developement 

thanks.

hplemolite
Shopify Partner
3 0 0
app.post('/api/updatetheme', async (req, res) => {
  try {
    const { ids, name, role } = req.body;
    console.log(ids, name, role, "bodydata");

    const headerFile = await shopify.api.rest.Asset.all({
      session: res.locals.shopify.session,
      theme_id: ids,
      asset: { "key": "sections/header.liquid" },
    });
    let headerContent = headerFile.data[0]?.value;

    if (headerContent) {
 
      // Modify the regular expression pattern to match the <details> element properly
      headerContent = headerContent.replace(/<details\b[^>]*>\s*(.*?)\s*<\/details>/s, '<details-modal class="header__search">Updated details content</details-modal>');
     
      console.log(res.locals.shopify.session);

      const asset = new shopify.api.rest.Asset({
        session: res.locals.shopify.session,
      });
      asset.theme_id = ids;
      asset.key = "sections/header.liquid";
      asset.value = headerContent;
      await asset.save({ update: true });
    } else {
      throw new Error("Failed to retrieve header content");
    }

    res.status(200).json({ success: true });
  } catch (error) {
    console.error("Failed to update header.liquid file:", error);
    res.status(500).json({ success: false, error: "Failed to update header.liquid file" });
  }
});  this is my node js code, but when i i put call data not updating why? please any solution for it
 
adir1
Shopify Partner
4 0 0

I was using the same query till now but shopify has declared REST as legacy, so I was trying to use themeFileUpsert query in graphQL, but it says you need write_themes and write_themes_assets access scope which I have been trying to add in my TOML file but it throws an error saying that write_themes_assets is not a valid access scope, do you have any migration steps which can help me.