Introduction
GraphQL is a powerful query language for APIs that enables you to request exactly the data you need. Combining GraphQL with Next.js 14 allows you to build high-performance, data-driven web applications. This tutorial will guide you through the process of integrating GraphQL with Next.js 14, from setup to advanced usage.
Prerequisites
- Basic knowledge of React and Next.js
- Familiarity with GraphQL concepts
- Node.js and npm/yarn installed
- A code editor like VS Code
Step 1: Setting Up Your Next.js 14 Project
- Create a New Next.js 14 Project
Open your terminal and run:
npx create-next-app@latest my-graphql-app
or
yarn create next-app my-graphql-app
- Navigate to Your Project Directory
cd my-graphql-app
Step 2: Install GraphQL and Apollo Client
- Install Apollo Client and GraphQL Packages
Apollo Client is a widely-used library for integrating GraphQL with React. Install the required packages:
npm install @apollo/client graphql
or
yarn add @apollo/client graphql
- Optional: Install Apollo Server for Local Development
If you need a local GraphQL server for development, you can install Apollo Server:
npm install @apollo/server graphql
or
yarn add @apollo/server graphql
Step 3: Configure Apollo Client
- Create an Apollo Client Instance
Create a new file lib/apolloClient.js
:
// lib/apolloClient.js
import { ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://your-graphql-endpoint/graphql', // Replace with your GraphQL endpoint
cache: new InMemoryCache(),
});
export default client;
- Integrate Apollo Client with Next.js
Wrap your application with Apollo Provider. Update _app.js
:
// pages/_app.js
import '../styles/globals.css';
import { ApolloProvider } from '@apollo/client';
import client from '../lib/apolloClient';
function MyApp({ Component, pageProps }) {
return (
<ApolloProvider client={client}>
<Component {...pageProps} />
</ApolloProvider>
);
}
export default MyApp;
Step 4: Fetch Data with GraphQL
- Define a GraphQL Query
Create a new file queries/getPosts.js
:
// queries/getPosts.js
import { gql } from '@apollo/client';
export const GET_POSTS = gql`
query GetPosts {
posts {
id
title
content
}
}
`;
- Fetch Data in a Page Component
Use the useQuery
hook to fetch data in a Next.js 14 page. Update pages/index.js
:
// pages/index.js
import { useQuery } from '@apollo/client';
import { GET_POSTS } from '../queries/getPosts';
function HomePage() {
const { loading, error, data } = useQuery(GET_POSTS);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return (
<div>
<h1>Blog Posts</h1>
<ul>
{data.posts.map(({ id, title, content }) => (
<li key={id}>
<h2>{title}</h2>
<p>{content}</p>
</li>
))}
</ul>
</div>
);
}
export default HomePage;
Step 5: Advanced Features
- Pagination with GraphQL
Update your GraphQL query to support pagination:
// queries/getPosts.js
export const GET_POSTS = gql`
query GetPosts($limit: Int, $offset: Int) {
posts(limit: $limit, offset: $offset) {
id
title
content
}
}
`;
- Mutations with GraphQL
Define a mutation for adding new posts:
// queries/addPost.js
import { gql } from '@apollo/client';
export const ADD_POST = gql`
mutation AddPost($title: String!, $content: String!) {
addPost(title: $title, content: $content) {
id
title
content
}
}
`;
Use this mutation in a component:
// components/AddPostForm.js
import { useMutation } from '@apollo/client';
import { ADD_POST } from '../queries/addPost';
function AddPostForm() {
const [addPost, { data, loading, error }] = useMutation(ADD_POST);
const handleSubmit = (e) => {
e.preventDefault();
const { title, content } = e.target.elements;
addPost({ variables: { title: title.value, content: content.value } });
};
return (
<form onSubmit={handleSubmit}>
<input name="title" type="text" placeholder="Title" />
<textarea name="content" placeholder="Content"></textarea>
<button type="submit">Add Post</button>
</form>
);
}
export default AddPostForm;
- Server-Side Rendering (SSR) with GraphQL
Fetch data server-side in getServerSideProps
:
// pages/index.js
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
import { GET_POSTS } from '../queries/getPosts';
export async function getServerSideProps() {
const client = new ApolloClient({
uri: 'https://your-graphql-endpoint/graphql',
cache: new InMemoryCache(),
});
const { data } = await client.query({
query: GET_POSTS,
});
return {
props: {
posts: data.posts,
},
};
}
function HomePage({ posts }) {
return (
<div>
<h1>Blog Posts</h1>
<ul>
{posts.map(({ id, title, content }) => (
<li key={id}>
<h2>{title}</h2>
<p>{content}</p>
</li>
))}
</ul>
</div>
);
}
export default HomePage;
Step 6: Testing and Debugging
- Test GraphQL QueriesUse tools like Apollo Client DevTools or GraphiQL to test and debug your GraphQL queries.Image: Screenshot of Apollo Client DevTools.
- Debug Data FetchingCheck for errors and ensure data is correctly fetched and rendered. Use console logs and error boundaries if necessary.Image: Debugging errors in the browser console.
Step 7: Deployment
- Deploy to VercelImage: Vercel deployment process.
- Push your code to a Git repository.
- Connect your repository to Vercel and deploy.
- Other Deployment OptionsEnsure your GraphQL endpoint is accessible and properly configured in production.Image: Deployment configuration.
Conclusion
You’ve now integrated GraphQL with Next.js 14, enabling you to build dynamic, data-driven applications with modern querying capabilities. This tutorial covered setup, querying, mutations, advanced features, and deployment to help you create robust Next.js 14 applications.
Further Reading
About Muhaymin Bin Mehmood
Front-end Developer skilled in the MERN stack, experienced in web and mobile development. Proficient in React.js, Node.js, and Express.js, with a focus on client interactions, sales support, and high-performance applications.