Challenges

Implement On Page SEO Support

Extracting Images

Usually, with Open Graph metatags, we provide an image with the meta tag with the name og:image. But we haven't included an image yet.

For a blog app, we have a few options:

  • We can use images from the Next.js public directory
  • We can use a tool like og-image to create an image for us
  • We can pick an image from the blog post content

Usually, a blog post contains at least an image or a Youtube video. So, we can try to pick an image from there.

In our case, we use Markdown, and we embed Youtube videos with the Youtube component. Here's how to find an image inside the blog post content:

Create a file called lib/find-image-in-markdown.js and add the following content:

import {compiler} from 'markdown-to-jsx'

export default function findImageInMarkdown(markdown) {
    const images = []

    compiler(markdown, {
        createElement(type, props) {
            if (type === 'img') {
                images.push(props.src)
                return
            }

            if (type === 'Youtube') {
                images.push(`https://img.youtube.com/vi/${props.videoId}/maxresdefault.jpg`)
            }
        }
    })

    return images[0] || null;
}

Now import above module inside pages/post/[slug].js with:

import findImageInMarkdown from '../../lib/find-image-in-markdown'

Then update the code in getStaticProps to have this line:

post.image = findImageInMarkdown(post.content)

That's it.


Let's verify this functionality:

  • Try to create or update an existing blog post with the following content:
This is just a video. Do not watch it:

<Youtube videoId="ut0pk7GqV0Y" />

If you are not using GitHub as a data source for your blog, your blog posts are available inside the data directory in the app root.

  • Preview the social card for the blog post or inspect metatags
Q: What's inside the Open Graph image `og:image`?
authenticating...

šŸ™ We need your help

We need your help to keep maintain & add new content to this course. Here's how you can support us: