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.

Async Middleware (with ApolloLink)

See original GitHub issue

Intended outcome:

To resolve a promise inside an ApolloLink middleware to adjust request headers.

Actual outcome:

Wasn’t able to write code that works.

How to reproduce the issue:

import { ApolloLink } from 'apollo-client-preset'

export const authMiddleware = new ApolloLink((operation, forward) => {
  resolvePromise().then(data => {
    operation.setContext(({ headers = {} }) => ({
      headers: {
        ...headers,
        authorization:  || null,
      }
    }))

    return forward(operation)
  })
})

There’s no examples regarding this type of middleware in the docs. How can this be achieved?

Version

  • apollo-client@^2.0.1

Issue Analytics

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

github_iconTop GitHub Comments

80reactions
vtsatskincommented, Nov 15, 2017

@pycraft114 @matteodem Here is how I got it working:

import {
  ApolloClient,
  InMemoryCache,
  ApolloLink,
  from,
} from "apollo-client-preset";
import { setContext } from "apollo-link-context";
import { createHttpLink } from "apollo-link-http";

import { AsyncStorage } from "react-native";

const GRAPHQL_API_ENDPOINT = "https://path/to/graphql/api"

const httpLink = createHttpLink({
  uri: GRAPHQL_API_ENDPOINT,
});

const authMiddleware = setContext(operation =>
  somePromise().then(token => {
    return {
      // Make sure to actually set the headers here
      headers: { 
        authorization: token || null,
      },
    };
  })
);

const client = new ApolloClient({
  link: from([authMiddleware, httpLink]),
  cache: new InMemoryCache(),
});

@jbaxleyiii The documentation was a little confusing due to not having a fully working example with the HTTP link. I understand this is meant to be generalized for any link, but your advice in this issue was a little misleading due to having to set explicitly structure the context to what HttpLink expects. How can we make the documentation clearer in the migration and other related documentations?

77reactions
marceloogedacommented, Mar 2, 2018

Following the @vtsatskin’s implementation, I’ve changed the authMiddleware function to works with async/await.

const authMiddleware = setContext(async (req, { headers }) => {
  const token = await AsyncStorage.getItem(TOKEN_NAME);

  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : ''
    },
  };
});
Read more comments on GitHub >

github_iconTop Results From Across the Web

Apollo HttpLink Async - Stack Overflow
You can use apollo-link-context to modify your requests. You can cache the values as shown if you don't fetch them on every request....
Read more >
Advanced HTTP networking - Apollo GraphQL Docs
Take full network control with Apollo Link. The Apollo Link library gives you fine-grained control of HTTP requests that are sent by Apollo...
Read more >
How to use the apollo-link.from function in apollo-link - Snyk
To help you get started, we've selected a few apollo-link.from examples, ... ApolloClient({ link: from([Middleware, Afterware, errorLink, httpLink]), cache, ...
Read more >
Apollo GraphQL : Async Access Token Refresh - Able
We'll be using the fromPromise utility function from the apollo-link package to transform our Promise to an Observable.
Read more >
apollo-link.Operation.setContext JavaScript and Node.js code ...
function createClient(headers, token, initialState) { let accessToken = token; (async () => { // eslint-disable-next-line no-param-reassign accessToken ...
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