How to integrate Hygraph CMS with Astro and Netlify?
- First, create your proyect with the command
npm create astro@latest
-
Go trough the installation process
-
Create your account in Hygraph and create a project.
-
Go to your project dashboard in Hygraph, and select “Proyect settings”
-
You can grab the Content API or the High Performance Read-only Content API for data visualization. The defference between them is that hte content API allows data mutation.
-
Then you need to add permision for this API to be accesible. Click on the “Add Permission” button on the Public Content API section. In this case we will use the Read permission.
-
Create your data schema on hygraph. In my case i would create a blogPost with a title, a slug and content.
-
Create a blog entry and complete the fields.
-
I created the title of a Single Line Text, the slug of Type URL and the content of Multi Line text. This allows for customization on those fields, like an autogenerated slug and some markdown capabilities in case of the content. In astro, later you could use Marked and some tailwindcss/typography for styling the Markdown content (more on this later)
-
In astro, save your
HYGRAPH_ENDPOINT
in a .env file on the project root. Then you could call this key withimport.meta.env.HYGRAPH_ENDPOINT
in any of your files. -
For quering the blogPost data you could import directly into your index page (or you could create a service folder and create a function, it is your choice) like this:
const query = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
query: `
{
blogPosts {
id
title
slug
content {
markdown
}
}
}`,
}),
};
const response = await fetch(import.meta.env.HYGRAPH_ENDPOINT, query);
const json = await response.json();
console.log(json.data.blogPosts);
- The code provided before can be on its own function or in the Astro
frontmatter
. You should see the log of the posts on the server console. If not, then be sure to have published your blog post.
And there is, you could find this working in this github repo it has marked for parsing markdown content!
console.log("See ya astronauts!");