In this blog, we are about to explore the introduction of GraphQL CodeGen and its advantages.
After that, we will move toward the intricate configuration of GraphQL Codegen with apollo-client for our next js project.
Also, look no further and grab the opportunity to start your projects with the certified Magento 2 development company.
Introduction of CodeGen
GraphQL Codegen is a tool that simplifies working with GraphQL APIs in TypeScript by automatically generating types and queries based on our schema.
It reduces the amount of boilerplate code you have to write and makes it easier to work with GraphQL APIs.
To use it, we would define our schema in a .graphql or .graphqls file and then use a codegen plugin to generate the TypeScript types and queries which we are about to cover deeper.
The generated code includes interfaces for your GraphQL types and functions for making queries and mutations.
Advantages of CodeGen –
1. Automated Code Generation:
GraphQL Code Generator simplifies your development process by automatically creating typed queries, mutations, and subscriptions.
These are created for front-end libraries like React, Next.js, and other various frameworks & libraries.
Whether you use Apollo Client, URQL, or React Query, it ensures consistent and type-safe code.
2. Type Safety and Consistency:
Manually managing GraphQL operation types can lead to issues like outdated typings and typos.
By automating this process, GraphQL Code Generator enhances the stability of your stack and improves the developer experience.
3. Efficient Workflow:
Without GraphQL Code Generator, developers often write repetitive code for queries and mutations.
By analyzing your GraphQL schema, the tool generates fully typed code, eliminating the need for manual TypeScript type maintenance and enhancing your development workflow.
4. Broad Language Support:
While GraphQL Code Generator supports TypeScript by default, it can also generate code for other languages.
It automates common data fetching practices and improves type safety in code that would typically be manually written.
Configuration Apollo client with Graphql Code-Gen –
Our main focus will be on configuring GraphQL Codegen with Apollo Client in a Next.js environment.
To set up, we can follow this setup next js project blog that covers all about the setup.
We assume you are familiar with setting up Apollo Client in a Next.js project. If not, you can refer to the Apollo client configuration with the Next.js blog for more insights.
Let’s go with the steps to configure Apollo Client with GraphQL Codegen in a Next.js application.
Step 1: Start by creating a new Next.js application:
npx create-next-app@latest cd next_codegen
Step 2: Installing Dependencies
Install the necessary dependencies for Apollo Client, GraphQL, and GraphQL Codegen.
npm install @apollo/client graphql @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo
Step 3: Initialising Apollo Client
Initialize Apollo Client in your Next.js application. Create a new file named client.ts in the lib directory.
// lib/client.ts import { ApolloClient, InMemoryCache } from '@apollo/client'; // change the schema's uri with our graphql server end point export const client = new ApolloClient({ uri: 'https://magento-endpoint/graphql', cache: new InMemoryCache(), });
Step 4: Integrating with Next.js
In your Next.js app, wrap your pages with the Apollo Provider.
// pages/_app.js import "@/styles/globals.css"; import type { AppProps } from "next/app"; import { client } from '@/lib/client'; import { ApolloProvider } from '@apollo/client'; export default function App({ Component, pageProps }: AppProps) { return ( <ApolloProvider client={client}> <Component {...pageProps} /> </ApolloProvider> ); }
Step 5: Configuring GraphQL Codegen
Create a codegen.ts file in the root directory of your project and define the configuration with our graphql server endpoint for GraphQL Codegen:
// codegen.ts // change the schema's uri with our graphql server end point module.exports = { overwrite: true, schema:'https://magento-endpoint/graphql', documents: [ 'graphql/**/*.graphql', ], generates: { 'generated/graphql.tsx': { plugins: [ 'typescript', 'typescript-operations', 'typescript-react-apollo' ] } } };
Now we need to create queries and mutations in our graphql folder as configured in our codegen.ts.
Here graphql directory holds all queries and mutations files, here our products.query.graphql will be there for fetching the products list, likewise, we can also create a mutation in the same directory.
// graphql/products.query.graphql query Products( $filters: ProductAttributeFilterInput $search: String $pageSize: Int = 20 $currentPage: Int = 1 ) { products( filter: $filters pageSize: $pageSize currentPage: $currentPage search: $search ) { aggregations { attribute_code label options { count label value } } total_count page_info { current_page page_size total_pages } items { uid name url_key sku new_from_date only_x_left_in_stock rating_summary description { html } thumbnail { disabled label position url } short_description { html } price_range { maximum_price { discount { amount_off percent_off } final_price { currency value } regular_price { currency value } } } } } }
Step 6: Generating Queries and Mutations
To generate TypeScript types and React Apollo hooks from your GraphQL queries and mutations. we use this below this command.
npx graphql-codegen --config codegen.ts
But instead of using this command, we can configure this command into package.json file, Here we have added graphql-codegen –config codegen.ts , this command will execute while we make the build using npm run build or whenever we run npm run generate.
"scripts": { "dev": "next dev", "build": "next build && graphql-codegen --config codegen.ts", "start": "next start", "lint": "next lint", "generate":"graphql-codegen --config codegen.ts" },
After hitting the command, our hooks will be generated into a generated directory with graphql.tsx contains a bunch of hooks.
However, we can also change where we have to generate this directory, it is generated as our configurated codegen.ts file.
// codegen.ts // change the schema's uri with our graphql server end point module.exports = { overwrite: true, schema:'https://magento-endpoint/graphql', documents: [ ... ], generates: { ... } };
Step 7: Example Usage
Now, let’s demonstrate how to use the generated hooks for query data in your project.
For instance, in your pages/index.js.
import { useProductsLazyQuery } from '@/generated/graphql'; import { useEffect } from 'react'; export default function Home() { const [getPosProduct,{ data, loading, error } ]= useProductsLazyQuery(); useEffect(() => { getPosProduct({ variables: { search: '', pageSize: 20, currentPage: 1 }, }); }, []); console.log(data, ' fetched data ') if (loading) return <p>Loading...</p> if (error?.message) return <p>{error.message}</p> else { return ( <> <main className={''}> {/* populate the product list */} </main> </> ); } }
Now we can see our data in console.log
Finally, our project structure will look like this.
Conclusion
In conclusion, combining GraphQL code generation with Apollo Client and Next.js can significantly improve the development process.
By utilizing code generation, we can ensure type safety and reduce manual errors in your GraphQL queries and mutations.
Apollo Client provides a robust set of tools for working with GraphQL APIs, including caching and real-time updates, while Next.js offers server-side rendering and performance optimizations.
Together, these technologies create a powerful stack for building efficient and scalable web applications with GraphQL.
You can also have a look at our Magento 2 extensions already crafted by certified Adobe Commerce Developers.
For a personalized experience, hire Magento developers who can dedicatedly work on your customised e-commerce projects.
Current Product Version - 1
Supported Framework Version - 1
Be the first to comment.