In today's modern web development landscape, GraphQL has become a powerful tool for fetching and manipulating data efficiently. When combined with Payload CMS, a headless content management system, it offers developers a flexible and scalable approach to query content.
Payload CMS supports seamless integration with GraphQL. In this tutorial, I'll cover some of the techniques that I've used to leverage GraphQL more effectively.
In this article I'll be covering the following:
Why use GraphQL with Payload?
Visual Studio Code and GraphQL
How to setup Next.js to support GraphQL
Generate GraphQL schema in Payload CMS.
Write GraphQL queries for nested relationships.
How to test out your GraphQL queries.
When to use GraphQL, REST or Local?
Why use Payload and GraphQL
When I first started using Payload, I felt that REST API's were all I was going to need and as I began to write more complex content, GraphQL seemed more and more like the right tool for the job.
Payload has great support for GraphQL and it provides some benefits:
More flexibility over what data is returned.
Payload generates GraphQL schema and types based on Collection configurations.
Reduces response sizes when multiple relationships and joins are used.
Supports Mutations which are similar to REST Post and Update.
Optimizing GraphQL on Payload
GraphQL has great benefits but writing queries using strings can become hard to manage and make the experience less enjoyable.
I also felt that writing queries using strings didn't take advantage of the strongly typed GraphQL schema that Payload was generating.
I felt a more optimized strategy should include the following:
Utilize Payload's generated GraphQL schema.
Use a Visual Studio plugin for full intellisense.
Avoid writing string based queries since they can be error prone and harder to maintain and write.
Import GraphQL queries directly into pages.
Centralize (or co-locate) queries for better organization rather than completely inline queries.
Lastly, generate all the needed queries and mutations based on the schema without having to write anything unless needed.
So based on these requirements, I'll walk through some of these strategies to make GraphQL awesome on Payload.
Setting up GraphQL schema
In order to import and generate the Payload GraphQL schema, add the following modules to the package.json.
Bash
1pnpm add @payloadcms/graphql graphql-tag -D
Also, add the graphql module as a dependency.
Bash
1pnpm add graphql
Once installed, the generate command can be called using:
Since we're adding a new type of module import, TypeScript is going to complain and show some red squiggly lines in the IDE.
To satsify TypeScript we'll need to add the following type declarations to a *.d.ts file.
In this case I'm just using globals.d.ts but you can name it whatever makes sense or add it to an existing delcaration file.
TypeScript
1declaremodule'*.graphql'{
2import{ DocumentNode }from'graphql'
3const Schema: DocumentNode
4
5export= Schema
6}
7
8declaremodule'*.gql'{
9import{ DocumentNode }from'graphql'
10const Schema: DocumentNode
11
12export= Schema
13}
Now we need to let TypeScript know where it can find the GraphQL declarations, by adding the path to the include array section of the tsconfig.json configuration.
tsconfig
JSON
1{
2 "include": ["global.d.ts"],
3}
Visual Studio Code GraphQL support
In order for the VS Code IDE to know how to diplay and handle GraphQL files types, the GraphQL Foundation provides the following extensions.
GraphQL: Syntax Highlighting
GraphQL: Language Feature Support
These extensions really make writing GraphQL queries and mutations awesome and much less error prone than using strings.
Point to the Payload GraphQL schema
Now we can finally tie everything together and use the actual Payload generated schema.graphql file.
Add the following configuration snippet to your package.json file.
This is where the GraphQL extensions will look for schema definitions and file extensions that need GraphQL support.
package.json
JSON
1{
2 "graphql": {
3 "schema": "schema.graphql",
4 "documents": "**/*.{graphql,gql,js,ts,jsx,tsx}"
5 }
6}
Now all the GraphQL pages will have the following enhancements:
File icon
Intellisense and code completion
Syntax highlighting
Create a Payload Collection
In order to fully demonstrate why GraphQL is an important part of Payload, I'll write a query that accomplishes the following:
Queries a pages Collection
Queries any content blocks defined in the layout builder.
This Content block configuration is quite simple but it will show how to query multiple blocks.
Content block example
TypeScript
1importtype{ Block }from'payload'
2import{
3 lexicalEditor,
4}from'@payloadcms/richtext-lexical'
5
6const Content: Block ={
7 slug:'content',
8 interfaceName:'ContentBlock',
9 fields:[
10{
11 name:'richText',
12 type:'richText',
13 editor:lexicalEditor(),
14 label:false,
15},
16],
17}
18exportdefault Content;
Writing GraphQL queries
Now that the Collection and blocks are available to query, I'll create the following GraphQL queries:
Page.gql: Queries for a page by ID.
PageBySlug.gql: Query for page by slug name, which is based on a where clause.
By holding down the Cmd key, and clicking on any type in VS Code IDE, it will instantly open up the schema.graphql and point to the definition.
As you build your queries now, the VS Code plugin will show intellisense while typing.
Query Page by ID
JavaScript
1// outer is the query name and parameters
2query Page($id:Int!,$draft:Boolean){
3// inner indicates which Payload schema.graphql type to use.
4Page(id: $id,draft: $draft){
5// fields here
6}
7}
Here's the full query for the Page.gql.
Page.gql
TypeScript
1query Page($id: Int!, $draft: Boolean){
2Page(id: $id, draft: $draft){
3 id
4 slug
5 title
6 description
7 layouts {
8... on BannerBlock {
9 id
10 media {
11 id
12 width
13 height
14 alt
15 url
16 filename
17 mimeType
18 thumbnailURL
19}
20 links {
21 link {
22 displayText
23type
24reference{
25 relationTo
26 value {
27... on Page {
28 title
29 description
30 slug
31 id
32}
33}
34}
35 url
36 newTab
37}
38}
39 blockName
40 blockType
41}
42... on ContentBlock {
43 id
44 richText
45 blockName
46 blockType
47}
48}
49}
50}
A couple things to note here:
layouts uses the ... on BannerBlock and ... on ContentBlock notation, which is available from the generated schema because each block defines an interfaceName in it's configuration.
Any relationship fields will have a reference key and can use the ... on <type> notation.
Here's an example of how Payload structures relationship fields.
Example using ... on
TypeScript
1{
2 reference {
3 relationTo
4 value {
5... on <type>{
6// fields here
7}
8}
9}
Using the ... on <type> is very useful when building blocks and relationship queries.
Query Page by slug
Here's the query by slug example. This is useful when you want to find a document page by a more SEO optimized name.
JavaScript
1// outer is the query name and parameters
2query Page($slug:String,$draft:Boolean){
3
4// inner indicates which Payload schema.graphql type to use which is "Pages", not to be confused with "Page" singular.
6// pagination "docs" array which is required for "where" conditions.
7 docs {
8// fields here
9}
10}
11}
This example actually uses a where condition.
JavaScript
1where:{AND:[{slug:{equals: $slug }}]}
Anytime, a GraphQL or REST query uses a where condition, its response will return a PaginatedDocs type which contains a docs array and other pagination details.
So we'll also need to add the docs notation in the actual query.
The query by slug is very similar to the query by id with the only difference being the where and docs syntax changes.
Testing GraphQL queries
When running Payload in development mode, it provides the graphql-playground endpoint.
Bash
1http://localhost:3000/api/graphql-playground
This is an excellent tool to try out your queries to see if they are working and returning the data as you expect.
Here's the GraphQL playground UI for testing.
This tools is already wired up to use the schema.graphql generated by Payload so you can build queries directly inside of this UI interface.
I personally prefer to build my queries in VS Code and then copy/paste them into the playground interface.
Accessing GraphQL from Next.js pages
Here's a couple of Next.js pages that will demonstrate how to use and access Payload's graphql endpoint.
Every GraphQL query is based on a POST request, where the body of the request is the actual query along with variables.
A couple things to note are:
The request header Content-Type needs to be set to application/json.
Make sure any variables are the proper primitive JavaScript type that the GraphQL query expects.
The import statement for each query, will return an AST tree representation of the GraphQL query and needs to be deserialized to a string using the graphql print helper function.
The response objects for each query are a bit different.
Query by ID response format
JSON
1{
2 "data": {
3 "Page": {
4 }
5 }
6}
The reponse for any where conditions will also send the docs array.
Query by slug response format
JSON
1{
2 "data": {
3 "Pages": {
4 "docs": []
5 }
6 }
7}
Next.js page to access by ID
This page will look for the [id] path param in the url.
The last topic worth mentioning is how to generate all the queries and mutations without having to write them by hand.
This is can be useful if you don't need any customizations in your queries. Generated queries will pull all data that is mapped by the schema.
In order to generate the graphql.schema into queries and mutations, we'll need to use a generator.
Bash
1pnpm add gql-generator -D
Let's also add some package.json scripts to orchestrate the process and do the following:
generate the Payload schema
cleanup the generated output folder before re-generating.
generate the schema to the output folder.
All of the generated code will go into the /src/payload/graphql/gen directory, so it does not interfere with any custom queries in the parent directory /src/payload/graphql.
So hopefully this article has offered some improvements to the GraphQL experience when using Payload CMS.
I have found this aproach to using GraphQL very useful for more complex block queries but it can be used for all types of queries.
There is always going to be the case for using an inline string query in GraphQL but having some tools to take the hard part out of writing complex queries is a good thing.
Hope this article has helped to unlock some potential in your projects. Cheers!