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

8
  • 1
    Is there a way to extend Apollo provider Commented Mar 29, 2020 at 16:24
  • apollographql.com/docs/link/links/context I red apollo-link-context documentation. But my token is inside Vuex state. How can I set headers? Commented Mar 31, 2020 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? Commented Mar 31, 2020 at 19:35
  • Have you tried initiating your the client in a diffrent file where you import the store instead? Commented Apr 3, 2020 at 15:56
  • 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. Commented Apr 7, 2020 at 6:26

1 Answer 1

6
+100

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!

Sign up to request clarification or add additional context in comments.

3 Comments

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.
@cemkaan I have added the updated answer to how you can store the token and retrieve it in middleware. Hope this is clear now.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.