Default Apollo fetch policy in Nuxt

July 9th 2021 GraphQL NuxtJS

By default, the Apollo GraphQL client caches query responses. When using SSR with data sources that change frequently, this can be a problem. Fortunately, caching can be disabled, but setting this as the default behavior in a NuxtJS application proved more difficult than one would expect.

I used the NuxtJS Apollo module. Setting a different fetchPolicy for a single query worked as expected:

this.repositoryEdges = (
  await this.$apollo.query({
    fetchPolicy: "no-cache",
    query: starredRepositories,
    variables: {
      login: "damirarh",
    },
  })
).data.user.starredRepositories.edges;

However, setting the default value globally in nuxt.config.js had no effect:

apollo: {
  defaultOptions: {
    $query: {
      fetchPolicy: 'no-cache',
    },
  },
}

Further investigation revealed two reasons for this.

  1. The default options were not applied in @nuxtjs/apollo versions prior to 4.0.1-rc.4.

  2. I had to use query instead of $query as the key inside defaultOptions to make it work, although the documentation states otherwise:

    apollo: {
      defaultOptions: {
        query: {
          fetchPolicy: 'no-cache',
        },
      },
    }
    

The second part is even more intriguing. When I created a sample project for this blogpost, it turned out that the documented $query key works fine with smart queries:

@Component({
  apollo: {
    user: {
      query: starredRepositories,
      variables: {
        login: "damirarh",
      },
    },
  },
})
export default class IndexPage extends Vue {}

But when I explicitly called the Apollo client methods, the $query key was ignored and I had to use query instead:

this.repositoryEdges = (
  await this.$apollo.query({
    query: starredRepositories,
    variables: {
      login: "damirarh",
    },
  })
).data.user.starredRepositories.edges;

To make matters worse, the query key in the defaultOptions caused the smart queries to fail:

Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a "gql" tag?

This could be a problem if you use both smart queries and explicit method calls in your project. Fortunately, this is not the case for me.

You can try the described behavior in a sample project from my GitHub repository. Since I'm using the GitHub GraphQL API, you'll need to create your own personal access token and put it in plugins/apollo-config.js for the application to work.

The default query options in the NuxtJS Apollo module only work since version 4.0.1-rc.4, but even in the most recent version (4.0.1-rc.5), the correct key to use depends on how you run the queries. For smart queries, use $query. For explicit calls to Apollo client methods, use query instead. Unfortunately, the presence of this key in the default options causes smart queries to fail.

Get notified when a new blog post is published (usually every Friday):

Copyright
Creative Commons License