Skip to content
Home » Blog » How to get data from Hygraph in next.js using params

How to get data from Hygraph in next.js using params

Yes, it is pretty simple. use this code and update your query.

import Link from "next/link";
import { Metadata } from "next";
import Image from "next/image";

async function getPage(slug) {
  const response = await fetch(process.env.NEXT_HYGRAPH_ENDPOINT, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      query: `query Page($slug:String!) {
        page(where: {slug: $slug}) {
          title
          slug
         shotDescription
          contentBlocks
    {
      heading
      content
      {
        html
        markdown
        text
      }
        image
      {
        url
      }
      imagePosition

    }

     seo
    {
      metaTitle
      metaDescription
      keywords
    }

        }
      }`,
      variables: {
        slug,
      },
    }),
  });
  const json = await response.json();
  return json.data.page;
}

export default async function Page({ params }) {
  const page = await getPage(params.slug);
  return (
    <div className="pt-25 container">
      <h1 className="text-5xl font-bold mb-4">{page?.title}</h1>
      <p className="text-lg mb-8">{page?.contentBlocks[0].content.text}</p>
      <span className="text-center">
        <Image
          src={page?.contentBlocks[0].image.url}
          width={1080}
          height={1080}
        />
      </span>
    </div>
  );
}

Leave a Reply

Your email address will not be published. Required fields are marked *