- Nuxt.js module to use vue-apollo
- uses internally same approach as vue-cli-plugin-apollo
This version requires Vue 2.6+ with serverPrefetch support. For example:
npm install --save vue@2.6.6 vue-template-compiler@2.6.6 vue-server-renderer@2.6.6Sometime you may need to remove/rebuild package-lock.json/yarn.lock to make it work.
npm install --save @nuxtjs/apolloor
yarn add @nuxtjs/apollo// nuxt.config.jsexportdefault{modules: ['@nuxtjs/apollo',],apollo: {clientConfigs: {default: {httpEndpoint: 'http://localhost:4000',}}}}Install graphql-tag
npm install --save graphql-tagor
yarn add graphql-tagAdd a gql.d.ts file in your sources folder with the following content:
declare module '*.gql'{import{DocumentNode}from'graphql'constcontent: DocumentNodeexportdefaultcontent}declare module '*.graphql'{import{DocumentNode}from'graphql'constcontent: DocumentNodeexportdefaultcontent}You have a successfully enabled vue-apollo in your project.
Checkout Official example and vue-apollo official documentation for how to use vue-apollo inside your application
{// Add apollo modulemodules: ['@nuxtjs/apollo'],apollo: {// Sets up the apollo client endpointsclientConfigs: {// recommended: use a file to declare the client configuration (see below for example)default: '~/plugins/my-alternative-apollo-config.js'// you can setup multiple clientsalternativeClient: {// requiredhttpEndpoint: 'http://localhost:4000',// override HTTP endpoint in browser onlybrowserHttpEndpoint: '/graphql',// See https://www.apollographql.com/docs/link/links/http.html#optionshttpLinkOptions: {credentials: 'same-origin'},// You can use `wss` for secure connection (recommended in production)// Use `null` to disable subscriptionswsEndpoint: 'ws://localhost:4000',// LocalStorage tokentokenName: 'apollo-token',// Enable Automatic Query persisting with Apollo Enginepersisting: false,// Use websockets for everything (no HTTP)// You need to pass a `wsEndpoint` for this to workwebsocketsOnly: false},},/** * default 'apollo' definition */defaultOptions: {// See 'apollo' definition// For example: default query options$query: {loadingKey: 'loading',fetchPolicy: 'cache-and-network',},},// setup a global query loader observer (see below for example)watchLoading: '~/plugins/apollo-watch-loading-handler.js',// setup a global error handler (see below for example)errorHandler: '~/plugins/apollo-error-handler.js',// Sets the authentication type for any authorized request.authenticationType: 'Bearer',// Token name for the cookie which will be set in case of authenticationtokenName: 'apollo-token',// [deprecated] Enable the graphql-tag/loader to parse *.gql/*.graphql filesincludeNodeModules: true,// Cookie parameters used to store authentication tokencookieAttributes: {/** * Define when the cookie will be removed. Value can be a Number * which will be interpreted as days from time of creation or a * Date instance. If omitted, the cookie becomes a session cookie. */expires: 7,/** * Define the path where the cookie is available. Defaults to '/' */path: '/',/** * Define the domain where the cookie is available. Defaults to * the domain of the page where the cookie was created. */domain: 'example.com',/** * A Boolean indicating if the cookie transmission requires a * secure protocol (https). Defaults to false. */secure: false,},}}getAuth or inMemoryCacheOptions.fragmentMatcher) inside apollo configuration, you MUST define your clientOptions using an external file
// ~/plugins/my-alternative-apollo-config.jsexportdefault(context)=>{return{httpEndpoint: 'http://localhost:4000/graphql-alt',/* * For permanent authentication provide `getAuth` function. * The string returned will be used in all requests as authorization header */getAuth: ()=>'Bearer my-static-token',}}// ~/plugins/apollo-watch-loading-handler.jsexportdefault(isLoading,countModifier,nuxtContext)=>{loading+=countModifierconsole.log('Global loading',loading,countModifier)}// ~/plugins/apollo-error-handler.jsexportdefault({ graphQLErrors, networkError, operation, forward },nuxtContext)=>{console.log('Global error handler')console.log(graphQLErrors,networkError,operation,forward)}You can either (in a simple setup) just add an object as described above. If you need to overwrite cache or the default getAuth() function then use a path to your config file which returns the client config options.
Sets up the apollo client endpoints. All available options for each endpoint you find here
Check out official vue-apollo-cli where possible usecases are presented.
Token name for the cookie which will be set in case of authentication. You can also provide an option tokenName in each of your clientConfigs to overwrite the default. When each request is made, the value of whatever is in this cooke will be sent in an "Authorization" HTTP header as specified by authenticationType below.
Sets the authentication type for any authorized request. Modify this if the authentication type your GraphQL API requires is not the default Bearer. All requests will then be sent with the appropriate HTTP header in the format: "Authorization: " (Eg. Authorization: Bearer abc123).
If your backend requires an Authorization header in the format "Authorization: ", without any prefix, then you should set this value to an empty string.
In case you use *.gql files inside of node_module folder you can enable the graphql-tag/loader to parse the files for you.
You have following methods for authentication available:
// set your graphql-tokenthis.$apolloHelpers.onLogin(token/* if not default you can pass in client as second argument, you can set custom cookies attributes object as the third argument, and you can skip reset store as the fourth argument */)// unset your graphql-tokenthis.$apolloHelpers.onLogout(/* if not default you can pass in client as first argument, and you can skip reset store as the second argument */)// get your current token (we persist token in a cookie)this.$apolloHelpers.getToken(/* you can provide named tokenName if not 'apollo-token' */)Check out the full example
// ~/components/my-component.jsexportdefault{methods: {asynconSubmit(){constcredentials=this.credentialstry{constres=awaitthis.$apollo.mutate({mutation: authenticateUserGql,variables: credentials}).then(({data})=>data&&data.authenticateUser)awaitthis.$apolloHelpers.onLogin(res.token)}catch(e){console.error(e)}},}}// ~/components/my-component.jsexportdefault{methods: {asynconLogout(){awaitthis.$apolloHelpers.onLogout()},}}// ~/middleware/isAuth.jsexportdefault({app, error})=>{consthasToken=!!app.$apolloHelpers.getToken()if(!hasToken){error({errorCode:503,message:'You are not allowed to see this'})}}// ~/store/my-store.jsexportdefault{actions: {foo(store,payload){letclient=this.app.apolloProvider.defaultClient}}}// ~/components/my-component.jsexportdefault{asyncData(context){letclient=context.app.apolloProvider.defaultClient}}exportdefault{nuxtServerInit(store,context){letclient=context.app.apolloProvider.defaultClient}}// ~/components/my-component.jsexportdefault{methods: {foo(){// receive the associated Apollo client constclient=this.$apollo.getClient()// most likely you would call mutations like following:this.$apollo.mutate({mutation, variables})// but you could also call queries like this:this.$apollo.query({query, variables}).then(({ data })=>{// do what you want with data})}}}Once you get the client, you can access its methods and properties. See API Reference
// nuxt.config.jsexportdefault{apollo: {foo: {query: fooGql,variables(){return{myVar: this.myVar}}}}}See vue-apollo documentation for more information on smart queries
// nuxt.config.jsexportdefault{apollo: {clientConfigs: {default: '~/apollo/client-configs/default.js'},includeNodeModules: true}}Version 4 of this module leaves you with zero configuration. This means we use the best possible approach available from vue-cli-plugin-apollo and the same configuration behaviour. This means you don't need to wire up your own configuration, simply pass
Edit your configuration as following:
// nuxt.config.jsexportdefault{apollo: {clientConfigs: {default:{httpEndpoint: YOUR_ENDPOINT,wsEndpoint: YOUR_WS_ENDPOINT}}}}Version 3 of this module is using apollo-client 2.x. You need to make sure to update all your middle/afterware according to the upgrade guide of apollo-client. Check this source for a reference: https://www.apollographql.com/docs/apollo-server/migration-two-dot/
CORS errors are most often resolved with proxies. If you see a Cross-Origin-Request error in your client side console look into setting up a proxy. Check out https://github.com/nuxt-community/proxy-module for quick and straight forward setup.
This is just a placeholder. You'll want to replace it with whatever storage mechanism you choose to store your token. Here is an example using local storage : vuejs/apollo#144
Setup the required fields in .env file in root folder
# cat .env
HTTP_ENDPOINT=https://your-endpoint
WS_ENDPOINT=wss://your-endpointIn index.vue the login process requires that the gql endpoint enables a mutation which returns a valid token:
mutationauthenticateUser($email:String!,$password:String!){
authenticateUser(email: $email, password: $password) {
tokenid
}
}If your gql backend is prepared start running nuxt as follow
npm install
npm run dev