question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to update ApolloClient after login?

See original GitHub issue

Hi, I’m trying to do token based authentication for my app, I have something like this

async function getHttpLink() {
  const httpLink = createHttpLink({
    uri: `${hostUrl()}/graphql`
  });
  const token = await getAuthToken();
  const authLink = getAuthLink(token);

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

function getAuthLink(token) {
  const authLink = setContext((_, { headers }) => {
    return {
      headers: {
        ...headers,
        authorization: token ? `Bearer ${token}` : null,
        test: "test"
      }
    };
  });
  return authLink;
}

then in my main.js I have something like this

  setApolloClient = async () => {
    try {
      await getHttpLink().then(client => {
        this.setState({
          client
        });
      });
    } catch (e) {
      console.log(e);
    }
  };

  render() {
    const Layout = RootNavigator(signedIn, this.isCustomerVerified());
    return (
      <ApolloProvider client={this.state.client}>
        {/*<Layout screenProps={{ setApolloClient: this.setApolloClient }} />*/}
        <Layout />
      </ApolloProvider>
    );
  }

Intended outcome: So the plan is before the user is signed in, the token is nil

After sign in happens, the headers will get the newly created auth token from AsyncStorage.

Actual outcome: When I check the headers in the servers, token is still nil. I’m pretty sure the token is stored in AsyncStorage as when I refresh it goes skips the login page and goes straight to the home page.

Version

  • apollo-client@2.2.0

Thanks in advance for any help given, please tell me if you need any more info!

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:2
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

6reactions
Poincarecommented, Jan 26, 2018

This seems difficult to debug without more of the surrounding code, but here are a few things to try:

  • Log the value of the token after you await getAuthToken and make sure it is defined
  • Examine the network request sent by the browser to the server and make sure that it is formed as you expect it. I see you have a “test” header - is that sent to the server correctly?
3reactions
haulxnextfunccommented, Oct 5, 2018

return new ApolloClient({ cache, uri: Api.GRAPH_QL_URL, clientState: {defaults, resolvers}, request: async operation => { console.log("Client request: ", { operationName: operation.operationName, variables: operation.variables, query: operation.query }); let token = await AsyncStorage.getItem(strings.keyToken); operation.setContext({ headers: { Accept: “application/json”, authorization: token ? JWT ${token} : “” } }); } });

check the request option

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to update ApolloClient authorization header after ...
Basically, we have this in our index. js file to set-up the ApolloProvider authorization to make queries / mutations. import React from 'react' ......
Read more >
Authentication - Apollo GraphQL Docs
Reset store on logout. Since Apollo caches all of your query results, it's important to get rid of them when the login state...
Read more >
How to update ApolloClient authorization header after ...
Another way to achieve this is that you can use setLink method from apollo-config. After that, export a function that'll set the headers...
Read more >
Refreshing Token Based Authentication With Apollo Client 2.0
A common method of authentication on the web is JSON Web Tokens (JWT). A user logs in using their username and password, and...
Read more >
Build: Updating your cache with Apollo Client - YouTube
Janessa and Trevor take us through updating the cache with Apollo Client in this instalment of Apollo's BUILD series.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found