Ask Your Question

What is the process to implement cache.writeQuery while using next and apollo-server for SSR?

asked 2021-12-10 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2021-12-04 19:00:00 +0000

bukephalos gravatar image

To implement cache.writeQuery while using next and apollo-server for SSR, you can follow these steps:

  1. In your Next.js application, create a new file named apolloClient.js. Here, you will define your Apollo client and set up the cache.

  2. Import InMemoryCache from apollo-cache-inmemory and ApolloClient from apollo-client.

  3. Create a new instance of InMemoryCache and pass it as an argument to the ApolloClient constructor.

  4. Define uri for your Apollo server, which will be used to create the HttpLink for the client.

  5. Pass the cache and link to the ApolloClient constructor, and export the ApolloClient instance.

Example code for apolloClient.js:

import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';

const cache = new InMemoryCache();

const link = new HttpLink({
  uri: 'http://localhost:4000/graphql', // replace with your server URL

export const apolloClient = new ApolloClient({
  1. Import the apolloClient instance into your Next.js pages where you want to fetch data with Apollo.

  2. In your component's getInitialProps method, use the apolloClient to fetch data.

Example code for a page that fetches data with Apollo and writes to the cache using cache.writeQuery:

import { gql } from 'apollo-boost';
import { apolloClient } from '../apolloClient';

const MY_QUERY = gql`
  query MyQuery {
    myData {

const MyPage = ({ data }) => (
    <p>ID: {}</p>

MyPage.getInitialProps = async () => {
  const { data } = await apolloClient.query({ query: MY_QUERY });
    query: MY_QUERY,
  return { data: data.myData };

export default MyPage;

In this example, the getInitialProps method calls apolloClient.query to fetch data from the server. After the data is received, cache.writeQuery is called to write the data to the cache. Finally, the data object is returned as a prop to the component.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer

Question Tools


Asked: 2021-12-10 11:00:00 +0000

Seen: 8 times

Last updated: Dec 04 '21