> Contact

Please answer the questions below to send me a message.

(1 / 3) Reset | Exit

> Hello there, what is your name?

> Blog

Nuxt Generate Dynamic Routes with Apollo and GraphQL

Nuxt ships with a static site generator (SSG), which generates all of your routes when calling nuxt generate. This works great for predefined routes however extra work is involved when dealing with dynamic routes. We need to let Nuxt generate know about our dynamic routes in the nuxt.config.js file, we do this by adding the generate property and returning an array in the routes property. The example below shows how we can list our routes manually:

./nuxt.config.js

export default {
  generate: {
    routes: [
      '/post/post-1',
      '/post/post-2',
      '/post/post-3'
    ]
  }
}

Although this would work, listing out all your routes manually is not very clever and we can automate this functionality. There are many examples of how to do this using Axios which is great if you are using a JSON API however if you are using GraphQL like I was, it was harder to find information, so I'm going to show you how I did it.

1. Install Apollo-Fetch Package

First of all, we need to install apollo-fetch:

NPM: npm install apollo-fetch --save

Yarn: yarn add apollo-fetch

Once it's installed in your project you'll want to require it in your nuxt.config.js file, so add the code below to the top of the file

const { createApolloFetch } = require('apollo-fetch')

2. Add Dynamic Routes to Generate Using Apollo-Fetch

Now you have the correct package installed and you are requiring it in your nuxt.config.js file you can add the following code to generate all your dynamic routes automatically when you run Nuxt generate.

./nuxt.config.js

generate: {
    routes: function () {
      const uri = 'https://your-api-url.goes/here'
      const apolloFetch = createApolloFetch({ uri })
      const query = `
      {
        posts {
          slug 
        }
      }`
      return apolloFetch({ query }).then(result => {
        const { data } = result
        return data.posts.map(post => `post/${post.slug}`)
      }).catch(error => {
        console.log(error)
      })
    }
}

Now when you run nuxt generate apollo-fetch will get all 'Posts' from and add them all to the routes array using the post slug as the URL that will be generated. Hope this helps someone struggling to find information on generating dynamic routes using GraphQL. Please leave a comment if you have any questions.

// Comments