Skip to content

Instantly share code, notes, and snippets.

@Gomah
Created May 16, 2018 13:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gomah/3937698ed3938723c3a6f319c60398a3 to your computer and use it in GitHub Desktop.
Save Gomah/3937698ed3938723c3a6f319c60398a3 to your computer and use it in GitHub Desktop.
Nuxt apollo client, restore cache on client & optimize SSR
import { ApolloLink } from 'apollo-link';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
export default ctx => {
const httpLink = new HttpLink({
uri: process.env.PROJECT_GRAPHQL_SERVER,
});
const cache = new InMemoryCache();
// If on the client, recover the injected state
if (process.client) {
if (typeof window !== 'undefined') {
window.onNuxtReady(() => {
cache.restore(window.__NUXT__.apollo.defaultClient);
});
}
}
const middlewareLink = new ApolloLink((operation, forward) => {
const token = ctx.app.$cookies.get('access_token');
if (token) {
operation.setContext({
headers: { Authorization: `Bearer ${token}` },
});
}
return forward(operation);
});
const link = middlewareLink.concat(httpLink);
return {
link,
cache,
...(process.server
? {
// Set this on the server to optimize queries when SSR
ssrMode: true,
}
: {
// This will temporary disable query force-fetching
ssrForceFetchDelay: 100,
}),
connectToDevTools: process.env.NODE_ENV !== 'production',
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment