Full Stack Personal Blog 08: Integrating GraphQL on the Frontend
cz2025.06.03 15:02

@apollo/client is a library for interacting with GraphQL backends. It provides a simple API and powerful features, helping developers easily implement data queries, cache management, and state management in frontend frameworks like React.

1. Use @apollo/client Provider in layout

// [locale]/layout.tsx

import { ApolloWrapper } from '@/lib/ApolloProvider'

//... other code

export default async function LocaleLayout({ children, params }: Props) {
  return (
    <html lang={locale} suppressHydrationWarning>
      <body>
        <ThemeProvider
          attribute="class"
          defaultTheme="system"
          enableSystem
          disableTransitionOnChange
        >
          <NextIntlClientProvider>
            <ApolloWrapper>{children}</ApolloWrapper>
            <Toaster />
          </NextIntlClientProvider>
        </ThemeProvider>
      </body>
    </html>
  )
}

2. Define the ApolloWrapper Component

'use client'

import type React from 'react'

import {
  ApolloClient,
  ApolloProvider,
  InMemoryCache,
  HttpLink,
} from '@apollo/client'
import { useMemo } from 'react'

// Function to create a new Apollo Client instance
function createApolloClient() {
  return new ApolloClient({
    cache: new InMemoryCache({}),
    link: new HttpLink({
      uri: '/api/graphql',
      // You can add additional options here like headers, credentials, etc.
    }),
    defaultOptions: {
      watchQuery: {
        fetchPolicy: 'cache-and-network',
      },
    },
  })
}

// Provider component that wraps your app and makes Apollo Client available
export function ApolloWrapper({ children }: { children: React.ReactNode }) {
  const client = useMemo(() => createApolloClient(), [])

  return <ApolloProvider client={client}>{children}</ApolloProvider>
}

3. Query a Single Post

In client components, you can use useQuery to fetch data, or use useApolloClient() to get the apolloClient and then use apolloClient.query() to query data.

import { gql, useMutation, useQuery } from '@apollo/client'
//...
const GET_POST = gql`
  query GetPost($id: ID!) {
    post(id: $id) {
      id
      title
      summary
      content
    }
  }
`
const id = searchParams.get('id')
const {
  data: postDsata1,
  loading,
  error,
} = useQuery(GET_POST, {
  variables: {
    id,
  },
})

const { data: postData2 } = await apolloClient.query({
  query: GET_POST,
  variables: {
    id,
  },
})

4. Use apolloClient in Server Components

Define a server-side apolloClient instance

// lib/apolloServerClient.ts
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client'

export function getApolloServerClient() {
  const httpLink = new HttpLink({
    uri: process.env.GRAPHQL_ENDPOINT || 'http://localhost:3000/api/graphql',
  })

  return new ApolloClient({
    cache: new InMemoryCache(),
    link: httpLink,
    // Important for SSR to avoid leaking data between requests
    ssrMode: true,
  })
}

Use it in server components, for example in the post detail page.tsx

Next.js will prefer static rendering at build time, so here we force dynamic rendering with export const dynamic = 'force-dynamic' and always fetch the latest data with export const revalidate = 0.

import { getApolloServerClient } from '@/lib/apolloServerClient'
import { gql } from '@apollo/client'
import { format } from 'date-fns'
import { Locale } from 'next-intl'
import { setRequestLocale } from 'next-intl/server'

export const dynamic = 'force-dynamic'
export const revalidate = 0

type Props = {
  params: Promise<{ locale: Locale; id: string }>
}

export default async function PagePostsDetail({ params }: Props) {
  const { locale, id } = await params
  setRequestLocale(locale)


  const { data } = await getApolloServerClient().query({
    query: gql`
      query GetPost($id: ID!, $userId: ID) {
        post(id: $id) {
          id
          title
          summary
          content
          createdAt
          updatedAt
          createdBy {
            id
            nickname
          }
        }
      }
    `,
    variables: {
      id,
    },
  })

  return (
    <div className="page-wrapper py-6">
      <div className="">
        <div key={data.post.id} className="relative flex flex-col gap-4">
          <div className="text-xl font-bold">{data.post.title}</div>
          <div className="text-muted-foreground flex items-center gap-2 text-sm">
            <span>{data.post.createdBy.nickname}</span>
            <span>{format(data.post.createdAt, 'yyyy.MM.dd HH:mm')}</span>
          </div>

      </div>
    </div>
  )
}

Comments