Create a .env
file, this is where the GraphQL API endpoint will go. You can either create this in your text editor manually or use the following bash command to create the file:
touch .env
echo PUBLIC_GRAPHQL_API= >> .env
Get the Content API URL from Hygraph, you can find it in Project Settings > API Access > Content API
Add the copied URL to the .env
file, it should look something like this now:
PUBLIC_GRAPHQL_API=https://api-region.graphcms.com/v2/projectId/master
Install graphql-request
and graphql
:
pnpm i -D graphql-request graphql
To load the data for the index page create a +page.js
file:
touch src/routes/+page.js
To get the data from the GraphQL API add the following to the src/routes/+page.js
file:
import { PUBLIC_GRAPHQL_API } from '$env/static/public';
import { gql, GraphQLClient } from 'graphql-request';
/** @type {import('./$types').PageLoad} */
export const load = async () => {
const client = new GraphQLClient(PUBLIC_GRAPHQL_API);
const query = gql`
query AllPosts {
posts {
title
slug
date
excerpt
tags
coverImage {
url
}
}
}
`;
const { posts } = await client.request(query);
return {
posts
};
};
Then in the src/routes/+page.svelte
file get the data returned from src/routes/+page.js
and dump out the contents of data
into a pre tag to see the data returned from the GraphQL call: