Update - 10/2021
Using @apollo/client
and graphql
packages:
import {
ApolloClient,
InMemoryCache,
gql,
HttpLink
} from "@apollo/client";
import { setContext } from "@apollo/client/link/context";
const token = "YOUR_TOKEN";
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
authorization: token ? `Token ${token}` : null,
},
};
});
const client = new ApolloClient({
link: authLink.concat(
new HttpLink({ uri: "https://api.github.com/graphql" })
),
cache: new InMemoryCache(),
});
client
.query({
query: gql`
query ViewerQuery {
viewer {
login
}
}
`,
})
.then((resp) => console.log(resp.data.viewer.login))
.catch((error) => console.error(error));
Original post - 12/2017
You can define authorization header using apollo-link-context
, check the header section
A complete example for using apollo-client for Github API would be :
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';
import gql from 'graphql-tag';
const token = "YOUR_ACCESS_TOKEN";
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : null,
}
}
});
const client = new ApolloClient({
link: authLink.concat(new HttpLink({ uri: 'https://api.github.com/graphql' })),
cache: new InMemoryCache()
});
client.query({
query: gql`
query ViewerQuery {
viewer {
login
}
}
`
})
.then(resp => console.log(resp.data.viewer.login))
.catch(error => console.error(error));