Using SSR + setContext + createHttpLink results in empty initialState
See original GitHub issueIntended outcome: I am using Apollo with NextJS to get SSR on my app. I followed the instructions on this example and this example to add Apollo to Next.js
Everything was working fine until I upgraded to Apollo Data 2.x following the instructions found on this page
Actual outcome: Now, when I use SSR + setContext + createHttpLink together, the initial state is Empty. The following code is how I have implemented it:
const cache = new InMemoryCache({
dataIdFromObject: (o) => o._id,
addTypename: true,
});
const httpLink = createHttpLink({
fetch,
uri: 'http://localhost:3333/graphql',
credentials: 'same-origin'
});
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 || null,
}
};
});
return new ApolloClient({
link: authLink.concat(httpLink)
queryDeduplication: true,
ssrMode: !process.browser,
cache: cache.restore(initialState || {}),
});
While this code works, and I see no errors, the initialState is empty and therefore the SSR is not working for my async requested data coming from the Database.
How to reproduce the issue:
if you change the code to be like the following, it works, but now I don’t have my token inside my header:
const cache = new InMemoryCache({
dataIdFromObject: (o) => o._id,
addTypename: true,
});
const httpLink = createHttpLink({
fetch,
uri: 'http://localhost:3333/graphql',
credentials: 'same-origin'
});
// I have to ignore the context, since using the concat method will break the initialState
return new ApolloClient({
link: httpLink
queryDeduplication: true,
ssrMode: !process.browser,
cache: cache.restore(initialState || {}),
});
Version I am using the following versions:
"apollo-cache-inmemory": "^1.1.0",
"apollo-client": "^2.0.2",
"apollo-engine": "^0.5.4",
"apollo-link": "^1.0.0",
"apollo-link-context": "^1.0.0",
"apollo-link-http": "^1.1.0",
"apollo-link-set-context": "^0.5.4",
"apollo-server-express": "^1.2.0",
"apollo-utilities": "^1.0.1",
"react": "^16.0.0",
"react-apollo": "^2.0.1",
"react-dom": "^16.0.0",
"next": "^4.1.4",
Issue Analytics
- State:
- Created 6 years ago
- Comments:5 (2 by maintainers)
If you can not get it from the links I sent you, let me know and I will create a repo, but most of my code regarding graphql, is identical to the links I sent you, all I am adding to it is
const authLink = setContext((_, { headers }) => {
partThis should no longer be an issue with modern day
apollo-client
(2.3.2) andreact-apollo
(2.1.4). Please post back if you notice otherwise. Thanks!