vuejs / apollo

🚀 Apollo/GraphQL integration for VueJS
http://apollo.vuejs.org
MIT License
6.03k stars 522 forks source link

Setting up Apollo with frameworks #460

Open lggwettmann opened 5 years ago

lggwettmann commented 5 years ago

Hey guys,

I've had quite some trouble setting up Apollo(-Boost) with Django cause the docs are not very extensive and difficult structured between Apollo, Vue-Apollo, Vue-Apollo-Boost (which doesn't seem to be documented at all).

I'd suggest adding a small section for all framework users out there. Eg for Django, I needed to find out about this to make CSRF protection work. Took me about three days.

Step 1> Install JS Cookie --> npm install --save js-cookie Step 2> Add the CSRF token to the Apollo client header:

import ApolloClient from 'apollo-boost'
import VueApollo from 'vue-apollo'
import Cookies from 'js-cookie'
Vue.use(VueApollo)

const apolloProvider = new VueApollo({
  defaultClient: new ApolloClient({
    headers: {
      'X-CSRFToken': Cookies.get('csrftoken')
    }
  })

Done.

Thanks in advance.

glinskyc commented 5 years ago

I experienced similar troubles that could have easily been explained in the documentation. As an Apollo newcomer, I have found the docs pertaining to the configuring of Apollo to be too minimal.

Upon installing the vue-apollo plugin, I had to configure Apollo in the following way to make use of a JWT and CSRF token stored in cookies (an alternative approach using JWT in localStorage). The JWT is typically an httponly cookie.

const defaultOptions = {

    // ... also config other things like httpEndpoint

    httpLinkOptions: {
        credentials: 'include',  // use 'same-origin' if it is appropriate for your case
        headers: {'X-CSRF-TOKEN': CSRF_TOKEN},
    },
    // since JWT is sent via cookies, getAuth() does not need to get a token from the authorization header
    getAuth: () => {return undefined},
  },

where CSRF_TOKEN is the value retrieved from a cookie. defaultOptions then gets used within createApolloClient:

const {apolloClient, wsClient} = createApolloClient({
    ...defaultOptions,
    ...options,
  });

If it applies to you, also make sure to configure your server, which hosts your GraphQL API, for CORS. Hopefully this saves someone else the trouble.

voluntadpear commented 5 years ago

Thanks @glinskyc your approach worked!