DEV Community

Cover image for Improve SEO with Microdata on your Gatsby MDX Blog
Cesar Varela
Cesar Varela

Posted on • Originally published at cesarvarela.com

Improve SEO with Microdata on your Gatsby MDX Blog

Microdata is an essential part of improving the SEO of your blog, and if you are new to it, it might get a bit confusing. I'll try to make it a bit easier for you to get Microdata working on your blog in this post.

Thankfully, a couple of packages make creating the proper structure of the microdata for our pages more straightforward, especially if you are using typescript:

npm i schema-dts react-schemaorg
Enter fullscreen mode Exit fullscreen mode

or

yarn add schema-dts react-schemaorg
Enter fullscreen mode Exit fullscreen mode

Next, we have to add a new prop to our <Seo /> component (that comes already created with almost all Gatsby starters) to handle our new Microdata structure. I'll add it in a parameter called script:

...

export default function Seo({ title, script = [] }) {

...

return <Helmet
      title={title}
      titleTemplate={`%s | ${site.siteMetadata.title}`}

      //this is the key line
      script={[].concat(script)}
    />
}
Enter fullscreen mode Exit fullscreen mode

Then when can start adding each microdata structure to our pages and templates. For example, in my post templates, first, I'll import the helmetJsonLdProp helper and the schema type that most reflects a blog post:

import { helmetJsonLdProp } from "react-schemaorg";
import { BlogPosting } from "schema-dts";
Enter fullscreen mode Exit fullscreen mode

It's important to use the helmetJsonLdProp helper because it plays nicely with react-helmet

Then we define the actual Microdata content in the post template render, and send it to our <Seo> component:

const Post = (props) => {

  const { mdx: { body, frontmatter, parent, timeToRead, slug } } = props.data

  const jsonLd = helmetJsonLdProp<BlogPosting>({
    "@context": "https://schema.org",
    "@type": "BlogPosting",
    "headline": frontmatter.title,
    "datePublished": frontmatter.date,
    "dateModified": parent.modifiedTime,
    "author": [{
      "@type": "Person",
      "name": "Cesar Varela",
      "url": `https://cesarvarela.com/blog/${slug}`
    }]
  })

  return <Layout content={<LayoutLink to="/blog">Blog</LayoutLink>}>

    // pass the jsonLd data to our Seo component
    <Seo title={frontmatter.title} script={jsonLd} />

    /* my custom post template jsx goes here, yours will vary obsviously  */
 </Layout>
Enter fullscreen mode Exit fullscreen mode

Done! If everything worked nicely, you should see your new Microdata here. And you can read more about it here

Working example here

Top comments (0)