There are lots of quick and easy, no-code ways to get blog up and running — such as Medium or Wordpress — but, whether it’s to customize, monetize, add security, or just learn, today, I’ll show you how to code your own blog from scratch.
- Markdown: Markdown is most used as an alternative to Rich Text. Enables advanced techniques such as MDX. Slug: Slug template with automatic initial value generation based off existing fields.
- Jun 24, 2019 Learn to build a blog using Markdown and GraphQL, and then deploy it to Netlify. The web is ever evolving and the need to stay updated as developers is really important. In this article, I’ll be introducing you to the world of static site generation and the JAMstack using Gridsome.
- SourceForge uses markdown syntax everywhere to allow you to create rich. Text markup, and extends markdown in several ways to allow for quick linking. To other artifacts in your project. Markdown was created to be easy to read, easy to write, and still readable in plain text format.
- Load the extension on detecting graphql-config file at root level or in a parent level directory; Load the extension in.graphql,.gql files; Load the extension on detecting gql tag in js, ts, jsx, tsx, vue files; Load the extension inside gql/graphql fenced code blocks in markdown files.
It follows the same syntax as regular Markdown code blocks, with ways to tell the highlighter what language to use for the code block. The language will be detected automatically, if possible. Or you can specify it on the first line with 3 colons and the language name.
When adding a blog to your existing website, or just starting out with a new blog, a static site generator can help you get started.
Static site generators such as GatsbyJS are primarily used to serve fixed content, but they can also be used for pretty much any web application, including blog and e-commerce web applications.
In this post, we are going to create a blog from scratch using GatsbyJS with ReactJS and GraphQL at its core.
What is GatsbyJS?
Gatsby is a simple, robust, and fast static site generator. It uses ReactJS to render static content on the web. The content in a Gatsby app is written in the same way as any other React app: through components. These components are rendered at build time to the DOM as static HTML, CSS, and JavaScript.
At a high level, Gatsby uses various source plugins to read data and make it available via a GraphQL interface. You write GraphQL queries to load this data and render React components. GraphQL can render content that is sourced from a large number of formats and sources such as Markdown, CSV, and CMS like Wordpress, Drupal, GraphCMS, and so on.
Why use Gatsby?
Gatsby takes care of a lot behind the scenes.
- Future proof JAMstack websites
- Gatsby has a rich plugin ecosystem that is easily extensible
- Pre-configured Webpack based build system (no need to break your head)
- Supports PWA (Progressive Web App) by default
- Optimized for speed. Gatsby loads only critical parts so that your site loads as fast as possible. Once loaded, Gatsby prefetches resources for other pages so that clicking on the site feels incredibly fast
Gatsby also has an ever-growing data plugin ecosystem, especially for data transformation. Overall, I think the points above should be enough to lure you into trying it out.
Pre-requisites
- Familiarity with HTML, JavaScript, ReactJS
- Nodejs with
npm
oryarn
installed - Gatsby CLI (which we are going to install in next section)
Note: At the time of writing this tutorial, Gatsby v2
was officially launched.
Getting Started with Gatsby
To start, we need to install the command line utility provided by GatsbyJS to quickly scaffold projects. Open your terminal and type the following command.
To verify that it has been installed, run the following command.
Once you successfully installed gatsby-cli
, it is time to generate a new project.
This process will take a minute or two and, at the end of it, you will have a new directory. Traverse inside it. Gatsby’s default project structure looks like this:
To see what we get by default, run gatsby develop
. This will run the project without creating the official build directory on a development server through webpack (used by Gatsby internally). After the command runs successfully, you will be prompted by the following screen like below in your terminal.
You can visit http://localhost:8000
to see the default site in action.
Running a GraphQL Query
Every Gatsby project contains at least these files. You might be familiar with some of these such as node_modules
and public
directory, which is served when deployed. It also contains package.json
, which contains the metadata of any modern Javascript application.
Our main object of focus are in the directory src
and files such as gatsby-config.js
and gatsby-node.js
.These contain the metadata and other essential information about our current application. Inside the src/
there are two sub-directories: components/
and pages/
. The components/
contain further two files: layout.css
and layout.js
. These serve as the starting point of our application.
You have already seen what the default page that comes with Gatsby looks like. We have a title in the navigation bar. Let’s add a subtitle. Open gatsby-config.js
and a new field description
and change title
like below.
Gatsby allows us to query metadata fields described in this file as a GraphQL query. In order to take a look at what kind of stuff we can query from Gatsby, run gatsby develop
from the terminal. You will not see any changes at http://localhost:8000/
yet because we haven't modified the component responsible for that. However, we can verify by running a simple GraphQL query. Open http://localhost:8000/___graphql
in the browser.
We’ve got the GraphQL browser open and over on the side here, we can see the documentation explorer, which lets us go through our schema and look at what kind of stuff we can query for. Click on the query
type on the right hand side to see what query fields we can access.
This gives us a list of all of the query types that we can look for. Take a look at the site
and the siteMetadata
. You can start typing a s
, and you will see an autocomplete for the query type site
. This is really helpful. Run the below query.
Great!
Now that you are familiar with the nitty-gritty of Gatsby and how it works, in the next section, we will start working on the blog.
Writing our first Markdown blog post
Gatsby makes use of various plugins for building static sites. In this section, we are going to install and configure in order to make use of gatsby-source-filesystem
and gatsby-transformer-remark
to work with locally stored Markdown files. Open your terminal and type.
I am using yarn
because Gatsby uses it by default over npm
as the package manager. Once both of these dependencies are installed, configure gatsby-config.js
file like below.
The rest of the plugins remain same. gatsby-transformer-remark
is used parse Markdown files in .md
format into HTML. gatsby-source-filesystem
helps us with reading those markdown files from the disk. Each post in our blog is going to be in markdown format.
To understand it better, let us add some posts. Traverse to src/pages
directory and then add one or two posts in a year, month, and date format with a slug like below.
Each markdown file is supposed to have some frontmatter fields that are used to create and update our posts. Open the 2018-11-14-hello-world.md
and the following content.
Similarly you can add the content to the second post.
The content of these two Markdown files will be our first two blog posts. The block surrounded in dashes is referred to as frontmatter, and the contents of the block can be used to inject React components with the specified data, e.g. path, date, title, tags etc.
One important note is that path will be used when we dynamically create our pages to specify the URL to each blog to render the file. We’ll do this later.
Creating the Blog Template
If you take a look at your blog in a browser, you will see that Gatsby is not yet displaying any blog posts that you have created. This is because Gatsby still does not know where these blog posts are or that you even want them to be displayed in the browser. However, if you try to query it in the GraphiQL browser tab, you can see that frontmatter data of blog post is available.
Each Markdown file is parsed into a node of type MarkdownRemark
. To query all markdown files in on query, we are using allMarkdownRemark
. All frontmatter fields are converted into GraphQL fields.
To display each post let us create a new template that will be consistent in style and getting frontmatter from GraphQL query we have just seen. Inside the src
directory, create a new folder called templates
and inside it, create a new file called blogPost.js
.
In this component, notice the new query postQuery
we are creating. This query will help us to display our blog posts into the template. This query puts all the frontmatter we require in order to display blog post in the component Template
's props
.
In above, I am fetching the title for each post and the HTML content. While rendering the output we get from the query, I am using dangerouslySetInnerHTML
which is a React’s replacement for using innerHTML
in the browser DOM. In general, setting HTML from code is risky because it exposes a user to a cross-site scripting (XSS) attack if used with sensitive data. Since we do not have any users (no login/signup system), I am just using it for content that is rendered as HTML from markdown.
We now have a template of how our blog post will look but we still haven’t configured a way to render and convert a blog post into HTML. That’s next. Open gatsby-node.js
in the root of your project and add the following code.
We start by requiring Node’s path
in order to fetch the blog post template. Notice the actions
along with graphql
as parameters when we are exporting createPages
. Gatsby uses Redux internally to manage state. That's where actions
come from. The object actions
contain the functions and these can be individually extracted by using ES6 object de-structuring. It has pre-defined functions such as createPage
, createRedirect
, setWebpackConfig
and so on. You can find all of them here.
We then make use createPage
programmatically. There are two other ways other than the approach we are implementing. In our case, we need to read Markdown files.
Since our home page is still not done to display a list of blog posts you will have to visit each URL listed below in order to see the blog posts in action.
- For the first post, visit:
[http://localhost:8000/first-post](http://localhost:8000/first-post)
- For the second post, visit:
[http://localhost:8000/second-post](http://localhost:8000/second-post)
Try to modify the Template
component and other fields from the frontmatter. Open src/blogPost.js
.
To represent the changes, I have added the date in italics just before the content of the blog post and after the title. Visit any post’s URL and see it in action.
Adding Previous and Next Blog Post Links
For this feature to work with our blog, we are going to make use Gatsby Link
component. It is a wrapper around @reach/router
’s Link component that adds enhancements specific to Gatsby and you can even use props such as activeStyle
or activeClassName
to add styling attributes to the rendered element when it matches the current URL. Just like how a normal routing component in React behaves. Open blogPost.js
file and add this.
Notice how I am using span
tags with attribute role
to wrap emojis along with aria-label
attribute. It is considered as good practice in Gatsby, React and you will definitely avoid any linting errors. Now to make the above code work, we need to modify the context
in gatsby-node.js
.
Graphql Markdown In Python
The context object now contains two keys called prev
and next
. We are also using index
value of each post. If the index 0
, there is not going to be any previous post since it is the first one. You cannot go to a previous post here. We are then using these new context properties in blogPost.js
using pathContext
.
Visit the first post and you will get the following result.
Display all posts on Homepage
Since all of our markdown posts are getting rendered into HTML correctly, the next and previous post feature working too. So let us move ahead and display all the blog posts on the home page. Not the complete posts, but a link to each one.
On visiting the Home page URL: http://localhost:8000/
you will get the following result.
Conclusion
We now have a functioning blog!
I challenge you to expand your own blog further by adding comments or tags functionalities. Gatsby has a lot to offer. You learn more about Gatsby at their official documentation.
The complete code for the tutorial at this Github repository
React Query is a library that provides a set of hooks for fetching, caching, and updating data in your React applications. In this tutorial, we will be looking at React Query and learning how to use it in a React and GraphQL app.
What is React Query?
React Query (RQ) is a performant and powerful data synchronization library for React apps. It provides a collection of hooks for fetching and managing data. It is backend agnostic, which means you can use REST, GraphQL, or whatever APIs you like, RQ doesn’t care. React Query handles caching, background updates, and stale data out of the box with zero-configuration. The caching layer of RQ is powerful and minimal effort to configure.
React Query makes state managing easy because it allows you to fetch, mutate and cache data with almost no hassle. And can also be customized for more advanced use cases. While React Query does a lot for you, it’s not a complete replacement for client-state management libraries because RQ can’t handle UI state (state for controlling the interactive parts of our app); it’s a library for fetching and synchronization data.
However, RQ is designed to replace the boilerplate code and related wiring used to manage cache data in your client-state and replaces it with just a few lines of code. RQ has to manage asynchronous operations between your server and client and use Redux, MobX, Zustand, or even React Context to handle the UI state. This way, you will get a simplified app logic and delivers a snappy experience to your users with less code.
What we’re building

In this guide, we will be building a Blog app using React, React Query, and GraphQL. We will retrieve the data from the TakeShape GraphQL API. Let’s get started!
Setting up
Before we craft up a new React app, we need to sign up for an account on TakeShape (it’s free) then create a new project to get a GraphQL API to play with. After you create an account and create a read-only API key, open your command-line interface and run the following:
This command will create a new React app for us. Next, we need to install a couple of libraries. Browse to the project root and do the following:
Here’s what each of the libraries you are installing does:
Graphql Markdown Cheat
react-query
allows interacting with the GraphQL API and retrieve the data.react-router-dom
enables routing in our app.graphql
is a dependency forgraphql-request
.graphql-request
allows fetching data from a GraphQL backend.react-markdown
helps render Markdown in a React app.
With the dependencies installed, we can get our hands dirty and see React Query in action.
Folder structure
Structure your project as follows:
Take special note of the useRequest.js
file. It is a custom hook that uses RQ to retrieve the data from the TakeShape GraphQL API. This file is where the magic happens; it helps interact with the API to fetch the blog posts. You can alternatively use the RQ hooks in your components, but it’s nice to have a custom hook to avoid repeating ourselves.
Next, let’s configure our app to use React Query.
Setting up React Query
In order to use the hooks of RQ to interact with our GraphQl API, we need to wrap our top-level app component with the RQ library query provider.
Using React Query
In useRequest.js
, we start by importing the useQuery
hook and graphl-request. Next, we declare the API_URL
constant with the credentials provided by TakeShape. For each request, we need to include an authorization header with the API key from TakeShape in order to authenticate to the GraphQL API . Using GraphQLClient
allows us to set the API key on each request.
To get all blog posts from the API, we use the useGetPosts
function. The useQuery
hook expects a key (get-posts
) and a GraphQL query. The hook can receive more options, but for this example, we just need these two. Once the fetch is done, we return the data. React Query will append some data to the returned value, which allows handling loading and error states.
Next, useGetPost
, receives the id
of the post to fetch. To pass in the id
to the GraphQL query, we need to add it as a second argument to the request()
method. With this, the data is fetched and then returned.
The custom hook is ready to use. Let’s create the React components and rely on the hook to retrieve the data.
Creating the components
This component is responsible for the display of a blog post preview. It receives the object as a parameter and then shows it accordingly.
PostTemplate.js
is a template to display a blog post. The id
is pulled out from the router params and then passed in to the useGetPost
hook. With this, we can now get the post using its id
. It returns the data and some states provided by RQ to handle the case when something went wrong.
Showing the blog posts
Markdown Graphql Syntax
In App.js
, we import the custom hook and use it to get all blog posts from the API. Then loop through the response data and display the posts using the Post
component.
We are now ready to test our example app in the browser. Open the project directory in your CLI and run:
Graphql Markdown Cheat
If everything works as it should, the app will be up and running here: [<http://localhost:3000/>](<http://localhost:3000/>)
.
Awesome! Our Blog app is looking nice.
React Query comes with dedicated devtools. It helps visualize all of the inner workings of React Query and will likely save you hours of debugging. To enable it, we need to enable it in index.js
.
Import ReactQueryDevtools
from react-query
and add it as a child component of the QueryClientProvider
component. That’s it! The devtools are ready to use. Let’s try it in the browser.
Once you click on the React Query logo, the devtools will pop up with its neat features. Enjoy!
You can find the finished project in this CodeSandbox. Thanks for reading!
Conclusion
React Query is a useful library for managing asynchronous operations between your server and client. It continues to gain traction and is trusted in production by large companies such as Google, Facebook, Amazon, and Microsoft. Folks are using it to simplify their state management because it has great caching strategies, can synchronize and updates server state, and has less boilerplate. RQ is a go-to for your next project that requires remote data fetching.
