Challenges

Implement On Page SEO Support

Create Metatags

Creating meta tags in Next.js is simple. You can use next/head to inject metatags from anywhere in your app.

Let's open pages/post/[slug].js.

Then replace the getStaticProps function with:

export async function getStaticProps({ params }) {
  let post = null

  try {
    post = await getPost(params.slug)
  } catch (err) {
    if (err.status !== 404) {
      throw err
    }
  }

  post.url = `http://localhost:3009/post/${post.slug}`
  post.summary = `${post.content.substr(0, 100)}`

  return {
    props: {
      post
    },
    revalidate: 2
  }
}

Here we added url & summary field to our the post object.

After that, add the following code before we render the blog post:

<Head>
    <title>{post.title}</title>
    <meta name='description' content={post.summary} />

    <meta name='twitter:card' content='summary_large_image' />

    <meta property='og:site_name' content='My Blog App' />
    <meta property='og:url' content={post.url} />
    <meta property='og:title' content={post.title} />
    <meta property='og:description' content={post.summary} />
    {post.image && (<meta property='og:image' content={post.image} />)}
</Head>

(Here's the final version of the file after all these changes.)

That's all you have to do. Run your app and verify these metatags.


If you are curious, you might have seen meta tags with the name twitter:card.

Q: What's that?
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: