Adding Hashnode to Gatsby websites
If you are reading this you probably have two things:
Although they work great we sometimes want to mix them together so we can do things as:
- Add links to our hashnode posts in Gatsby (“Articles section”).
- Show posts stats in Gatsby.
- Show our hashnode user stats.
- and many more options
The Solution: GraphQL
Hashnode already has a wonderful GraphQL interface which can be found here: https://api.hashnode.com/. This interface can be used to easily get all our user posts (and other data) by the following query:
{
user(username: "HASHNODE_USERNAME") {
publication {
posts {
_id
title
slug
brief
coverImage
}
}
}
}
The query result, which includes a list of all your posts, can now be used in Gatsby to build our components and pages.
An even better solution: Gatsby source plugin
Although the direct GQL interface exists and works fine I wanted a plugin to be able to query all my hashnode posts with Gatsby from the start. This lead me this weekend to create gatsby-source-hashnode.
(Full code can be found here: https://github.com/nitzano/gatsby-source-hashnode)
What it does? when Gatsby start it runs the GraphQL query from above with your username and creates HashNodePost
entries (nodes) in Gatsby so they can be queried and used anywhere.
When querying GraphiQL in gatsby it will look like this:
Using the plugin
- Add the plugin to gatsby with
npm install gatsby-source-hashnode
- Configurate the plugin in
gatsby-config.js
with your username:
// in gatsby-config.js
module.exports = {
plugins: [
{
resolve: "gatsby-source-hashnode",
options: {
username: "<HASHNODE_USERNAME>",
},
},
],
};
3.Query your data in your gatsby page/component:
const data = useStaticQuery(graphql`
query {
allHashNodePost {
edges {
node {
coverImage
brief
slug
title
}
}
}
}
`);
You can also view the data in GraphiQL (http://GATSBY_HOST/___graphql
) with this query:
query MyQuery {
allHashNodePost {
edges {
node {
_id
brief
slug
title
}
}
}
}