简体   繁体   中英

NextJS: Dynamic URL get auto redirected to root url(home page)

In NextJS I've created a dynamic page to fetch and display blog content, with the following URL https://example.com/blog/[blogId]

But when I try to access the URL on production the user gets redirected to root URL(home page) instead of the blog content page.

Below is my folder structure

pages

|__ blog

   |___ [blogId].tsx

Can anyone tell me what's going wrong here? PS: Locally this is working fine.

If you want to use [blogId] as the variable part of your URL string, you have to make sure the data being served from your data source exactly matches.

getStaticPaths should generate an array of blogID in your case, something like this:

export async function getStaticPaths() {
  const pages = await getPathsForBlogs();
  return {
    paths: pages?.map(({ node }) => `/blog/${blogID}`) || [],
    fallback: false,
  }
}

In getStaticPages , you'd ingest that stack of paths and Next will generate a page at each blogID . In this example, we send the data payload back to the component on the custom param page , which you'd desconstruct in your /pages/blog.js component.

export async function getStaticProps({ params, preview = false, previewData }) {
  const pageData = await getSingleActionPage(params.blogID, previewData);

  return {
    props: {
      preview,
      page: pageData ?? null,
    },
    revalidate: 60,
  }
}

Try this

|__ blog

   |___ [blogId] // this is directory
      
      |___ index.tsx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM