Challenges

Server Rendering to Static Rendering

Add Fallback 404 Page

Currently, we don't render a 404 page when we couldn't find a blog post. That's what we are doing in this step:

Replace our getStaticProps function with this:

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

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

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

It will return the post prop as null when we cannot find the blog post.

Now we need to update our Next.js page to show a 404 page. Before we do that, let's import this:

import Head from 'next/head'

Then add the following code block after we handle router.isFallback:

if (!post) {
  return (
    <Theme>
      <Head>
        <meta name="robots" content="noindex" />
      </Head>
      404 - Page not found!
    </Theme>
  )
}

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

It will show a 404 page and ask search engines to stop indexing. We do that by adding the robots meta tag.

šŸ›Žļø We haven't talked about next/head yet. But will discuss it in detail in a future lesson.
Q: Do you want some extra points?
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: