The introduction of Vue3 a few years back gave Vue fans the option of using a so-called Composition API to write components (the “classic” way was rebranded as the “Options” API). I’ll admit I had a little bit of heartburn over this — I didn’t love working in React, and was worried that Vue was making a move that would over-complicate a framework that I felt was perfect in its simplicity. After working in the composition API for the last 6 months or so, I can say that it has grown on me.
One challenge, however, is that the Composition is much less “Google-able.” I found myself Googling for how to do things and finding that for every 1 article or Stack Overflow post providing an answer with Vue “Composition” code, I’d find 20 provided in the traditional “Options” code.
One such time was when I was attempting to connect to 2 separate GraphQL servers using Vue Apollo . Of course, eventually, I did find in their Docs a basic example of how to set this up, which you can find here and skip this article altogether. On the other hand, if you’re looking for a more substantial example, keep reading!
For this example, I’m going to create a useApolloClients
function that takes in 2 different URL endpoints and returns 2 Apollo services, one for each. In each of these services, we’re going to go ahead and setup an InMemoryCache()
and also inject a JWT into the headers of each GQL HTTP request. Finally, I’ll show how to wire those up in your Vue3’s main.js
. Let’s get started.
ApolloClient Creation #
First, install the requisite packages
yarn add @vue/apollo-composable @apollo/client
Then, in a file located somewhere like src/util/useApolloClients.js
, you’ll have three functions
getHeaders #
getHeaders is where you take your JWT (stored in local state, or asynchronously somewhere else), and stuff it in an HTTP header. Later we’ll tell Apollo to use this function for every request.
createClient #
createClient handles the magic of taking your desired settings, your created HTTP headers, and your GraphQL server’s URL and spits back out an Apollo Client.
useApolloClients #
This is the function you will export. For my case here, we take 2 URL for 2 different GraphQL servers. The first will be the default. The second can take whatever name you want here; that name is how it will be called in code.
Final src/util/useApolloClients.js #
Provide Clients in main.js #
Now that we have that ready, let’s make them available in your app. Your main.js will look something like this.
In Action #
Now, in your Composition API components, you have access to either server when you run a mutation, query, or subscription. By default, if you don’t specify anything, Apollo will send your request to the default
service you setup in your configuration. If you want to switch to a different client, your code will look something like this.
That’s it! Happy GraphQLing.