Adding hashnode to Gatsby websites

If you are reading this you probably have two things:

  1. A Gatsby website (mydomain.com).
  2. A Hashnode blog somewhere else (blog.mydomain.com).

Although they work great we sometimes want to mix them together so we can do things as:

  1. Add links to our hashnode posts in Gatsby ("Articles section").
  2. Show posts stats in Gatsby.
  3. Show our hashnode user stats.
  4. and many more options

The Solution: GraphQL

Hashnode already has a wonderful GraphQL interface which can be found here: 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: 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:

GQL_EXAMPLE.jpg

Using the plugin

  1. Add the plugin to gatsby with npm install gatsby-source-hashnode
  2. Configurate the plugin ingatsby-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
      }
    }
  }
}

Comments (1)

Kenn Stack's photo

Great Article! Simple, Short, and Consistent! 🚀🚀🚀