Next.js Discord

Discord Forum

Vercel ISR with data fetched with Apollo Client

Unanswered
Alan posted this in #help-forum
Open in Discord
I am using Apollo client to fetch post data from a wordpress site and display it on my next.js webpage. What I want to do is have the data be revalidated whenever a new post is created. This is all working fine.

The problem is that when the data gets revalidated the page takes 5 seconds, which is less than ideal.

My understanding of ISR is that users would be sent prerendered pages and all data fetching would be done on the server, eliminating the need for the content to be fetched at each request.

Below I have attached all related code:

main-card.tsx
import { GetPostsByCatDocument, GetPostsByCatQuery } from 'graphql/queries.generated'
import { getClient } from '@the-heights/apollo-client';

export interface MainCardProps {

}


export async function MainCard() {
  const { data: {posts} } = await getClient().query<GetPostsByCatQuery>({
    query: GetPostsByCatDocument,
    variables: { first: 5, categoryName: 'top story' },
    context: {
      fetchOptions: {
        next: { tags: ["posts"] },
      },
    },
  });

//react code and stuff
}


apollo-client.ts
import { ApolloClient, HttpLink, InMemoryCache } from "@apollo/client";
import { registerApolloClient } from "@apollo/experimental-nextjs-app-support/rsc";

export const { getClient } = registerApolloClient(() => {
    return new ApolloClient({
      cache: new InMemoryCache(),
      link: new HttpLink({
        uri: "https://www.bcheights.com/graphql",
      }),
      defaultOptions: {
        query: {
          fetchPolicy: 'no-cache'
        },
      }
    });
  });

route.ts
'use server'

import { NextRequest, NextResponse } from 'next/server'
import { revalidateTag } from 'next/cache'


export async function POST(req: NextRequest) {

const data = await req.json();
const apiKey = req.headers.get('x-api-key')
if (apiKey !== process.env.WP_X_API_KEY) {
return NextResponse.error();
}

console.log(data);

revalidateTag('posts');
}

Any help would be greatly appreciated!!

2 Replies

Okay I’ve done some skimming of previous posts… Would it be better to use SWR for this?
Whiteleg shrimp
I wonder if you have to use the fetch provided by next or, alternatively, use route level caching. Apollo does allow you to specify your own fetch method so that's a possibility. The documentation here lays it out pretty well https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating.

Another approach is to use this method:
https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#fetching-data-on-the-server-with-third-party-libraries

Which moves the caching one level up so you don't have to do any replacement of the fetch