Salta ai contenuti

Hygraph & Astro

Questi contenuti non sono ancora disponibili nella tua lingua.

Hygraph is a federated content management platform. It exposes a GraphQL endpoint for fetching content.

In this section, you’ll create a Hygraph GraphQL endpoint to fetch with Astro.

To get started, you will need to have the following:

  1. A Hygraph account and project. If you don’t have an account, you can sign up for free and create a new project.

  2. Hygraph access permissions - In Project Settings > API Access, configure Public Content API permissions to allow read requests without authentication. If you haven’t set any permissions, you can click Yes, initialize defaults to add the required permissions to use the “High Performance Content API”.

To add your Hygraph endpoint to Astro, create a .env file in the root of your project with the following variable:

.env
HYGRAPH_ENDPOINT=YOUR_HIGH_PERFORMANCE_API

Now, you should be able to use this environment variable in your project.

If you would like to have IntelliSense for your environment variables, you can create a env.d.ts file in the src/ directory and configure ImportMetaEnv like this:

src/env.d.ts
interface ImportMetaEnv {
readonly HYGRAPH_ENDPOINT: string;
}

Your root directory should now include these new files:

  • Directorysrc/
    • env.d.ts
  • .env
  • astro.config.mjs
  • package.json

Fetch data from your Hygraph project by using the HYGRAPH_ENDPOINT.

For example, to fetch entries of a blogPosts content type that has a string field title, create a GraphQL query to fetch that content. Then, define the type of the content, and set it as the type of the response.

src/pages/index.astro
---
interface Post {
title: string;
}
const query = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
query: `
{
blogPosts {
title
}
}`,
}),
};
const response = await fetch(import.meta.env.HYGRAPH_ENDPOINT, query);
const json = await response.json();
const posts: Post[] = json.data.blogPosts;
---
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width" />
<meta name="generator" content={Astro.generator} />
<title>Astro</title>
</head>
<body>
<h1>Astro</h1>
{
posts.map((post) => (
<div>
<h2>{post.title}</h2>
</div>
))
}
</body>
</html>

To set up a webhook in Netlify:

  1. Deploy your site to Netlify with this guide. Remember to add your HYGRAPH_ENDPOINT to the environment variables.

  2. Then Go to your Hygraph project dashboard and click on Apps.

  3. Go to the marketplace and search for Netlify and follow the instructions provided.

  4. If all went good, now you can deploy your website with a click in the Hygraph interface.

Altre guide per le CMS

Contribuisci

A cosa stai pensando?

Crea una Issue su GitHub

Il modo più rapido per segnalare un problema al nostro team.

Comunità