简体   繁体   中英

Next.js 404 page with i18n

I have a blog posts page where I list bunch of posts. Clicking on each of the posts leads to a [slug].js file.

The default english locale works great. However, the other locales throw 404 page when trying to open individual blog posts.

My code is below. I suspect the problem is somewhere in the next.config.js file, but I'm not sure where.

The default url works fine:

localhost:3000/blog-posts/some-blog-post

But this one throws 404:

localhost:3000/de/blogeintraege/some-blog-post

Any advice / help is appreciated!

next.config.js

module.exports = {
  basePath: '',
  reactStrictMode: true,
  i18n: {
    locales: ['en', 'de'],
    defaultLocale: 'en',
  },
  async rewrites() {
    return [
      {
        // does not handle locales automatically since locale: false is set
        source: '/de/blogeintraege',
        destination: '/blog-posts',
        locale: false,
      },
      ...
}

}

blog-posts.js

export default function BlogPosts({ children, posts }) {
    const router = useRouter();
    const { locale } = router;
    const routeTranslation = locale === 'en' ? enRoutes : deRoutes

    return (
        <div className="container p-4">
            <div className="row justify-content-center">
                {
                    posts.categories.edges[0].node.posts.edges.map(post => (
                        <div className="col-12 col-sm-10 card" key={post.node['slug']}>
                            <Link href={routeTranslation.publications + '/' + post.node['slug']} key={post.node['slug']}>
                                <div className="d-flex">
                                    <div className="mb-3">
                                        <img src={post.node['featuredImage']['node']['sourceUrl']} />
                                    </div>
                                </div>
                            </Link>
                        </div>
                    ))
                }
            </div>
        </div>
    )
}

export async function getStaticProps({locale}) {
    const where = locale === "en" ? "Publishing" : "Blogeintraege";

    const res = await fetch('https://example.com/graphql', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            query: `
              query MyQuery {
                  categories(where: {name: "${where}"}) {
                    edges {
                      node {
                        posts {
                          edges {
                            node {
                              featuredImage {
                                node {
                                  sourceUrl
                                }
                              }
                              customUrl {
                                customUrl
                              }
                              title
                              slug
                            }
                          }
                        }
                      }
                    }
                  }
                }
            `,
        })
    })

    const json = await res.json()

    return {
        props: {
            posts: json.data,
        },
    }
}

blog-posts/[blog-post].js

const BlogPost = ({ blogpost }) => {
    const router = useRouter();
    const { locale } = router;
    const translation = locale === 'en' ? en : mk;

    return (
        <div className="container p-4">
            <div className="row justify-content-center">
                <div className="col-12 card">
                    </div>
                        <div className="text-white text-break px-4 text-cms" dangerouslySetInnerHTML={{ __html: blogpost.content }} />
                </div>
            </div>
        </div>
    )
}


export async function getStaticPaths({locale}) {
    const res = await fetch('https://example.com/wp-migration/graphql', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            query: `
              query MyQuery {
                  posts(first: 100, where: {categoryName: "Publishing"}) {
                    nodes {
                      slug
                    }
                  }
                }
              `,
        })
    })

    const json = await res.json()

    return {
        paths: json.data.posts.nodes.map(blogpost  => {
            return {
                params: {
                    blogpost: blogpost.slug
                },
            };
        }),
        fallback: false,
    };
}

export async function getStaticProps({ params }) {

    const res = await fetch('https://example.comwp-migration/graphql', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            query: `
              query MyQuery {
                  postBy(slug: "${params.blogpost}") {
                    title
                    content
                    featuredImage {
                      node {
                        sourceUrl
                      }
                    }
                  }
                }
              `,
        })
    })

    const json = await res.json()

    return {
        props: {
            blogpost: json.data.postBy,
        },
    };
}

export default BlogPost

You are missing a rewrite for the [slug] route, so it doesn't register. From the NextJs documentation

I think adding this to your rewrites() in next.config will work, but wasn't able to test it myself.

      {
        source: '/de/blogeintraege/:slug*',
        destination: '/blog-posts/:slug*',
        locale: false,
      },

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