Connecting Payload to NextJS frontend using the GraphQL query generator based on Schema

default discord avatar
6 months ago

My project is based on the PayloadCMS site and Server

These 2 repos



I need to generate the frontend GraphQL queries from the Schema generated in the backend as I haven’t been able to get my queries to work. @noheadphones do let me know if you can help. I haven’t added any new packages other than graphql-codegen and everything is running versions as per package.json

  • default discord avatar
    6 months ago

    I'll try to see if I can help...

    my package.json deps:


    dev deps:


    in the root dir i have a codegen.ts file with

    import type { CodegenConfig } from '@graphql-codegen/cli'
    const config: CodegenConfig = {
      overwrite: true,
      schema: '<api url with `/api/graph` ending>',
      documents: 'graphql/**/*.graphql',
      generates: {
        'graphql/generated/client.ts': {
          plugins: ['typescript', 'typescript-operations', 'typescript-react-query'],
          config: {
            exposeQueryKeys: true,
            exposeFetcher: true,
            withHooks: true,
            dedupeFragments: true,
            fetcher: {
              endpoint: '<api url with `/api/graph` ending>',
              fetchParams: {
                headers: {
                  'content-type': 'application/json',
    export default config

    package.json has this script as well

    "gen:graphql": "graphql-codegen --config codegen.ts"

    then i have a graphql folder, inside it theres a generated folder (empty initially)

    then a queries folder where i put my queries in files


    query GetGlobal {
      Global {

    a named query and inside a valid query to my API

    i have a query client ts file

    import { QueryClient } from '@tanstack/react-query'
    const queryClient = new QueryClient()
    export default queryClient

    i then import that


    in _app.tsx and wrap my page components with it

    import queryClient from '@utilities/queryClient'
    import { QueryClientProvider } from '@tanstack/react-query'
    <QueryClientProvider client={queryClient}>
    //... add your children here, eg. the default <Component 

    lastly just run

    yarn gen:graphql

    and if you have a query you should get a successful output

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!


Connect with the Payload Community on Discord



Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.