Building A Store with Next.js + Shopify - PART 2: Link Next.js project with Shopify store

Right now you already created a filled Shopify store. If not, you need to check out the previous course.

We'll wait for you.

Your Next.js application needs data from your Shopify store to function. In this section, we will use some access tokens to grant your Next.js application access to your Shopify Store.

Enough talk. Let’s begin.

This section is made up of 2 parts. The first section happens in your Shopify admin page and the second section happens in your Next.js application. We are trying to link both up, aren’t we?

First Part

Head to your Shopify admin page.

  1. Click the sales and apps section.

  2. Search for headless and install it.

  3. Back in your admin admin dashboard, add headless to sales channels.

  4. Open the headless app and click Create Storefront.

  5. On the manage API access section, click manage Storefront API.

  6. Copy the public access token. (You will need this later)

  7. Scroll to the Storefront API permissions section and click the pencil icon to edit.

  8. Check the access to inventory to grant your Storefront API access to read several products in stock.

  9. Click Save

Phew!

That’s it for the Shopify section. This might even be the last tedious process we ever do on the Shopify admin page.

Now for the next part.

Second Part

Head to your Next.js applications directory. That is the folder with the name of your recently created Next.js project.

Are you there?

If yes then create a new file. Call it .env.local.

In this file you created, fill it up with your public access token and your Shopify store URL.

Like so.

SHOPIFY_STOREFRONT_ACCESS_TOKEN=<your-token>
SHOPIFY_STORE_DOMAIN=https://<your-store>.myshopify.com/api/2023-10/graphql.json

Replace <your-token> with the token you copied above. And <your-store> with the name of your store.

And just like that. You have successfully linked body and soul.

Any query call you make to that URL with that access point will get a response from your Shopify store.

Because you like scalable web apps (I hope). You are going to write a generic fetch function to avoid writing one every time you need to query your Shopify store (which we will do a lot).

Here is the code for the function. Paste it in your <project>/lib/fetch.ts file.

export async function shopifyFetch({
  query,
  variables,
}: {
  query: string
  variables: object
}) {
  const endpoint = process.env.SHOPIFY_STORE_DOMAIN
  const key = process.env.SHOPIFY_STOREFRONT_ACCESS_TOKEN

  try {
    if (endpoint && key) {
      const result = await fetch(endpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Shopify-Storefront-Access-Token': key,
        },
        body: { query, variables } && JSON.stringify({ query, variables }),
      })

      return {
        status: result.status,
        body: await result.json(),
      }
    } else throw new Error('Endpoint or key is undefined')
  } catch (error) {
    console.error('Error:', error)
    return {
      status: 500,
      error: 'Error receiving data',
    }
  }
}

What this function does is: Give an object containing a query and some variables. It sends a post request to your Shopify store endpoint using the Shopify Storefront API access key as the authorization key. The returned data is split into body and status for error-handling purposes.

That is it for the generic fetching function.

You will find the full code for this section in this GitHub Link.

In the next section. You will test the fetch function you just created.

See you there!