Astro/Hygraph

How to integrate Hygraph CMS with Astro and Netlify?

  1. First, create your proyect with the command
npm create astro@latest
  1. Go trough the installation process

  2. Create your account in Hygraph and create a project.

  3. Go to your project dashboard in Hygraph, and select “Proyect settings”

  4. 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.

  5. 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.

  6. Create your data schema on hygraph. In my case i would create a blogPost with a title, a slug and content.

  7. Create a blog entry and complete the fields.

  8. 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)

  9. In astro, save your HYGRAPH_ENDPOINT in a .env file on the project root. Then you could call this key with import.meta.env.HYGRAPH_ENDPOINT in any of your files.

  10. 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);
  1. 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!");