I keep seeing examples about setting context on Apollo Client like this :
new ApolloClient({
uri: '...',
request(operation) {
const currentUser = readStore<CurrentUser>("currentUser");
currentUser &&
operation.setContext({
headers: { authorization: currentUser.token },
other: "things"
});
}
});
}
With things that go to the request headers, and "other" things. Yet after more than 2h of research, I couldn't find one example of that other context data being retrieved on the other end, on Apollo Server.
It seems like all the examples are about authorization tokens, but how to I retrieve the rest, say using apollo-server-express
?
Here is what I have so far :
const apollo = new ApolloServer({
typeDefs,
resolvers,
context({ req }): Context {
const currentUser =
(req.headers.authorization &&
(jwt.verify(
req.headers.authorization,
process.env.JWTSIGN
) as Context["currentUser"])) ||
null;
// Ok for req.headers.authorization, how to I get "other: things" ?
return {
ip: req.ip,
currentUser
};
}
});
The context
function here only gets a req and a res object from Express. After some logs, it doesn't seem to contain the data I want.
Thank you.
The only reason it appears headers are shared in the example you shared is because ApolloClient
uses the headers
value inside its context to populate the HTTP headers it sends when making a request. Those headers are then parsed by express
and made available on the req
object. The context used by ApolloClient
is strictly client-side. The context used by ApolloServer
is strictly server-side. You can't use ApolloClient
's context to pass arbitrary values to your server -- you should utilize headers or arguments inside your GraphQL query for that.