Hashnode API with NextJS
Learn how to fetch data from the Hashnode API in NextJS using Apollo Client
Learn how to integrate the Hashnode API in NextJS using Apollo Client.
I was building my dev portfolio using NextJS and wanted to fetch my articles from Hashnode and display them in my portfolio.
The most efficient way of implementing this feature in Next was to fetch the articles using getStaticProps and revalidate them after intervals this would make the site blazing fast and extremely SEO friendly.
We could have used the useEffect hook but affects the performance and isn't SEO friendly. Hashnode has an API, which you can use to retrieve, create, edit and delete articles using Graphql. However creating, editing, and deleting articles require a personal access token. In this tutorial, we will focus on only fetching articles.
Setting up our projects
Let's start by installing and importing the necessary packages. We will use Apollo Client for fetching the data
Installing the necessary packages:
npm install @apollo/client graphql
Import the necessary packages:
import { ApolloClient, InMemoryCache, gql } from "@apollo/client";
Now, let's use getStaticProps to fetch the data:
Note: getStaticProps works only in files present in the pages folder, if you want to pass the data to a component present in any other folder you need to fetch the data in a page-level file and pass it to the component or use Providers.
Fetching the data
If you export a function called getStaticProps (Static Site Generation) from a page, Next.js will pre-render this page at build time using the props returned by getStaticProps.
Creating the getStaticProps function:
export async function getStaticProps() {
const client = new ApolloClient({
uri: "https://api.hashnode.com/",
cache: new InMemoryCache(),
});
const { data } = await client.query({
query: gql`
query GetPosts {
user(username: "uenmedia") {
publication {
posts(page: 0) {
brief
title
}
}
}
}
`,
});
return {
props: {
posts: data.user.publication.posts,
},
};
}
You can use the Hashnode Graphql Playground to generate your query accordingly.
Pass the data to your component
export default function Home({ posts }) {
return (
<main className="main">
<h2 className="header-main">Blog post from hashnode API</h2>
<div className="card-container">
{posts.map((post, key) => {
return (
<div>
<h1>{post.title}</h1>
<p>{post.brief}</p>
</div>
);
})}
</div>
</main>
);
}