next.jsapollo-client

How to use noStore in apollo client wrapper in nextJS app router?


I'm using the app router of nextJS for the first time and I need to implement apollo client with using env variables on runtime:

app/layout.tsx

import { ApolloWrapper } from './ApolloWrapper'
import './global.css'

export const metadata = {
  title: 'Welcome to example'
}

export default function RootLayout({
  children
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>
        <ApolloWrapper>{children}</ApolloWrapper>
      </body>
    </html>
  )
}

In this page I can use the BACKEND env variable on runtime, which is set in my docker compose file:

app/page.tsx

import { unstable_noStore as noStore } from 'next/cache'

export default function Index() {
  noStore()
  return <div className="wrapper">Backend: {process.env['BACKEND']}</div>
}

But how do I implement this in the apollo wrapper - which is a client component?

app/ApolloWrapper.tsx

'use client'

import { HttpLink } from '@apollo/client'
import {
  ApolloClient,
  ApolloNextAppProvider,
  InMemoryCache
} from '@apollo/experimental-nextjs-app-support'

function makeClient() {
  const httpLink = new HttpLink({
    uri: process.env['BACKEND'], // <-- !
    fetchOptions: { cache: 'no-store' }
  })

  return new ApolloClient({
    cache: new InMemoryCache(),
    link: httpLink
  })
}

export function ApolloWrapper({ children }: React.PropsWithChildren) {
  return (
    <ApolloNextAppProvider makeClient={makeClient}>
      {children}
    </ApolloNextAppProvider>
  )
}

Solution

  • You can pass it as a prop into your ApolloWrapper component and just write the makeClient function inside the ApolloWrapper function so it can access the prop.