Nuxt JS and Shopify

Generating dynamic routes.

What a pain in the neck! Trying to generate dynamic routes for shopify js buy sdk was a hassle and half. So usually when I generate dynamics routes in Nuxt js and go into my nuxt.config.js and start typing my generate object. But, before we get to that we need to import the shopify js buy sdk. I use npm:

npm install shopify-buy

After we have installed the shopify js buy sdk, we need to import the shopify client. Now you could copy the import over and over again in each file that you need the client... but that's a no no!

So let's create a file called "shopConfig.js" and in the config file you will have this code in it. You need to fill in the "xxx's" with your own information. The shopConfig.js file should be in the same path as the nuxt.config.js.

import Client from 'shopify-buy';
 const client = Client.buildClient({
    domain: 'xxxxxxxxx.myshopify.com',
    storefrontAccessToken: 'xxxxxxxxxxxxxxxxxxxxxxx'
  });
 export default client

Now we can import our shop client into any .vue file.

import shop from '~/shopConfig'

So, now let's get into why you can here for...

Let's fetch all of the products from shopify. Then we call the .map() function that loops through the products returns a array of data. So, we're just creating an array of handles which are just like slugs.

generate:{
    routes: function(){
      return client.product.fetchAll()
      .then( res => {
        const shopProductSlugs = res.data.stories.map(shopPS=> shopPS.handle)
        return [
          // return your routes....
          '/',
          'cart',
          'checkout',
          ...shopProductSlugs 
        ]
      })
    }
  }
['string, 'boolean', 'number', 'foo', 'bar']

Then we use the spread operator to make the returned routes to look like the code below.

return [
   '/',
   'cart',
   'checkout',
   'string',
   'boolean',
   'number',
   'bar'
 ]

Once we have that setup, we go into the terminal and run npm run dev. It starts doing magic then I get this error...

Img

To be able to fix this error we have to go inside the nuxt.config.js file. We need to require node-fetch and the shop buy SDK at the top of your nuxt.config.js file.

const fetch = require('node-fetch')
 import Client from 'shopify-buy';
 const client = Client.buildClient({
  domain: 'xxxxxxxxx.myshopify.com',
  storefrontAccessToken: 'xxxxxxxxxxxxxxxxxxxxxxx'
}, fetch);

Once that's done... Run npm run generate and it should build your routes.

-Donte Trumble