For the complete documentation index, see llms.txt. This page is also available as Markdown.

User authentication

Now that users can sign up, let's see how do send the token with all requests.

We need to remove apollo-boost to start using apollo-link.

~/packages/web
$ yarn remove apollo-boost
$ yarn add apollo-link-http apollo-link-context apollo-cache-inmemory graphql-tag

In App.tsx replace:

import ApolloClient from "apollo-boost";
const client = new ApolloClient({ uri: "/graphql" });

with:

import ApolloClient from "apollo-client";
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';

const httpLink = createHttpLink({
  uri: '/graphql',
});

const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = localStorage.getItem('token');
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

Also replace import { gql } from "apollo-boost" withimport gql from "graphql-tag";

To see if this is working we can log out context in our Health resolver:

LinksPage.tsx is still sending a query to Health. You should see the following in your terminal:

send-tokenbranch available on GitHub.

Last updated