Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: getStaticPaths is required for dynamic SSG pages and is missing for "xxx". NextJS

I am getting this error "Error: getStaticPaths is required for dynamic SSG pages and is missing for 'xxx'" when I try to create my page in NextJS.

I don't want to generate any static page on build time. So why do I need to create a 'getStaticPaths' function?

like image 808
Juanma Menendez Avatar asked Jan 18 '21 22:01

Juanma Menendez


3 Answers

If you are creating a dynamic page eg: product/[slug].tsx then even if you don't want to create any page on build time you need to create a getStaticPaths method to set the fallback property and let NextJS know what to do when the page you are trying to get doesn't exist.

export const getStaticPaths: GetStaticPaths<{ slug: string }> = async () => {

    return {
        paths: [], //indicates that no page needs be created at build time
        fallback: 'blocking' //indicates the type of fallback
    }
}

getStaticPaths does mainly two things:

  • Indicate which paths should be created on build time (returning a paths array)

  • Indicate what to do when a certain page eg: "product/myProduct123" doesn't exist in the NextJS Cache (returning a fallback type)

like image 191
Juanma Menendez Avatar answered Oct 06 '22 07:10

Juanma Menendez


Dynamic Routing Next Js

pages/users/[id].js

import React from 'react'

const User = ({ user }) => {
  return (
    <div className="row">
      <div className="col-md-6 offset-md-3">
        <div className="card">
          <div className="card-body text-center">
            <h3>{user.name}</h3>
            <p>Email: {user.email} </p>
          </div>
        </div>
      </div>
    </div>
  )
}

export async function getStaticPaths() {
  const res = await fetch('https://jsonplaceholder.typicode.com/users')
  const users = await res.json()

  const paths = users.map((user) => ({
    params: { id: user.id.toString() },
  }))

  return { paths, fallback: false }
}


export async function getStaticProps({ params }) {
  const res = await fetch(`https://jsonplaceholder.typicode.com/users/${params.id}`)
  const user = await res.json()

  return { props: { user } }
}

export default User
like image 14
Felipe Corredor Avatar answered Oct 06 '22 08:10

Felipe Corredor


For rendering dynamic route use getServerSideProps() instead of getStaticProps()

For Example:

export async function getServerSideProps({
locale,
}: GetServerSidePropsContext): Promise<GetServerSidePropsResult<Record<string, unknown>>> {

return {
    props: {
        ...(await serverSideTranslations(locale || 'de', ['common', 'employees'], nextI18nextConfig)),
    },
  }
}

You can check here as well

like image 6
Khem Raj Regmi Avatar answered Oct 06 '22 07:10

Khem Raj Regmi