/ astro-integrations / How to Use Hygraph with Astro: Complete Guide
astro-integrations 4 min read

How to Use Hygraph with Astro: Complete Guide

Step-by-step guide to integrating Hygraph with your Astro website.

Hygraph (formerly GraphCMS) is a GraphQL-native headless CMS that stands out for its content federation feature, which lets you combine data from multiple sources into a single GraphQL API. If you are already comfortable with GraphQL or you need to pull content from different backends into one unified schema, Hygraph is worth a serious look. With Astro, you can query Hygraph at build time and generate blazing-fast static pages from your CMS content.

Since Hygraph uses GraphQL as its primary interface, the integration relies on standard GraphQL queries rather than a proprietary SDK. This keeps things flexible and portable.

Prerequisites

  • Node.js 18+
  • An Astro project (npm create astro@latest)
  • A Hygraph account with a project created (free tier available, paid plans start at $199/mo)
  • Basic familiarity with GraphQL queries

Installation

Install a lightweight GraphQL client. You do not need Apollo or anything heavy for build-time fetching:

npm install graphql-request graphql

Configuration

Create a reusable Hygraph client:

// src/lib/hygraph.ts
import { GraphQLClient } from "graphql-request";

const hygraph = new GraphQLClient(import.meta.env.HYGRAPH_ENDPOINT, {
  headers: {
    Authorization: `Bearer ${import.meta.env.HYGRAPH_TOKEN}`,
  },
});

export default hygraph;

Add your Hygraph credentials to .env:

HYGRAPH_ENDPOINT=https://api-us-east-1.hygraph.com/v2/your-project-id/master
HYGRAPH_TOKEN=your-permanent-auth-token

Find these in your Hygraph project under Settings > API Access. The endpoint URL includes your region and project ID. Create a Permanent Auth Token with read access for your content stage.

Set up your content model in Hygraph's dashboard. For a blog, create a "Post" model with fields: Title (Single line text), Slug (Single line text), Excerpt (Multi line text), Content (Rich text), Cover Image (Asset picker), and Published At (Date and time).

Basic Usage

Query posts from Hygraph and render them in Astro:

---
// src/pages/blog/index.astro
import hygraph from "../../lib/hygraph";
import { gql } from "graphql-request";
import BaseLayout from "../../layouts/BaseLayout.astro";

const { posts } = await hygraph.request(gql`
  query Posts {
    posts(orderBy: publishedAt_DESC) {
      id
      title
      slug
      excerpt
      publishedAt
      coverImage {
        url
      }
    }
  }
`);
---

<BaseLayout title="Blog">
  <h1>Blog</h1>
  {posts.map((post) => (
    <article>
      <a href={`/blog/${post.slug}`}>
        {post.coverImage && (
          <img src={post.coverImage.url} alt={post.title} loading="lazy" />
        )}
        <h2>{post.title}</h2>
        <p>{post.excerpt}</p>
        <time>{new Date(post.publishedAt).toLocaleDateString()}</time>
      </a>
    </article>
  ))}
</BaseLayout>

For individual post pages with dynamic routes:

---
// src/pages/blog/[slug].astro
import hygraph from "../../lib/hygraph";
import { gql } from "graphql-request";
import BaseLayout from "../../layouts/BaseLayout.astro";

export async function getStaticPaths() {
  const { posts } = await hygraph.request(gql`
    query PostSlugs {
      posts {
        slug
      }
    }
  `);

  return posts.map((post) => ({
    params: { slug: post.slug },
  }));
}

const { slug } = Astro.params;

const { post } = await hygraph.request(gql`
  query Post($slug: String!) {
    post(where: { slug: $slug }) {
      title
      content {
        html
      }
      coverImage {
        url
      }
      publishedAt
    }
  }
`, { slug });
---

<BaseLayout title={post.title}>
  <article>
    <h1>{post.title}</h1>
    <time>{new Date(post.publishedAt).toLocaleDateString()}</time>
    {post.coverImage && (
      <img src={post.coverImage.url} alt={post.title} />
    )}
    <div set:html={post.content.html} />
  </article>
</BaseLayout>

Production Tips

  1. Use Hygraph's image transformations. Append transformation parameters to asset URLs for automatic resizing and format conversion. For example, add ?width=800&height=400&fit=crop to any asset URL for on-the-fly optimization without a separate image service.

  • Leverage content stages. Hygraph supports Draft and Published stages. Query the Draft stage for preview environments and Published for production. Use different auth tokens for each stage to keep things secure.

  • Set up webhooks for rebuilds. Under project settings, configure webhooks to trigger a rebuild on your hosting platform whenever content is published. This keeps your static site in sync without manual deploys.

  • Use content federation wisely. Hygraph's killer feature is federating external REST or GraphQL APIs into your schema. If you need product data from Shopify alongside blog content, you can query both through a single Hygraph endpoint.

  • Type your GraphQL responses. Generate TypeScript types from your Hygraph schema using graphql-codegen. This gives you autocomplete and compile-time safety for all your queries.

  • Alternatives to Consider

    • Contentful if you want a REST API option alongside GraphQL and a larger ecosystem of integrations.
    • Sanity if you need real-time collaboration features and a more flexible schema builder with GROQ queries.
    • DatoCMS if you prefer a similar GraphQL-first CMS with built-in image optimization and a simpler pricing model.

    Wrapping Up

    Hygraph and Astro work well together for content-driven sites, especially when you need GraphQL flexibility or content federation. The free tier covers small projects, and the GraphQL API means you query exactly the data you need with no over-fetching. If your project involves pulling content from multiple sources or you prefer GraphQL over REST, Hygraph is a solid foundation for your Astro site.