Server side pagination in Hygraph with Sveltekit and Houdini

Paul Matute portrait

Paul Matute

Published May 11, 2023

Share

Pagination is a common requirement in projects. Hygraph is a CMS that includes an API for dealing with pagination.

Pagination in hygraph cover photo

In this post I will cover how to implement pagination in a Sveltekit project using Hygraph as CMS, and houdini client.

Link to the repository can be found here.

Creating a new hygraph project

To get started we need to signup to hygraph and create a new project. We will select the simple blog template and make sure that we have the 'Include template content' tickbox selected.

In our newly created project we then navigate towards the project settings and under 'Access' we find 'API access'. We then copy the Content API url.

Creating a new Sveltekit project

As all new Sveltekit projects go we need to initialize the project with npm create svelte@latest pagination-hygraph.

We then follow the steps prompted by the terminal to finish the setup.

We will then need to install Houdini Graphql to handle the graphql calls. To easily setup houdini we can run npx houdini@latest init and follow the prompts using the url we copied from the step before.

(Optional) Changing the watch interval.

With the new created config from houdini, we can change the configuration to only fetch the schema.graphql once at startup.

Creating our query

To fetch data we need to create our query. We need to create a gql file anywhere in our src directory.

The important thing to note is that we don't query directly to the 'post' in our schema but instead the 'postConnection'. We include after and before parameters so that we can fetch after or before our query results. For the pagination approach I am taking it is imperative that we query in 'pageInfo' the start and end cursor. The hasPreviousPage and hasNextPage is just a quality of live improvement for the interface to know if there are more items or not.

Loading data

Once we have the query written we need to fetch the data and pass it to the client. For that we use the page server load function of a route. We use the url searchparams to handle the position.

and then we can use the data in our route as such, with the anchors including the searchparams.

Final notes

This is one approach using that uses a relay-like api. Certainly there are other ways you could implement pagination that would fit your use case better.

Other posts

Computer in a room

Using github gists to show code blocks

While GitHub repositories are great for hosting entire projects, sometimes you need a more straightforward solution for sharing smaller code blocks. That's where GitHub Gists come into play.