Frequently Asked Questions

Getting Started & Technical Setup

How do I set up a Hygraph GraphQL API for my Next.js project?

To set up a Hygraph GraphQL API, create a Hygraph project and define your schema (e.g., models like NextUser and Post). Once your schema is ready, you can use the Hygraph API playground to write queries and mutations. For a step-by-step guide, see the Hygraph Quickstart.

What environment variables are needed to connect Next.js to Hygraph?

You need to set NEXT_PUBLIC_HYGRAPH_URL and NEXT_PUBLIC_HYGRAPH_PERMANENTAUTH_TOKEN in your .env.local file to connect your Next.js app to Hygraph's API.

What are the main ways to fetch GraphQL data in a Next.js app using Hygraph?

You can fetch GraphQL data using native fetch, axios, apollo-client, or graphql-request. Each method has its own advantages in terms of simplicity, caching, and advanced features. See the full code examples in the GitHub repository.

How do I authenticate API requests to Hygraph from my Next.js app?

Authentication is handled via a Bearer token in the Authorization header. Set HYGRAPH_PERMANENTAUTH_TOKEN in your environment and include it in your API requests.

Can I use Apollo Client with Hygraph in Next.js?

Yes, Apollo Client is fully supported and recommended for enterprise applications. It provides features like client-side caching, polling, refetching, and GraphQL subscriptions. See the Apollo Client documentation for details.

Is there a quick way to test my GraphQL queries before integrating with Next.js?

Yes, you can use the Hygraph API playground to write and test queries and mutations interactively before integrating them into your Next.js app.

What is the recommended schema setup for user-post relationships in Hygraph?

A common schema setup is to have a NextUser model and a Post model, with a one-to-many relationship (one user can have multiple posts).

Where can I find working code examples for integrating Hygraph with Next.js?

Working code examples for fetch, axios, apollo-client, and graphql-request are available in the GitHub repository linked from the original blog post.

What are the prerequisites for following Hygraph's Next.js integration guides?

Basic understanding of React and Next.js is recommended. If you're new to these frameworks, refer to Hygraph's guides on Next.js vs React and Routing in React.

How do I manage loading and error states when fetching data from Hygraph?

When using fetch or axios, you need to manually manage loading and error states. Apollo Client and graphql-request provide built-in support for handling these states more efficiently.

Can I use Hygraph with other JavaScript frameworks besides Next.js?

Yes, Hygraph can be integrated with other frameworks such as React, Vue.js, and more. See Hygraph's blog for guides on Vue.js CMS integration.

What are the advantages of using GraphQL over REST APIs with Hygraph?

GraphQL reduces frontend coupling, efficiently manages data from multiple sources, and provides a better developer experience compared to REST APIs. For a detailed comparison, see GraphQL vs REST APIs.

Does Hygraph support real-time data updates?

Yes, Hygraph supports GraphQL subscriptions for real-time events. Learn more about subscriptions in the Hygraph GraphQL Subscriptions Guide.

How do I handle client-side caching with Hygraph?

Apollo Client provides robust client-side caching for GraphQL queries. For simpler use cases, graphql-request offers lightweight caching options.

Where can I find more resources and tutorials for Hygraph and Next.js?

Visit the Hygraph Blog and Documentation for tutorials, guides, and best practices.

What is the difference between Next.js and React when using Hygraph?

Next.js is a framework built on top of React that adds features like server-side rendering and routing. Hygraph can be used with both; see this guide for more details.

How do I manage relationships between models in Hygraph?

Hygraph allows you to define relationships such as one-to-many between models (e.g., one user can have multiple posts) directly in the schema editor.

Can I use Hygraph for both small and enterprise-level projects?

Yes, Hygraph is suitable for both small projects and large-scale enterprise applications, offering flexible pricing and advanced features for scalability.

What are some recommended GraphQL clients for JavaScript?

Recommended clients include fetch, axios, apollo-client, and graphql-request. For more options, see Top 5 JavaScript GraphQL Clients.

How do I use Hygraph with dynamic routing in Next.js?

Refer to Hygraph's guide on Dynamic Routing in Next.js for best practices and code examples.

Features & Capabilities

What key features does Hygraph offer for content management?

Hygraph provides a GraphQL-native architecture, content federation, scalability, enterprise-grade security, user-friendly tools, Smart Edge Cache, localization, and asset management. These features enable efficient content delivery and management for modern businesses. Learn more.

Does Hygraph support integrations with other platforms?

Yes, Hygraph supports integrations with Digital Asset Management systems (Aprimo, AWS S3, Bynder, Cloudinary, Imgix, Mux, Scaleflex Filerobot), Adminix, Plasmic, and custom integrations via SDKs and APIs. Explore the Hygraph Marketplace for more options.

What APIs does Hygraph provide?

Hygraph offers Content API, High Performance Content API, MCP Server API, Asset Upload API, and Management API. Each serves different use cases for querying, mutating, managing, and uploading content. See the API Reference Documentation for details.

How does Hygraph ensure high performance for content delivery?

Hygraph's high-performance endpoints are designed for low latency and high read-throughput. The platform actively measures and optimizes GraphQL API performance, with best practices available in the GraphQL Report 2024.

What technical documentation is available for Hygraph?

Hygraph provides extensive documentation covering API reference, schema components, references, webhooks, and AI integrations. Access all resources at the Hygraph Documentation page.

Pricing & Plans

What pricing plans does Hygraph offer?

Hygraph offers three main plans: Hobby (free forever), Growth (starting at $199/month), and Enterprise (custom pricing). Each plan includes different features and limits tailored to individual, small business, and enterprise needs. See pricing details.

What features are included in the Hobby plan?

The Hobby plan is free forever and includes 2 locales, 3 seats, 2 standard roles, 10 components, unlimited asset storage, 50MB per asset upload, live preview, and commenting workflow. Sign up here.

What does the Growth plan cost and include?

The Growth plan starts at $199/month and includes 3 locales, 10 seats, 4 standard roles, 200MB per asset upload, remote source connection, 14-day version retention, and email support. Get started.

What features are available in the Enterprise plan?

The Enterprise plan offers custom limits, scheduled publishing, dedicated infrastructure, global CDN, advanced security, SSO, multitenancy, instant backup recovery, custom workflows, and dedicated support. Try for 30 days or request a demo.

Security & Compliance

What security certifications does Hygraph have?

Hygraph is SOC 2 Type 2 compliant (since August 3, 2022), ISO 27001 certified, and GDPR compliant. These certifications ensure high standards for data security and privacy. Learn more.

How does Hygraph protect user data?

Hygraph encrypts data at rest and in transit, provides granular permissions, audit logs, SSO integrations, regular backups, and options for dedicated hosting in multiple regions. See security features.

Use Cases & Benefits

Who can benefit from using Hygraph?

Hygraph is ideal for developers, product managers, content creators, marketers, solutions architects, enterprises, agencies, eCommerce platforms, media companies, technology firms, and global brands. See case studies.

What industries use Hygraph?

Industries represented include SaaS, marketplace, education technology, media, healthcare, consumer goods, automotive, technology, fintech, travel, food & beverage, eCommerce, agency, gaming, events, government, consumer electronics, engineering, and construction. Explore case studies.

What business impact can Hygraph deliver?

Hygraph improves operational efficiency, accelerates speed-to-market, reduces costs, enhances scalability, and increases customer engagement. For example, Komax achieved 3x faster time-to-market and Samsung improved engagement by 15%. See more.

Can you share specific customer success stories?

Yes. Samsung built a scalable API-first app, Dr. Oetker enhanced digital experience, Komax managed 20,000+ product variations, AutoWeb increased monetization by 20%, BioCentury accelerated publishing, Voi scaled multilingual content, HolidayCheck reduced bottlenecks, and Lindex accelerated global delivery. Read case studies.

What pain points does Hygraph solve for customers?

Hygraph addresses developer dependency, legacy tech stacks, content inconsistency, workflow challenges, high operational costs, slow speed-to-market, scalability issues, schema evolution complexity, integration difficulties, performance bottlenecks, and localization challenges. See examples.

How does Hygraph differentiate itself from other CMS platforms?

Hygraph is the first GraphQL-native Headless CMS, offers content federation, enterprise-grade features, user-friendly tools, Smart Edge Cache, and proven ROI. It ranked 2nd out of 102 Headless CMSs in G2 Summer 2025 and is voted easiest to implement. See report.

What feedback have customers given about Hygraph's ease of use?

Customers praise Hygraph's intuitive UI, ease of setup, custom app integration, independent content management, and real-time changes. Some note it can be complex for less technical users. See feedback.

How long does it take to implement Hygraph?

Implementation time varies. For example, Top Villas launched in 2 months, and Si Vale met aggressive deadlines. Hygraph offers a structured onboarding process and extensive training resources. See case study.

What support resources are available for Hygraph users?

Hygraph provides webinars, live streams, how-to videos, documentation, and a community Slack channel for support and guidance. Access documentation or join Slack.

Who are some of Hygraph's notable customers?

Notable customers include Samsung, Dr. Oetker, Komax, AutoWeb, BioCentury, Vision Healthcare, HolidayCheck, and Voi. See customer stories.

Introducing Click to Edit

How to fetch GraphQL data in Next.js

Both GraphQL and Next.js are gaining popularity in the recent years. Let's go over how to fetch the data from GraphQL APIs in your Next.js app.
Aagam Vadecha

Last updated by Aagam 

Nov 04, 2024

Originally written by Aagam

How to fetch GraphQL data in Next.js

#What is GraphQL

GraphQL is a query language and a runtime to efficiently write and manage backend APIs. It is designed to reduce overheads and frontend couplings that come with REST APIs, efficiently manage data from multiple sources and provide a great developer experience. It was developed by Facebook in 2012 to use internally and made public in 2015. It allows querying, mutating data, and also publishing/subscribing to real-time events. Due to numerous advantages, it has become a great alternative to REST APIs, you can read about the precise differences here. Along with us a lot of other reputed software firms also use it in production.

#Ways to fetch data from a GraphQL Server

When we want to call a backend Graphql API server to query or mutate some data there are many clients that we can use from the frontend. It really depends on the use case and the scope of the project. In this article, we will learn by examples how to query data from the frontend using different clients. We will start from the bottom with most basic methods like a simple fetch API call to all the way towards using full-fledged clients like apollo-client

Server Side Setup

For this example, first we will need a server side API that the clients can invoke. We will use the Hygraph platform as it will give us a ready to use GraphQL API within a few minutes. If you are new to Hygraph, please refer to this 5 minute guide to understand the fundamentals. You can create a Hygraph project, create your schema. We can do a small schema setup wherein we have one model named NextUser and another model named Post. The relationship is one user can have multiple posts.

Once you have the project and schema defined, your API is ready to use. Querying user details on the Hygraph API playground is quite easy, once your schema is in place, write your query/mutation and give the variables, then hit the play button, it will give you the results.

Hygraph API Playground showing a 'GetNextUserByEmail' GraphQL query for a Next.js app, with variables and the JSON result

Here we are sending a query to get details of a user, we pass email as a variable to this query. You can do a similar setup on Hygraph within few minutes, and in case you already have any other GraphQL API server running you’re good to go. On the frontend side, we will be using a Next.js application.

Understanding of React and Next.js is a prerequisite for this article. In case you are unfamiliar with these, you can get started checkout these articles for understanding React and Next.js better.

The code snippets ahead will contain the core parts, in case you’re stuck somewhere, please find the final working Next.js app with all different clients here. If you want to clone and work with this repository, please create a .env.local file, then add HYGRAPH_URL and HYGRAPH_PERMANENTAUTH_TOKEN environment variables for your setup.

.env.local

NEXT_PUBLIC_HYGRAPH_URL=add-your-hygraph-api-url
NEXT_PUBLIC_HYGRAPH_PERMANENTAUTH_TOKEN=add-your-hygraph-token

If you’re building a small application, or if your application has only few Graphql API calls then you might not need a dedicated Graphql client, and using an existing package like fetch / axios/ request to make those API calls might do the job. Okay, before getting started with code for different clients let us set up the constants file, we will define our Hygraph server connection details and one GraphQL query that we will send to the server using different clients.

lib/constants.js

export const HYGRAPH_URL = process.env.NEXT_PUBLIC_HYGRAPH_URL;
export const HYGRAPH_PERMANENTAUTH_TOKEN = process.env.NEXT_PUBLIC_HYGRAPH_PERMANENTAUTH_TOKEN;
export const GRAPHQL_QUERY = `query getNextUserByEmail($email:String!){
nextUser(where:{email:$email}){
firstname
lastname
email
posts{
title
}
}
}`;

Fetch

At its very base an API call to a GraphQL server is still an HTTP network call, this means that we can use Curl / Fetch with the correct parameters and payload to make the API call.

Here is an API request using JavaScript’s native fetch. We have used tailwind for styling feel free to use any UI/CSS framework. (Full React component here) .

import { React, useState } from 'react';
import { HYGRAPH_URL, HYGRAPH_PERMANENTAUTH_TOKEN, GRAPHQL_QUERY } from '../lib/constants';
import { UserDetail } from '../components/UserDetail';
export default function Fetch() {
const [email, setEmail] = useState('');
const [userDetails, setUserDetails] = useState({});
const [isLoading, setIsLoading] = useState(false);
const getUserDetailByFetchAPICall = async () => {
try {
if (!email) {
return;
}
setIsLoading(true);
const headers = {
'content-type': 'application/json',
Authorization: `Bearer ${HYGRAPH_PERMANENTAUTH_TOKEN}`,
};
const requestBody = {
query: GRAPHQL_QUERY,
variables: { email },
};
const options = {
method: 'POST',
headers,
body: JSON.stringify(requestBody),
};
const response = await (await fetch(HYGRAPH_URL, options)).json();
console.log('RESPONSE FROM FETCH REQUEST', response?.data);
setUserDetails(response?.data?.nextUser ?? {});
} catch (err) {
console.log('ERROR DURING FETCH REQUEST', err);
} finally {
setIsLoading(false);
}
};
return (
<div className="flex w-full h-3/4">
<div className="flex flex-col justify-evenly rounded-lg shadow-xl w-1/2 p-4 m-4 bg-gray-900">
<h2 className="text-center text-white font-medium text-2xl mb-4 self-start ">
FETCH CALL
</h2>
<input
className="border-2 outline-none p-2 rounded-md"
type="email"
placeholder="Email"
value={email}
onChange={(e) => {
setEmail(e.target.value);
}}
/>
<button
className="
flex justify-center
p-2 rounded-md
bg-gray-800 text-white hover:bg-gray-700 w-1/2 self-center"
onClick={() => getUserDetailByFetchAPICall()}
>
{isLoading ? (
<div className="mr-2 w-5 h-5 border-l-2 rounded-full animate-spin" />
) : null}
<span>FETCH</span>
</button>
</div>
<UserDetail user={userDetails} />
</div>
);
}

Here we have used the fetch method to our Hygraph server which is a POST call, the graphql query/mutation and respective variables are passed as a part of the request body. And for authentication, we have passed a standard Authorization header with a bearer token.

Axios

The Axios implementation is quite similar to fetch, Axios is a bit more high level and developer friendly library and many code bases might already be using Axios. Here’s what an axios call would look like. (Full component here)

import { React, useState } from 'react';
import { HYGRAPH_URL, HYGRAPH_PERMANENTAUTH_TOKEN, GRAPHQL_QUERY } from '../lib/constants';
import { UserDetail } from '../components/UserDetail';
import axios from 'axios';
export default function Fetch() {
const [email, setEmail] = useState('');
const [userDetails, setUserDetails] = useState({});
const [isLoading, setIsLoading] = useState(false);
const getUserDetailByAxiosAPICall = async () => {
try {
if (!email) {
return;
}
setIsLoading(true);
const headers = {
'content-type': 'application/json',
'Authorization': `Bearer ${HYGRAPH_PERMANENTAUTH_TOKEN}`
};
const requestBody = {
query: GRAPHQL_QUERY,
variables: { email }
};
const options = {
method: 'POST',
url: HYGRAPH_URL,
headers,
data: requestBody
};
const response = await axios(options);
console.log('RESPONSE FROM AXIOS REQUEST', response.data);
setUserDetails(response?.data?.data?.nextUser ?? {});
}
catch (err) {
console.log('ERROR DURING AXIOS REQUEST', err);
}
finally {
setIsLoading(false);
}
};
return (
// ... JSX Markup
);
}

UI from a Next.js and GraphQL blog, showing an 'Axios Call' tab for data fetching compared to Apollo Client

With libraries like fetch or axios you will manually have to manage loading states for all the queries and mutations, write separate code for error handling as well. This might become an overhead when the number of requests scale. Also advanced features like client side caching, graphql subscriptions based on websocket protocols, refetching queries, cannot be used in a straight-forward manner.

Apollo Client

Apollo client is a robust, production-ready, and mature client for graphql on the web. It is the most popular graphql client and has support for major frontend frameworks. It enables us to use powerful features like polling & refetching data, simplifies managing and configuring client-side cache, helps to use graphql fragments, and also supports subscriptions. If you are building a full-blown enterprise application that relies heavily on GraphQL, you might want to consider using the Apollo client.

Let’s see how to configure the Apollo client in a Next.js app. First, make a file that initializes and exports the Apollo client.

lib/apolloClient.js

import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';
import { HYGRAPH_URL, HYGRAPH_PERMANENTAUTH_TOKEN } from '../lib/constants';
import { setContext } from '@apollo/client/link/context';
const httpLink = createHttpLink({
uri: HYGRAPH_URL,
});
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
authorization: `Bearer ${HYGRAPH_PERMANENTAUTH_TOKEN}`
}
};
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
export default client;

Next.js is a hybrid framework, so if you are using static or server rendered pages you can directly import and use this client right away. For client side rendering we can provide the client via ApolloProvider.

Import this client in your _app.jsand then use ApolloProvider to provide this client to your components down the tree.

pages/_app.js

import React from 'react';
import Layout from '../components/Layout';
import '../styles/globals.css';
import client from '../lib/apolloClient';
import { ApolloProvider } from '@apollo/client';
export default function MyApp({ Component, pageProps }) {
return (
<Layout>
<ApolloProvider client={client}>
<Component {...pageProps} />
</ApolloProvider>
</Layout>
);
}

Now, simply use hooks provided by apolloClient like useQuery, useLazyQuery, etc in your component something like this. (Full component here)

import { React, useState } from 'react';
import { UserDetail } from '../components/UserDetail';
import { gql, useLazyQuery } from '@apollo/client';
import { GRAPHQL_QUERY } from '../lib/constants';
export default function ApolloClient() {
const query = gql(GRAPHQL_QUERY);
const [email, setEmail] = useState('');
const [getUserDetailByApolloClientAPICall, { loading, error, data }] = useLazyQuery(query, { variables: { email } });
if (error) return <div> Error ! </div>;
return (
// ... JSX Markup
);
}

ApolloClient.png

We don’t have to manage the loading, error states manually for all queries, also there is a common client that can be used by any component unlike axios / fetch where all API calls need to send the payload to the url with the authentication header. The advanced features that Apollo Client supports are beyond the scope of this article but they are worth looking into.

GraphQL Request

GraphQL Request is another lightweight graphql client with good features and ease of use. It can be considered as a GraphQL client meant to provide ease of use and can be put above a normal fetch or axios API call, but it does not have as many advanced features like cache management as the apollo client, so functionality wise it lies somewhere between the axios and apollo client.

Here’s how to use it.

import { React, useState } from 'react';
import { HYGRAPH_URL, HYGRAPH_PERMANENTAUTH_TOKEN, GRAPHQL_QUERY } from '../lib/constants';
import { GraphQLClient, gql } from 'graphql-request';
import { UserDetail } from '../components/UserDetail';
const client = new GraphQLClient(HYGRAPH_URL, {
headers: {
Authorization: `Bearer ${HYGRAPH_PERMANENTAUTH_TOKEN}`,
},
});
const query = gql`${GRAPHQL_QUERY}`;
export default function GraphQLRequest() {
const [email, setEmail] = useState('');
const [userDetails, setUserDetails] = useState({});
const [isLoading, setIsLoading] = useState(false);
const getUserDetailByGraphQLRequestAPICall = async () => {
try {
setIsLoading(true);
const variables = { email };
const response = await client.request(query, variables);
console.log('RESPONSE FROM GRAPHQL-REQUEST API CALL', response);
if (response?.nextUser) {
setUserDetails(response.nextUser);
}
}
catch (err) {
console.log('ERROR FROM GRAPHQL-REQUEST API CALL', err);
}
finally {
setIsLoading(false);
}
};
return (
// ... JSX Markup
);
}

GraphQLRequest.png

#Conclusion

In this article, we had an introduction to GraphQL and learned how to setup a Hygraph GraphQL API within minutes, then we went through different client side options like Fetch, Axios, Apollo Client, and GraphQL Request to make GraphQL requests to our Hygraph API server with code examples. You can also take a look here to check out more GraphQL clients and if you are new to graphql we recommend checking out these awesome tools that are quite popular in the graphql community.

Blog Authors

Share with others

Sign up for our newsletter!

Be the first to know about releases and industry news and insights.