Search code examples
androidvue.jsgraphqlnativescript-vuevue-apollo

How to add headers in login.vue?


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


Solution

  • 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!