Saturday June 22, 2024

Automating Shopify Redirects

Most Shopify shops probably don’t have to worry about large numbers of redirects on a daily basis but one thing I’ve come up against working with Clemsons Vintage is managing redirects.

Most sites might need to add redirects once every so often, for example, if you update a blog URL or tweak the site structure but with Clemsons Vintage I’m working with redirects on a near-daily basis. This is due to the fact that everything sold on the site is a 1 of 1 item and therefore once it’s sold the product is marked as a draft and the URL then returns a 404, which isn’t ideal from a UX standpoint as these URLs will still be in the search results for a while. From an SEO standpoint, most of these URLs have little value but I like to follow best practice, until it starts to get unmanageable. This is what’s led look to look into automating Shopify redirects.

I had a quick look to see if there was already an app to do this but I couldn’t spot anything so decided to create my own private app with some help from ChatGPT.

The following instructions will help you create your own Shopify app that uses Google Cloud functions to create a redirect to a collection page. In the code shown this redirects users to a collection page of the same product type but you could tweak this to go to the same brand instead. Google Cloud Functions has a free tier that should cover the needs of this app but I would recommend keeping an eye on your billing and setting up notifications so you don’t end up with a large, unexpected bill at the end of the month.

Shopify to Google Cloud Function Redirect Setup

This guide will help you set up a Google Cloud Function to automatically create redirects for draft products to their respective category pages on Shopify.

Step-by-Step Guide

Step 1: Set Up Google Cloud Project

  1. Create a Google Cloud Account:
  2. Create a New Project:
    • Go to the Google Cloud Console.
    • Click on the project dropdown at the top of the page and select New Project.
    • Enter a name for your project and click Create.

Step 2: Enable APIs

  1. Enable Cloud Functions API:
    • In the Google Cloud Console, navigate to APIs & Services > Library.
    • Search for Cloud Functions API and click Enable.
  2. Enable Cloud Build API:
    • In the Google Cloud Console, navigate to APIs & Services > Library.
    • Search for Cloud Build API and click Enable.

Step 3: Create a Shopify Private App

  1. Login to Shopify Admin:
    • Navigate to your Shopify store's admin panel.
  2. Create a Private App:
    • Go to Apps.
    • Scroll down to the bottom and click Manage private apps.
    • Click Create a new private app.
    • Give your app a name (e.g., Google Cloud Function App) and enter an emergency developer email.
  3. Set API Permissions:
    • In the Admin API permissions section, ensure the following permissions are set to Read and write:
      • Products
      • Redirects
  4. Save the App:
    • Click Save.
    • Copy the API Key and Password (you’ll need these for authentication).

Step 4: Create the Function Code

  1. Navigate to Cloud Functions:
    • Go to the Google Cloud Console.
    • Navigate to Cloud Functions from the left-hand menu.
  2. Create a New Function:
    • Click on Create Function.
  3. Configure the Function:
    • Function Name: Enter a name for your function (e.g., handleWebhook).
    • Region: Select the region closest to you or your users.
    • Trigger: Select HTTP.
    • Authentication: Select Allow unauthenticated invocations.
  4. Environment Variables:
    • Expand the Environment variables, networking, timeouts and more section.
    • Add the environment variables for your Shopify store:
      • SHOPIFY_STORE: Your Shopify store name (e.g., my-store-name). I used the default URL when managing the backend of the store, this should look something like:{your store code}/products?selectedView=all
      • SHOPIFY_ACCESS_TOKEN: Your Shopify access token (the password from your private app).
  5. Runtime and Entry Point:
    • Runtime: Select Node.js 20.
    • Entry Point: Enter handleWebhook.
  6. Replace the Code:
    • Remove all the existing code in the index.js file and replace it with the code below
    • Remove all the existing code in the package.json file and replace it with the following updated code:
  7. Deploy the Function:
    • Click Deploy.

Step 5: Configure the Webhook in Shopify

  1. Login to Shopify Admin:
    • Navigate to your Shopify store's admin panel.
  2. Navigate to Webhooks Settings:
    • Click on Settings at the bottom left corner.
    • Click on Notifications.
  3. Create Webhook:
    • Scroll down to the Webhooks section and click on Create webhook.
    • Set the Event to Product update.
    • Set the Format to JSON.
    • Enter the URL provided by Google Cloud for your function.
    • Click Save webhook.

Step 6: Test and Verify

  1. Test the Setup:
    • Update a product in Shopify to change its status to draft.
    • Check the logs of your Google Cloud Function to see if the webhook was received and processed.
  2. Verify the Redirect:
    • Visit the URL of the draft product and ensure it redirects to the correct category page based on the updated mapping.

index.js code

const axios = require('axios');

// Mapping of product types to collection URLs
const productTypeToCollectionUrl = {
    'Football Shirt': '/collections/football-shirts',
    'Bag': '/collections/bags',
    'Fleece': '/collections/fleeces',
    'Gilet': '/collections/gilets',
    'Hat': '/collections/vintage-hats-caps',
    'Hoodie': '/collections/hoodies',
    'Jacket': '/collections/jackets',
    'Rugby Shirt': '/collections/rugby-tops',
    'Shirt': '/collections/shirts',
    'Shoes': '/collections/shoes',
    'Shorts': '/collections/shorts',
    'Sweatshirt': '/collections/sweatshirts',
    'T-Shirt': '/collections/t-shirts',
    'Trackies': '/collections/trackies',
    'Trousers': '/collections/trousers',
    // Add other mappings as needed

exports.handleWebhook = async (req, res) => {
    const product = req.body;

    if (product.status === 'draft') {
        const productType = product.product_type;
        const categoryUrl = productTypeToCollectionUrl[productType] || '/collections/default-collection'; // Default collection if no mapping found

        const redirect = {
            redirect: {
                path: `/products/${product.handle}`,
                target: categoryUrl

        try {
            await`https://${process.env.SHOPIFY_STORE}`, redirect, {
                headers: {
                    'X-Shopify-Access-Token': process.env.SHOPIFY_ACCESS_TOKEN
        } catch (error) {
            console.error('Error creating redirect:', error);
    } else {

Package.json Code

  "name": "shopify-webhook-function",
  "version": "1.0.0",
  "main": "index.js",
  "dependencies": {
    "axios": "^0.21.1"


By following these steps and using the code with the product type to collection URL mapping, your redirects should now correctly point to the appropriate collection URLs. Adjust the productTypeToCollectionUrl dictionary to match your specific product types and collection URLs.

I hope you found this useful and that it pretty much works first time but if you run into any issues just drop me a message on my contact form and I’ll do my best to help you get it working!

Chay Kelly Headshot
Chay Kelly
I am an SEO Consultant and digital marketer with many years of agency experience in implementing and executing digital strategies such as SEO, PPC and email marketing campaigns.
Learn More

Similar Posts