Created
May 16, 2018 13:24
-
-
Save Gomah/3937698ed3938723c3a6f319c60398a3 to your computer and use it in GitHub Desktop.
Nuxt apollo client, restore cache on client & optimize SSR
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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