Apollo-module: How use vue instance in Apollo Client?

Created on 26 Jan 2018  路  18Comments  路  Source: nuxt-community/apollo-module

I want to define a vue instance to use in apollo client.

My plugin look like this:

import Vue from 'vue'

export default ({ req, app }, inject) => {
  // Inject `token` key
  // -> app.$token
  // -> this.$token in vue components
  // -> this.$token in store actions/mutations
  inject('token', new Vue({
    data: () => ({
      token: process.server ? req.session.authToken : window.__NUXT__.state.auth.token
    }),
    methods: {
      set (args) {
        this.token = args
      },
      remove () {
        this.token = undefined
      }
    }
  }))
}

Here is my apollo client

import { ApolloLink, concat, split } from 'apollo-link'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { WebSocketLink } from 'apollo-link-ws'
import { getMainDefinition } from 'apollo-utilities'
import 'subscriptions-transport-ws'
import Vue from 'vue'

export default (ctx) => {
  const httpLink = new HttpLink({ uri: 'https://api.graph.cool/simple/v1/cjaeub9io2kcz0115e4m0ql6d' })

  // auth token
  let token = ctx.app.$token.token
  ...
}

console.log(ctx.app) I still see the $token, but console.log(ctx.app.$token) I got undefined
Why am I doing this?

Even though we use store to get the token on client but window.__NUXT__.state.auth.token seem to be not working for me (I still get null token). I have to refresh the page to apply the token :(

This question is available on Nuxt.js community (#c53)

All 18 comments

@kieusonlam can you post your complete setup for the apollo-client? Then I might be able to assist

@dohomi Here is my setup current setup

import { ApolloLink, concat, split } from 'apollo-link'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { WebSocketLink } from 'apollo-link-ws'
import { getMainDefinition } from 'apollo-utilities'
import 'subscriptions-transport-ws'

export default (ctx) => {
  const httpLink = new HttpLink({ uri: 'https://api.graph.cool/simple/v1/cjaeub9io2kcz0115e4m0ql6d' })

  // if (process.client) console.log(ctx.app)

  // auth token
  let token = process.server ? ctx.req.session.authToken : window.__NUXT__.state.auth.token

  // Replacement
  // let token = ctx.app.$token.token

  // middleware
  const middlewareLink = new ApolloLink((operation, forward) => {
    operation.setContext({
      headers: { authorization: `Bearer ${token}` }
    })
    return forward(operation)
  })

  const wsLink = process.client ? new WebSocketLink({
    uri: `wss://subscriptions.ap-northeast-1.graph.cool/v1/cjaeub9io2kcz0115e4m0ql6d`,
    options: {
      reconnect: true,
      connectionParams: () => {
        const token = process.server ? ctx.req.session.authToken : window.__NUXT__.state.auth.token
        return {
          Authorization: token ? `Bearer ${token}` : null
        }
      }
    }
  }) : undefined

  const link = process.server ? httpLink : split(
    ({query}) => {
      const {kind, operation} = getMainDefinition(query)
      return kind === 'OperationDefinition' && operation === 'subscription'
    },
    wsLink,
    httpLink
  )

  return {
    link: concat(middlewareLink, link),
    cache: new InMemoryCache()
  }
}

Without Nuxt I can do something like this
https://github.com/Akryum/vue-apollo/issues/183

@kieusonlam this is my current setup, I use localstorage and the 'vue-ls' module:

import Vue from 'vue'
export const getTokenFromStorage = () => {
  if (process.server) {
    return {}
  }
  const token = Vue.ls.get('token')
  const user = Vue.ls.get('user_credentials')
  return {
    token,
    user
  }
}
(...)
  const authMiddleware = new ApolloLink((operation, forward) => {
    const token = getTokenFromStorage().token
    operation.setContext({
      headers: {
        authorization: token ? `Bearer ${token}` : null
      }
    })
    return forward(operation)
  })
  // Set up subscription
  const wsLink = new WebSocketLink({
    uri: `wss://subscriptions.graph.cool/v1/${process.env.GRAPHQL_ALIAS}`,
    options: {
      reconnect: true,
      connectionParams: () => {
        const token = getTokenFromStorage().token
        return {
          Authorization: token ? `Bearer ${token}` : null
        }
      }
    }
  })

Maybe this helps you out. For me only client-side authorization is necessary because of user-restricted pages.

Are you using nuxt for your project? I saw you import Vue from your client setup.

Yes I use nuxt, this is the apollo-module tailored for nuxt only :-)
I import Vue for the use of vue-ls (https://github.com/RobinCK/vue-ls) Its a small wrapper to set/get data for localstorage

I understood your concept. Thanks for your advice!

How did you guys set up the apollo client and in nuxt can you explain me step by step!!

@razorabhu1995 https://github.com/nuxt-community/apollo-module#setup here is everything explained. If you have further questions then please post your nuxt.config.js setup

modules: [ '@nuxtjs/apollo', ], apollo: { clientConfigs: { default: { httpEndpoint: 'http://localhost:3000/graphql', }, }, }
nuxt v4.0.0

this is my code in nuxt.config.js!!!
actually i require to get the authorization token in the request header for nuxt.
have no idea about how to use the code in middleware or in plugins!! @dohomi

@dohomi Can you provide me with step by step procedure for setting up authorization token in the request header to access the user restricted pages. Nothing seems to be working for me.

Check out the fully featured login example for nuxt. I guess you are talking about Nuxt 1.4.1? : https://github.com/nuxt-community/apollo-module/tree/master/test/fixture
For any additional information check the docs there is for every usecase one example: https://github.com/nuxt-community/apollo-module#build-in-methods

nope im using nuxt v4.0.0beta.1

@dohomi Actually my issue is somewhat same as https://github.com/nuxt-community/apollo-module/issues/5
i have seen your comments in this issue as well!!
While sending request to the server. I want my authorization token to be in the request header but have not been able to get it there.

@razorabhu1995 you need to provide more infos what you are currently tried: where did you call

this.$apolloHelpers.onLogin("YOUR_TOKEN")

you need to update to the latest beta of this package. Are you referring to have user authentication or do you want to set a permanent token? either way: set your token with the provided function onLogin and you should be good to go. Did you check the test folder of this package? There are the two most common usecases implemented as complete NuxtJs setup.
There are only 2 steps required to make this package connect to your graphql server:

1. => provide the config apollo as you already did
2.a => call this.$apolloHelpers.onLogin('your_token') in time you want to set the token
or if you have permanent token
2.b => provide an option getAuth:() => 'your_token'

@dohomi

What i need to do is:

  • first , User logins then user gets a token in response (this is already done).

  • Now, After getting that token, I need to set that token to the request header for each and every other request to the server.
    i am unable to set the token to the request header

@razorabhu1995 please provide a repo I really don't know what kind of problem you have. You must call:
this.$apolloHelpers.onLogin('here you user login token from the response...')

its solved!!!

Thank you very much!! @dohomi really appreciated!!!

Guys I have an issue with sending headers in websocket
my graphql subscription needs a auth header to work
I can send headers with https endpoint but in wss I can not find any place to set headers in.
please help me with that

When I mutate or get some queries it works good
but when i subscribe to an event the console show me this:

cannot start as connection_init failed with : x-hasura-admin-secret/x-hasura-access-key required, but not found

Was this page helpful?
0 / 5 - 0 ratings