Fixing Shopify App Redirect in Remix

Fixing Shopify App Redirect in Remix

If you’ve been trying to redirect users within a Shopify Remix app and hitting roadblocks with navigate, redirect, or even window.location.href, then this article is for you. This is one of the issues when especially when integrating Shopify apps with Remix. The good news is that window.parent.location.href can solve this problem.

In this article, I'll show you why those methods fail and how you can use window.parent.location.href to successfully redirect users to a custom url.

The Problem

When working within Shopify's embedded app environment, you might encounter issues with standard redirect methods. Here's a quick rundown of the issues you might face:

  1. navigate: This method might append the new URL to the existing one, leading to malformed URLs.

  2. redirect: This can prevent the Shopify app from loading correctly.

  3. window.location.href: Sometimes, it simply doesn't lead to any page, leaving you stuck.

The Solution: window.parent.location.href

To overcome these issues, window.parent.location.href ensures that the whole window (not just the iframe) navigates to the new URL.

Step-by-Step Guide

  1. Ensure Proper Imports: Make sure you have the necessary imports for your icons and other utilities.

  2. Implement window.parent.location.href in Your ActionListDropdown: Update your redirection logic to use this method.

Here’s how you can do it:

Example Code

import React from 'react';
import { EditIcon } from '@shopify/polaris-icons';
import { ActionList, Popover } from '@shopify/polaris';
import { useLoaderData, useParams } from "@remix-run/react";

const ListDropdown = ({ actionList }) => {
  return (
    <div>
      <Popover
      >
        <ActionList
          actionRole="menuitem"
          items={actionList}
        />
      </Popover>
    </div>
  );
};

const App = () => {
const params = useParams()
  const {
    meta: { shop },
  }= useLoaderData();
  const handleRedirect = () => {
    const productUrl = `https://admin.shopify.com/store/${shop}/products/${getSplitIdValue(id)}`;
    window.parent.location.href = productUrl;
  };

  return (
    <ListDropdown
      actionList={[
        {
          content: "Edit",
          icon: EditIcon,
          onAction: handleRedirect,
        },
      ]}
    />
  );
};

export default App;

Explanation

  • window.parent.location.href: This ensures the redirection happens at the top-level window, bypassing the iframe restrictions.

  • Event Handlers: The onClick event handlers in the ListDropdown trigger the redirection for the "Advanced" button and the modal opening for the "Delete" button.

Additional Tip

  1. Setup: Ensure you have installed the required Shopify libraries as well as set up authentication, and user sessions.

  2. Check Authentication: Make sure you’re logged into the Shopify admin to avoid redirection to the login page.