Skip to content

This Dot Blog

This Dot provides teams with technical leaders who bring deep knowledge of the web platform. We help teams set new standards, and deliver results predictably.

Newest First
Tags: Gatsby
Building SEO-Powered Websites With Gatsby cover image

Building SEO-Powered Websites With Gatsby

Gatsby is a framework that leverages React for building SEO-powered websites. Many websites are created to be discovered, hence, SEO support is an important factor in such websites. Many factors influence SEO such as accessibility, correct meta-information (at the head tag) and some other external tools. Gatsby supports using appropriate meta information for individual pages to improve their presence online. In this article, we'll look at the limitations of Create React App in respect to SEO, and how Gatsby solves this with SSR. Furthermore in the article, we'll go through a tutorial on building a basic website with good SEO. Why CRA is not a good tool for SEO CRA is an opinionated tool used for building React applications but cannot be used for SEO. Here's why: When using React, you'll most probably be using a library like react-helmet (a document head manager for React) for updating meta-information about the site. The limitations of such libraries is that they contain JavaScript, which means they can only be executed on the browser (so JavaScript can run). SEO crawlers or social media tools that inspect head tags of websites (to display a card, perhaps) would not execute that JavaScript. Instead, they make use of the default meta information they can find. In CRA, the default title in public/index.html is "React App". This means, for every page you create (based on routes), they will all have the same title. They only show different titles when they are executed on the client's browser because the react-helmet library gets the chance to be executed, thereby updating the head tags. This article contains more information. How Gatsby solves React SEO problems with SSR Gatsby is a Static Site Generator (SSG) which uses Server Side Rendering (SSR) to generate static pages during the build process. What this means is that you provide dynamic meta information in every page, and during the process of static site generation, pages are server-side rendered with the specified meta information, thereby making static pages with their own details. With this technique, every page contains its own meta title, meta description and basically every meta information. The following tutorial shows how Gatsby improves SEO in web applications. Building an SEO powered site with Gatsby We'll be building a basic website with two pages: / - Home and /about - About Us. These two pages would have their own meta information attached to them during the build process. To get started, let's created our Gatsby project. Run the following in your terminal: ` This pulls the default template, and installs all necessary dependencies. In the src directory, you'll find three directories: components, images and pages. As you may observe, the template already comes with some configurations for seo and optimizing images. To build our project afresh, delete the following files/directories: ` This will leave us with components/seo.js and images. In a future series, we'll explore the gatsby-image plugin used in components/images.js. But for now, understand that it performs optimizations on images. Let's briefly explore the content of components/seo.js ` _Note that_ this component can look a bit different in another template, or you may do it differently. The SEO component receives four props: title, description, lang and meta with title as required. You can specify more props if you want or take out those you don't need. This allows different pages to specify their titles, descriptions and other meta information specific to them. Helmet is from react-helmet but is used a bit different from how it is used in CRA. It works with gatsby-plugin-react-helmet which provides server rendering support. components/seo.js also contains some GraphQL which we will cover in a future series. The Helmet plugin during the build process populates all pages with their respective meta information depending on the inputs provided during development. Now let's add our pages. With Gatsby, you do not need any routing packages for determining components to show based on specific URLs. To create a page, all you need to do is add the component's file directly under the pages directory. To create the two pages for our project, add two files: index.js for / and about.js for /about. Before proceeding with our pages, let's add a layout. Create components/layout.js and components/header.js. Add the following in components/header.js: ` Same React. The only thing new here is a different Link component from Gatsby is used. In the components/layout.js, add the following: ` For the pages, add the following to index.js: ` I added an unsplash image to images and required it require('../images/laptop.jpg') as seen above. We'll look at the usage of the SEO component soon. For pages/about.js, add the following: ` Create a new directory called styles under src and create a new file: global.css. Copy the following css styles to that file: ` For the global stylesheet to be used for the whole site, the gatsby-browser.js API file would be used. gatsby-browser.js is a reserved API file that gives access to actions within the browser. In gatsby-browser.js (at the root of your project), add the following: ` When you run the gatsby server for your project (gatsby develop), you'll get the following on localhost:8000: For /: For /about: The SEO component makes all the pages unique and SEO-ready. For index.js, we have: ` Just as we have configured the SEO component using react-helmet, this updates the meta information for the homepage during the build process. This way, the first thing crawlers will see is the unique meta details for the page, as they do not require any JavaScript to be updated. To test this, do the following: - build for project for production (gatsby run build) - serve the production build (gatsby run serve) This will run the built content on localhost:9000. You can use curl on your terminal to inspect the source code (or run inspect on the browser). ` The result: The reason it came out as "Homepage | Gatsby Default Starter" is because of the prop titleTemplate provided by Helmet which was configured like so in the SEO template: ` This appends a default title to every title provided by the pages. Conclusion In this article, we looked at how Gatsby solves the problem of SEO using server side rendering for generating static pages. The basic example used in the tutorial shows how each page contain their own meta information that can easily be crawled by SEO bots or social media tools....

Getting Started with GatsbyJS cover image

Getting Started with GatsbyJS

GatsbyJS is a React framework and a Static Site Generator (SSG) tool used in building web applications. It combines Server Side Rendering (SSR) features and static site development for building SEO-powered, secured, and fast applications....

Performance: Optimizing Images on Gatsby Sites cover image

Performance: Optimizing Images on Gatsby Sites

Performance: Optimizing Images on Gatsby Sites Our Labs website is written using Gatsby, and uses images in many places. We have images that are both statically hosted, and images that are hosted in Contentful. The Problem We found that many of our static images weren't compressed as optimally as they could be and were inflating page sizes. This example comes from a page with many images that are being used as-is with no post-processing in the site build. Some of the images are lossless compressed PNGs that can be JPGs instead, and some of them are already JPGs but their sizes far exceed the size of the container they're in. The Solution Instead of manually optimizing each static image we can let gatsby-image do this for us. Static Images The static images can be easily fixed by replacing all uses of with from gatsby-image. GQL queries will also need to be updated to return fixed or fluid images. gatsby-image doesn't take image urls directly like a normal tag does, but instead, takes a special fluid or fixed type that optimizes the images differently. The fixed type should be used when the width and height are known, and will not change. The fluid type should be used if the image will stretch to fill the container that it's in, depending on the screen size. Here's an example of an for avatars being replaced with a fixed image. ` The type of avatarUrl needs to be changed from a string to a sharp fixed image in the GQL query. This is also where optimization parameters such as size and quality can be configured. ` Here, just width and height are specified, but there are other useful parameters such as quality and toFormat, which can be useful if you want to make sure images are converted and compressed to your liking during the build. Here's an example that ensures images have a size of 160x160 and are JPGs with 80% quality: ` All static image paths returned by the query should be relative so that gatsby-image can find them. Absolute image paths will not work with it like they do with . Optimizing Images from Contentful While the gatsby-image package makes it very easy to optimize images when you're dealing with content templates, it doesn't work well on its own if you're dealing with markdown or pre-supplied HTML. Posts on our Labs blog are written in markdown, and are stored with Contentful, and we render posts by converting them to HTML with gatsby-transformer-remark. We're able to optimize these images using gatsby-remark-images-contentful. This plugin extends gatsby-transformer-remark to output images that use parameters from Contentful's Image API, and to generate different sized versions of images that are chosen based off of the size of the device. This plugin also adds a "blur up" effect as the image is downloaded, and holds the size of the incoming image to prevent a reflow. It's also notable that using this plugin will give us image lazy loading as well, which can speed up load times for image heavy pages substantially. Here's how we configured this plugin in gatsby-config.js: ` Before & After Results Here's an example of how our teams page has improved and went from a 856kB image weight to 300kB with these simple changes. Before After Here's an example of an image heavy blog post with images from Contentful that had its initial load size cut by _almost 50%_, from 6.1MB to 3.4MB. Before After The gains seen here come mostly from lazy loading provided by gatsby-image, so images are only downloaded once they're about to come into view; however savings also come from serving images of appropriate sizes, so a mobile device such as the Pixel 2 will have an initial load of 1.6MB. We don't forcefully format all blog post images to JPG currently as there may be legitimate reasons to not use them, e.g. you want to keep transparency or embed animated gifs. Closing Gatsby makes it easy to optimize your sites without expending too much effort. If you're already using Gatsby, I'd encourage you to make sure you're using it to its fullest potential....



*This article was taken from the above podcast.* Welcome to another edition of the Yolo Brolo podcast where we play with new technologies and you come around for the ride. Last time we scaffolded a basic Gatsby CLI project that is pretty much empty and does nothing than display the default Gatsby contents. But we’d be continuing by adding some cool features to the site so it’s not just plain HTML, we will turn the project into a blog, add markdown pages and syntax highlighting. EXPLORING PROJECT FILES Here, we’d be going over the contents of the scaffolded gatsby project we got from the previous tutorial. gatsby-config.js This file holds some important configurations specific and also important to the entire project. Basically the information included in this file are the site meta-data which holds information about the site title, description and author. It’s important to note that these properties can be extended to include other relevant information you seem fit for the site. For our project this looks like: ` Also, pre-bundled to this config file are plugins that are needed for the entire project and we would be exploring these plugins and their purpose. To learn more about most of the plugins it is recommended you do a google search on them and read them up on the official gatsby documentation page: - gatsby-plugin-react-helmet: This plugin is basically concerned with Server Side Rendering using react, SEO and meta tags. - gatsby-source-filesystem: This file is used to reading files from your local file system into the Gatsby project. - gatsby-transformer-sharp: This plugin is involved with a lot of image process and according to the official documentation the plugin is used to create ImageSharp nodes from image types (images in the Gatsby project) that are supported by an image processing library known as *Sharp*, the plugin as provides fields in their GraphQL types for processing images in a variety of ways including resizing, cropping, and creating responsive images. - gatsby-plugin-sharp: Generally, this plugin is used by other plugins for image processing, as it provides image processing functionalities built on top of the Sharp image processing library. - gatsby-plugin-manifest: This plugin is mostly concerned with adding Progressive Web Application (PWA) features and manifest files for offline use cases to the the Gatsby project. gatsby-browser.js This file holds information on every API we would love to add to the project and make use of in the browser. gastby-node.js This is where a lot of the generation takes place but in general this file will be used for creating pages for the site. gatsby-ssr.js This file handles everything server side rendering on Gatsby. src src is the source folder and most of the important stuff happen here, one of the important files here is the index.js file - index.js: This is the main file used by Gatsby to build up your application. If you look closely, you’d discover it contains the contents served when we run localhost:8000 or the netlify generated url for our deployed project. Enter $ gatsby develop on the terminal (make sure you are in the project directory) which will enable Gatsby spin up a local server to serve your Gatsby project on "localhost:8000”. Also, from the terminal output you’d notice that we have an exposed graphql endpoint at "localhost:8000/__graphql” for having a look at the graphql queries. BUILDING A BLOG It’s important to note that there are lots of starters and groups of plugins to help you achieve what we are about to do and you pretty much are free to check out Gatsby blog starters. But for the purpose of this tutorial we’d be building it from scratch just to see how it’s done and get our hands dirty. Also if you are trying things out with gatsby, always checkout the documentation as it’s a totally awesome one. Doing a quick google search on gatsby markdown pages will quickly take us to the gatsby documentation on "Adding Markdown Pages” . We need the gatsby-source-filesystem plugin to add markdown support to our blog. First we have to create a posts folder within the src folder from which the plugin will read the markdown pages from. Next, we create a file within the posts folder with the content: ` Next, we need to install the gatsby-transformer-remark plugin which will convert/transform the markdown pages to HTML. To install this plugin, stop the running gatsby server by clicking CTRL + c then run the following command: $ npm install –save gatsby-transformer-remark Once the installation is complete, we add an additional section to the gatsby-config.js under the gatsby-source-filesystem plugin file like so: ` Next, we need to create a page template for the markdown file and add some frontmatter which includes some extra meta-data for adding extra stuff to the HTML files. The frontmatter always comes at the top of the markdown files like so: ` To add the template file for the markdown pages, we need to add a templates folder to the src folder and add the page templates there(the template is basically a react component making use of a graphql query), for our case we need to create a postTemplate.js. Add the following content to the file; ` The pageQuery variable holds the graphql query, based on the $path defined in the frontmatter and return the html (converted markdown) and frontmatter from the markdown page. The Template function receives the query result in an object parameter called data, that includes an object called markdownRemark. This object contains the frontmatter and html that wew are going to destructure from the markdownRemark variable, finally the Template function basically renders the output of the deconstructed objects. The gatsby-node.js page needs the following code to create our page: ` After adding the code, we can check out our new feature and the markdown feature by rebuilding the project and starting our local server by running gatsby develop on the terminal, then checking out the blog page using localhost:8000/blog/my-first-post (the endpoint used to access our page has been configured in the frontmatter of the markdown). It is time to create, we can create another markdown page, we’d name, We pass it the frontmatter configurations and makes it hold # Hello world again! as content, like so; ` We move on to add some markdown code formatting syntax using the triple backticks like so; ` const greeting = "Hello”; console.log(${greeting} world ); ` Navigating to localhost:8000/blog/my-second-blog we’d see the Hello world again! Heading and the markdown formatted block of code within the triple ticks in a gray background, but that is not the prettiest syntax and we’d need to add some fancy highlighting. To achieve the syntax highlighting we’d be using gatsby-remark-prismjs plugin for markdown. For the plugin to work we need to have gatsby-transformer-remark plugin installed (which we already have) and gatsby-remark-prismjs (which we will install shortly). To download and add the plugin to the project stop the running server using CTRL + C and run on the terminal: > $ yarn add gatsby-remark-prismjs prismjs This command will download the prismjs plugin and add all it’s dependencies to the project. In the gatsby-config.js file we add the following configurations; ` It is also necessary to add add the prismjs css for the syntax highlighting feature to be complete. We add the css by adding require("prismjs/themes/prism-solarizedlight.css”) to the gatsby-browser.js file. After saving the changes we have made, we spin up the server again by running gatsby develop on the terminal to see the effects of the prismjs plugin and css to our markdown pages. To make the styling a little bit more fancier and language specific, we can add javascript keyword after the three backticks in the file, like so: `javascript const greeting = "Hello”; console.log(${greeting} world ); ` Checking localhost:8000/blog/my-second-blog you’d discover the color effects are a bit different from earlier, and it looks really great now. The ease with which things are done in Gatsby is mostly because the ecosystem around Gatsby is quite big and a lot of things you’d need has mostly been done. We can further add our own custom CSS styling to the project by creating a folder styles and create a global.css file, then we include the stylesheet in gatsby-browser.js file like so; > require("./src/styles/global.css”) Then in our global.css file we add the following styles to see that it actually works: ` Reloading our browser tab at localhost:8000/blog/second-blog-post we’d discover that it actually works! Now we can go ahead to delete the codes and add the following code to make our line highlighting in our markdown pages possible; ` Then in the file add {2} to the javascript keyword to highlight line two of the code block, like so; `javascript{2} const greeting = "Hello”; console.log(${greeting} world ); ` Checkout localhost:8000/blog/my-second-post and you’d discover that the second line of the code is highlighted! There are a lot of other styles we could also add to the markdown files. WRAP UP We touched the different gatsby files of a typical gatsby project, the config files, the pre-bundled plugins and the graphql queries. What's cool about Gatsby is that everything is statically rendered from the server, but once the page loads gatsby bootstrap up a spar and load the rest of the page dynamically and won’t request from the server everytime you reload. Most of all the codes added to our project where lifted from the Gatsby official documentation and it’s a good practice to checkout the official Gatsby documentation when you are in doubt. *This article was written by Opara Prosper who is a freelance writer.*...