5

How to update headers of apolloProvider?

Please check out nativescript-vue app repo:

https://github.com/kaanguru/vue-apollo-login

I can not explain properly so please check out the app. I don't know how to update appolloClient headers.

App repo has it's own comments and directives. It's easy to install and see by your self.

Current Structure of code:

Post request submits the user's identifier and password credentials for authentication and gets token in login page.

Apollo needs to place the jwt token into an Authorization header.

  • Main.js: Start apollo client if there is JWT start with headers

    • Goto login if there is no JWT

    • Goto birds list if there is JWT

  • Login : get jwt from server and write it to local storage

    • Go to birds list (does not show data because apollo initilised in main js)

structure


import ApolloClient from 'apollo-boost'
import VueApollo from 'vue-apollo'

Vue.use(VueApollo)

const apolloClient = new ApolloClient({
  uri: 'http://sebapi.com/graphql',

// HEADERS WORK FINE IF TOKEN WAS IN MAIN
//   headers: {
//     authorization: `Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTg2MzU2NzM2LCJleHAiOjE1ODg5NDg3MzZ9.wpyhPTWuqxrDgezDXJqIOaAIaocpM8Ehd3BhQUWKK5Q`,
// }

})
const apolloProvider = new VueApollo({
  defaultClient: apolloClient,
})

LOGIN.VUE

.then(
          (response) => {
            const result = response.content.toJSON();
            console.log("Result from Server: ", result);
            const token = result.jwt;

            // HOW TO ADD HEADERS TO APOLLOCLIENT this.$apollo.provider.defaultClient

            // this.$apollo.provider.defaultClient({
            //   request: (operation) => {
            //     operation.setContext({
            //       headers: {
            //         authorization: `Bearer ${result.jwt}` ,
            //       },
            //     });
            //   },
            // });

          },

Thank you for your interest.

NOTE: Please comment for more details. sebapi.com backend is a strapi graphql server.

Related Docs:

Apollo authentication

Apollo link composition

Vue apolloProvider Usage

Varit J Patel
  • 3,497
  • 1
  • 13
  • 21
Cem Kaan
  • 2,086
  • 1
  • 24
  • 55
  • 1
    Is there a way to extend Apollo provider – Cem Kaan Mar 29 '20 at 16:24
  • https://www.apollographql.com/docs/link/links/context/ I red apollo-link-context documentation. But my token is inside Vuex state. How can I set headers? – Cem Kaan Mar 31 '20 at 18:10
  • should I use vue-apollo local state instead of vuex state? Or can I pass Vuex.store state data to Vue Apollo Local State? – Cem Kaan Mar 31 '20 at 19:35
  • Have you tried initiating your the client in a diffrent file where you import the store instead? – Bhaskar Apr 03 '20 at 15:56
  • If I will initialize the client from somewhere other than main file, then there will be two copies of **apollo client** one in main file _handling auto-login_ and another one in the component which will _handle ordinary log in_. – Cem Kaan Apr 06 '20 at 14:40
  • I don't really understand the structure of your project. I personally have a client initalized at one point which I import throughout the project, as for login scenarios, I have a singular login function, and then, if I need to autologin (let's say using the authkey in cookies) I do it using a lifecycle hook of the authpage itself.. but the function used remains the same, so does the client.. – Bhaskar Apr 07 '20 at 05:58
  • 1
    Why would you have any business logic at all in your main.js file? Just initialize your apolloClient there (or in a diffrent file and export) In your app.vue file (which will initaially show the auth components), use the client in a lifcycle hook to autologin and if it fails, just stay on the login page, if it suceeds, goto the home page. – Bhaskar Apr 07 '20 at 06:26
  • @bhaskar I will give your offer a try and let you know. For now, I don't know if I can initialize apollo in the main file then add headers in login file. – Cem Kaan Apr 07 '20 at 09:25

1 Answers1

6

The thing is you need to use ApolloLink in order to use it for all the requests. The way you're using won't work.

You have to use middleware apollo-link-context to achieve this.

As per Apollo-link-context docs

apollo-link-context: Used to set a context on your operation, which is used by other links further down the chain.

The setContext function takes a function that returns either an object or a promise that returns an object to set the new context of a request. Add the below code to app.js and modify some changes and check.

import { setContext } from 'apollo-link-context'

const authLink = setContext((_, { headers }) => {
    // get the authentication token from ApplicationSettings if it exists
    const token = ApplicationSettings.getString("token");

    // return the headers to the context so HTTP link can read them
    return {
        headers: {
            ...headers,
            authorization: token ? `Bearer ${token}` : null
        }
    }
})

// update apollo client as below
const apolloClient = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache() // If you want to use then 
})

Change in Login.vue

.then(
    (response) => {
    const result = response.content.toJSON();
    console.log("Result from Server: ", result);
    const token = result.jwt;
    // Set token using setString
    ApplicationSettings.setString("token", result.jwt);
},

Hope this helps!

Varit J Patel
  • 3,497
  • 1
  • 13
  • 21
  • 1
    You have store the token and use it in main.js. The thing which you need to pass the token is apollo-link-context. I'm not having android so I said it won't work in my Mac. – Varit J Patel Apr 10 '20 at 02:42
  • 1
    @cemkaan I have added the updated answer to how you can store the token and retrieve it in middleware. Hope this is clear now. – Varit J Patel Apr 10 '20 at 05:02
  • Did you check? It will take as all requests are passing through it. don't think about it is in the main.js file so it won't work. For every request you make, it will bypass through apollo-link-context and add headers if the token exists. – Varit J Patel Apr 10 '20 at 06:41