How to use App Brigde Redirect in NextJS app

Paul_vd_Dool
Shopify Partner
18 3 4

Hi, 

I'm trying to build my first app and I'm quite new with React and NextJS so please bear with me.

I've got a section in my app where I want to link to the customer page in the Shopify Admin. As I understand, I'll need to use the App Bridge Redirect Action to modify the top-level URL outside of the iframe my app lives in. But I'm having trouble understanding how to properly setting up Redirect on the page I want to use it.

CustomerDetails.js

 

import { Redirect } from "@shopify/app-bridge/actions";

const CustomerDetails = () => {

  const handleRedirect = ( customerId ) => {
    redirect.dispatch( Redirect.Action.ADMIN_PATH, `/customers/${customerId}` );
  }

  return (
    // my template here
  )
}

export default CustomerDetails;

 

So here I have the page. The `handleRedirect` function will perform the redirect.

The trouble I'm having is with the lowercase `redirect` and how to properly set that up.

The official docs say to setup the redirect by doing the following:

const redirect = Redirect.create(app);

 This also requires you to set up (lowercase) app like thus:

const app = createApp({
  apiKey: '12345',
  shopOrigin: shopOrigin,
});

And this is where my knowledge falls short. I feel like this should be done in the `server.js` file. But as I only understand a little bit of what is happening in that file, I have no idea how to properly solve this. How to access a possible app object in `server.js` from `CustomerDetails.js`.

I want to know where in the app I should define the `app` and the `redirect` and how to properly use it in `CustomerDetails.js`.

Any help I very much appreciated. If I need to provide more information please let me know.

My current app structure

- my_app
    - pages
        [customerId.js] (serves CustomerDetails.js as in example above)
        _app.js
        index.js
    - components
        CustomerDetails.js
        CustomerList.js
    - server
        - handlers
        index.js
        server.js

 

Update

I've got it working using `useAppBridge()`.

I was running the Shopify App CLI and noticed it generated a new `_app.js` file in which it used `Redirect`. Looking at that code I saw the `app` object is generated by using

const app = useAppBrigde()

 Which is imported from `@shopify/app-bridge-react`.

By importing that in my CustomerDetails.js file, I was able to get the Redirect work.

import { Redirect } from "@shopify/app-bridge/actions";
import { useAppBridge } from "@shopify/app-bridge-react";

const CustomerDetails = () => {

  const app = useAppBridge();
  const redirect = Redirect.create( app );

  const handleRedirect = ( customerId ) => {
    redirect.dispatch( Redirect.Action.ADMIN_PATH, `/customers/${customerId}` );
  }

  return (
    // my template here
  )
}

export default CustomerDetails;

It's working, but I still would like to know if this is indeed the proper way to do this.

0 Likes