SEO and Metadata Management
8 min read
Hello, intrepid coder! 👩💻 Let's talk about making your Gatsby site famous—or at least, discoverable by the likes of Google and shareable on social media. This is where Search Engine Optimization (SEO) and metadata management come in.
The Definition & The Problem
First off, what is metadata? It's simply data that describes other data. For a webpage, this includes things like the page title, a brief description, keywords, and the author. This information lives inside the <head> tag of your HTML document and isn't usually visible on the page itself.
So, what's the problem we're trying to solve? Search engines like Google and social media platforms like Twitter or Facebook need to understand what your page is about. Without clear metadata, they have to guess. Sometimes they guess right, but often they don't, leading to your brilliantly written blog post showing up with a bizarre title and a random snippet of text when shared. Not a good look! We need a reliable way to tell them, "Hey, this is the title, this is the description, and here's a nice image to go with it."
In this guide, we'll walk through how to manage this crucial information in Gatsby, from site-wide defaults to page-specific details, making your site both professional and easy to find.
1. Managing Site-Wide Metadata in gatsby-config.js 🏛️
The Problem: Every page on your website will likely share some common information. Think about the site's main title, the author's name, or a link to your Twitter handle. Manually adding this to every single page would be a colossal waste of time. If you ever needed to update it, you'd have to go on a grand and tedious tour of your entire project. There must be a better way!
The Solution: And there is! Meet the gatsby-config.js file. This file is the central configuration hub for your Gatsby project. It's the perfect place to store information that applies to the entire site.
Inside gatsby-config.js, there's a special object called siteMetadata. Whatever you put in here can be accessed from any page or component in your site using a GraphQL query.
How to Do It:
Let's add some basic information to this file. If you used a starter, you might already have this object.
File: gatsby-config.js
module.exports = {
siteMetadata: {
title: `The Great Gatsby Guide`,
description: `A comprehensive and slightly humorous guide to mastering Gatsby.`,
twitterUsername: `@gatsbyjs`,
siteUrl: `https://www.yourdomain.tld`,
},
plugins: [
// ... your other plugins
],
}Important: Any time you make changes to gatsby-config.js, you need to restart your development server for the changes to take effect.
Now, how do we access this treasure trove of data? With a special React hook from Gatsby called useStaticQuery. This hook lets you run a GraphQL query from any component (not just pages!).
Let's create a custom hook to make this even easier to reuse.
File: src/hooks/use-site-metadata.js
import { graphql, useStaticQuery } from 'gatsby';
export const useSiteMetadata = () => {
const data = useStaticQuery(graphql`
query {
site {
siteMetadata {
title
description
twitterUsername
siteUrl
}
}
}
`);
return data.site.siteMetadata;
};Now, you can import and use this useSiteMetadata hook in any component to instantly get your site's title, description, and more.
2. Using the Gatsby Head API for Document Metadata 🧠
The Problem: We've got our site-wide data sorted, which is great. But what about metadata that is unique to each page? The title of your "About Me" page should be "About Me," not the generic site title. We need a way to precisely control the <head> tag for every individual page.
The Solution: Gatsby has a fantastic, built-in feature for this called the Gatsby Head API. Introduced in Gatsby v4.19.0, this is the modern, recommended way to handle page-specific head tags. It's more performant and easier to use than older solutions like react-helmet.
The Head API works by letting you export a special function named Head from your page components. Gatsby finds this function during the build process and uses whatever JSX it returns to build the final HTML <head> for that page.
How to Do It:
It's as simple as exporting a function. This Head function can even receive props from your page component, like data fetched from a GraphQL query.
Let's see it in action on a simple "About" page.
File: src/pages/about.js
import * as React from 'react';
const AboutPage = () => {
return (
<main>
<h1>About This Awesome Site</h1>
<p>Here's a little something about us.</p>
</main>
);
};
export default AboutPage;
// Here is the magic!
export const Head = () => (
<>
<title>About Us | The Great Gatsby Guide</title>
<meta name="description" content="Learn more about the team behind this amazing guide." />
</>
);Just like that, the "About" page now has its own unique title and description. Any page without a Head export will simply fall back to whatever is in your static/index.html.
3. Building a Reusable, Dynamic SEO Component ⚙️
The Problem: Using the Head API directly on every page is great, but you'll quickly notice you're writing <title> and <meta name="description"> over and over again. This violates the DRY principle (Don't Repeat Yourself). If you wanted to add a new, standard meta tag across all pages, you'd have to edit every single file. That sounds like a Friday afternoon nightmare.
The Solution: We'll create a single, reusable <Seo> component. This component will be the one-stop-shop for all our SEO needs. It will take page-specific information (like a title and description) as props, grab the site-wide defaults from our useSiteMetadata hook, and combine them to render a complete set of meta tags.
How to Do It:
First, create the component file.
File: src/components/seo.js
import React from 'react';
import { useSiteMetadata } from '../hooks/use-site-metadata';
const Seo = ({ title, description, pathname, children }) => {
const { title: defaultTitle, description: defaultDescription, siteUrl } = useSiteMetadata();
const seo = {
title: title ? `${title} | ${defaultTitle}` : defaultTitle,
description: description || defaultDescription,
url: `${siteUrl}${pathname || ``}`,
};
return (
<>
<title>{seo.title}</title>
<meta name="description" content={seo.description} />
{/* We will add more tags here in the next step! */}
{children}
</>
);
};
export default Seo;Now, let's refactor our "About" page to use this shiny new component. The Head API can render components just like any other part of React.
File: src/pages/about.js
import * as React from 'react';
import Seo from '../components/seo'; // Import the new component
const AboutPage = () => {
return (
<main>
<h1>About This Awesome Site</h1>
<p>Here's a little something about us.</p>
</main>
);
};
export default AboutPage;
// The Head export is now much cleaner!
export const Head = ({ location }) => (
<Seo
title="About Us"
description="Learn more about the team behind this amazing guide."
pathname={location.pathname}
/>
);Look how clean that is! Now we can reuse our <Seo> component on every page, just passing in the parts that are unique.
4. Implementing Open Graph and Twitter Cards for Social Sharing 🖼️
The Problem: You've written a masterpiece and you share the link on Twitter. But instead of a beautiful preview card with an image and title, you just get a plain link. Or worse, Twitter grabs a random, unflattering image from your page. This is because we haven't given social platforms the specific instructions they need.
The Solution: We need to add Open Graph (used by Facebook, LinkedIn, etc.) and Twitter Card meta tags. These are just specific <meta> tags that tell social networks exactly what title, description, and image to display in their link previews.
How to Do It:
Let's upgrade our <Seo> component to handle this. We'll add a few more props and a bunch of new meta tags.
File: src/components/seo.js (Upgraded)
import React from 'react';
import { useSiteMetadata } from '../hooks/use-site-metadata';
const Seo = ({ title, description, pathname, image, children }) => {
const {
title: defaultTitle,
description: defaultDescription,
image: defaultImage,
siteUrl,
twitterUsername,
} = useSiteMetadata();
const seo = {
title: title ? `${title} | ${defaultTitle}` : defaultTitle,
description: description || defaultDescription,
image: `${siteUrl}${image || defaultImage}`, // Make sure this is an absolute URL!
url: `${siteUrl}${pathname || ``}`,
twitterUsername,
};
return (
<>
{/* Standard SEO Tags */}
<title>{seo.title}</title>
<meta name="description" content={seo.description} />
<meta name="image" content={seo.image} />
{/* Open Graph (Facebook, etc.) */}
<meta property="og:url" content={seo.url} />
<meta property="og:type" content="website" />
<meta property="og:title" content={seo.title} />
<meta property="og:description" content={seo.description} />
<meta property="og:image" content={seo.image} />
{/* Twitter Cards */}
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:creator" content={seo.twitterUsername} />
<meta name="twitter:title" content={seo.title} />
<meta name="twitter:description" content={seo.description} />
<meta name="twitter:image" content={seo.image} />
{children}
</>
);
};
export default Seo;Notice we added a defaultImage to our siteMetadata and we're now constructing a full URL for images, which is required by these platforms.
Now when you use the <Seo> component for a blog post, you can pass in its specific featured image, and you'll get a beautiful, professional-looking social sharing card.
Fact: You can test how your links will appear and debug issues using tools like the Facebook Sharing Debugger and the Twitter Card Validator.
And that's the journey! You've gone from having no control over your site's metadata to building a powerful, reusable system for perfect SEO and social sharing. Go forth and get discovered! ✨
📚 Additional Resources
- Gatsby Documentation:
- Social Media Tools:
Challenge
Challenge Instructions
Your task is to build a reusable Seo component in React that will be used by Gatsby's Head API to manage page metadata.
This component must:
- Accept the following props:
title,description,pathname, andchildren. - Fetch site-wide metadata using the provided
useSiteMetadatahook. This hook returns an object with the following shape:{ title, description, image, siteUrl, twitterUsername }. - Merge the passed-in props with the site-wide metadata. The props passed directly to the component should take precedence over the site-wide defaults.
- Construct a final
seoobject containing the definitive values fortitle,description,image, andurl. - The
imageandurlvalues in the finalseoobject must be absolute URLs. You will need to combinesiteUrlfrom the hook with the relevant path (imagepath orpathname). - Render the following HTML tags with the correct attributes and content derived from your final
seoobject:- A
<title>element. <meta name="description" ... /><meta name="image" ... /><meta property="og:title" ... /><meta property="og:description" ... /><meta property="og:image" ... /><meta property="og:url" ... /><meta property="og:type" content="website" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:creator" ... />(usetwitterUsernamefrom the hook)<meta name="twitter:title" ... /><meta name="twitter:description" ... /><meta name="twitter:image" ... />
- A
- Render any
childrenpassed to the component.
Expected result
Your code should be a complete React component named Seo.
Inside the component, you must call the useSiteMetadata hook to get the default site data. You should then create a final seo object that merges this default data with the title and description props, giving precedence to the props. The seo object should also include an image URL and a page url, both constructed as absolute paths using the siteUrl from the hook.
The component's return statement must render a React Fragment containing a <title> tag and a series of <meta> tags. These tags must cover standard SEO (description, image), Open Graph (og:title, og:description, og:image, og:url, og:type), and Twitter Card (twitter:card, twitter:creator, twitter:title, twitter:description, twitter:image) metadata. The content attribute of each tag must be correctly populated from the final seo object. Finally, it should render the children prop.