Published on

How to Delete Files When Your Shopify App is Uninstalled A Step-by-Step Guide

Authors
  • avatar
    Name
    Entaice Braintrust
    Twitter

How to Delete Files When Your Shopify App is Uninstalled: A Step-by-Step Guide

Once upon a time, not long ago, in the land of e-commerce dreams, we built a Shopify app. It was a fine app—handling this, managing that—exciting stuff, really. But then, a problem reared its ugly head. You see, when our beloved app was cast into the lonely shadows of being un-installed, it left behind remnants—orphans, if you will—in the form of theme files in the Shopify stores. Tragic, right?

Well, we couldn’t stand for that! We needed a way to clean up after ourselves—like a responsible adult at an all-you-can-eat buffet.

The Uninstallation Predicament

Let's set the scene: The app is uninstalled. Cue the violins. In an ideal world, everything it touched should gracefully disappear. No stray liquid files crying out for purpose. Thankfully, Shopify offers webhooks—a little notification system—to give us the nudge when the app is ceremoniously booted out. But, as you know, they don’t do the dirty work for us. That’s where we come in!

Step 1: Setting Up the APP_UNINSTALLED Webhook

First thing's first. We need to make sure our app knows when it's been shown the door, so it can take its files with it.

import { DeliveryMethod } from '@shopify/shopify-api'
import themeFileDelete from './index.js'

export default {
  APP_UNINSTALLED: {
    deliveryMethod: DeliveryMethod.Http,
    callbackUrl: '/api/webhooks',
    callback: async (topic, shop, body, webhookId) => {
      const payload = JSON.parse(body)
      console.log(payload, '--------------Payload')
      await themeFileDelete() // Call our cleanup brigade
    },
  },
}

We've got our APP_UNINSTALLED webhook pointing to our file deletion function. It's about as close to a "911" call as we can get in the app-uninstallation world.

Step 2: Creating the File Deletion Function

Let’s dig into the juicy bits—how exactly do we do away with those pesky files using good ol' JavaScript and GraphQL?

const themeFileDelete = async (req, res) => {
  try {
    const client = new shopify.api.clients.Graphql({
      session: res.locals.shopify.session,
    })

    const themeId = 'gid://shopify/OnlineStoreTheme/146551537909'
    const filesToDelete = ['templates/index3.liquid']

    let mutation = `mutation($themeId: ID!, $files: [String!]!) {
      themeFilesDelete(themeId: $themeId, files: $files) {
        deletedThemeFiles {
          filename
        }
        userErrors {
          field
          message
        }
      }
    }`

    const response = await client.request(mutation, {
      variables: { themeId, files: filesToDelete },
    })

    console.log('Files deleted:', response.data)

    res.status(200).send({ message: 'Theme files deleted' })
  } catch (error) {
    console.error('Error deleting theme files on uninstall:', error)
    res.status(500).send({ message: error })
  }
}

export default themeFileDelete

Here’s the maestro behind the scenes: our themeFileDelete function that swings into action, wielding the power of GraphQL like a formidable knight quashing the file baddies.

Step 3: Bringing It All Together

We have our webhook diligently listening, and our function primed for action—now we just need to ensure they’re in cahoots. In the cold, technical heart of our app, these two must dance harmoniously so that the departure of our app is as virtuous as it is inevitable.

A Quick Recap

Picture this: our app, collecting its files as it bids adieu, thanks to a slick setup where a specific webhook cues our cleverly crafted deletion routine. It’s a tad bittersweet but beautifully clean.


So there we have it, friends—a tale as old as e-commerce itself. Cleaning up after app uninstallations may not sound glamorous, but it’s noble work. Let’s face it, nobody wants to find random config files lying around like awkward easter eggs. Our code is efficient, our processes are neat, and together we've stepped a little closer to a cleaner, more organized Shopify universe. Here’s to good housekeeping and happy coding!