Next.js + Apollo Server SSR

Hello everyone,

I have a question regarding Apollo Server integration with Next.js. I have a Next.js application with Apollo server running in the server part (same server).

Next.js way of handling SSR is to request the data in getServerSideProps/getStaticProps and pass the result to the client. Being on the server it’s encouraged that you avoid making unnecessary HTTP requests and instead directly call the functionality that’s available on the server (directly query the database or what have you).

My problem is that I wish to use the graphql pipeline but skip making the HTTP request and directly query the “system”. I have noticed that apollo server exposes executeOperation which does exactly what I need but the docs recommend using it for integration testing and doesn’t mention using it in any other way.

My solution would look something like this:

export const getStaticProps: GetStaticProps = async (context) => {
    const data = await apolloServer.executeOperation(QUERY HERE, context)
    return {
	props: data
    }
}

This code snippet is simplified to showcase the main idea.

Finally my question is: Could this work? Is there any downside to my method? Does anyone have a solution for this problem? Should I just give up and make an HTTP request even if it’s server to server on the same address?

Hi @notsaved :wave: welcome to the forum! I found a couple posts that might help set some context for executeOperation:

Based on these threads I don’t think there are any red flags that should stop you from using executeOperation in production. Maybe @glasser or @trevor.scheer might have some additional thoughts?

Thanks a lot for the reply, I tried to search before asking but not very well apparently. That was exactly what I was looking for! Cheers

At a quick glance, I think my recommendation would be to use the executeHTTPGraphQLRequest method and just fudge the HTTP bits that it expects in the parameters (you’ll need to correctly specify some headers to bypass csrf prevention, for example). I think this gives you the best of both worlds - not sending an actual HTTP request while calling into Apollo Server in a more comprehensive manner.

Some code paths that you’d be skipping by calling into executeOperation directly include:

  • some of the early plugin lifecycle methods won’t be called
  • batched queries
  • incremental delivery / @defer implementation

If you know none of those things are interesting to you then executeOperation is probably fine :slight_smile:

2 Likes