Embracing internationalization with Next.js's custom 404 page design

I created a blog posts page with multiple posts listed. Each post has an associated [slug].js file when clicked on.

While the default English locale functions correctly, other locales result in a 404 error when attempting to open individual blog posts.

Although I believe the issue lies within the next.config.js file, I'm uncertain about its exact location.

The default URL functions properly:

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

However, this URL generates a 404 error:

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

Any advice or assistance would be greatly appreciated!

next.config.js

module.exports = {
  basePath: '',
  reactStrictMode: true,
  i18n: {
    locales: ['en', 'de'],
    defaultLocale: 'en',
  },
  async rewrites() {
    return [
      {
        // Does not handle locales automatically as 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

Answer №1

The [slug] route is not properly rewritten in your configuration, causing it to not register as expected. For more information, refer to the NextJs documentation

Although I believe that including the following code snippet in your next.config file will resolve the issue, I have not been able to confirm it through testing:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The email sending feature of the ajax jquery form has unexpectedly ceased functioning

I'm encountering an issue with a form that was previously able to send emails from the server, but suddenly stopped working. I'm having trouble identifying the cause of the problem. Interestingly, when I use the form without ajax, the email funct ...

dojo.js is throwing a multipleDefine error when using qwest.js

Having some trouble loading qwest.js with the dojo (ArcGIS) AMD loader, encountering a multipleDefine error. require([ // `../vendor/react/react.js`, // this works fine `../vendor/qwest/qwest.min.js`, // this causes error ], ( // React, qwest, ) ...

Trigger Modal using PHP/JavaScript

After implementing the code below on my page, I expected guests to be redirected to the main page post login and greeted with a small pop-up modal containing a thank you message. However, despite trying multiple variations of this code, it doesn't see ...

Error: Trying to modify a property that is set as read-only while attempting to override the toString() function

I have a specific object that includes an instance variable holding a collection of other objects. Right now, my goal is to enhance this list of elements by adding a customized toString() method (which each Element already possesses). I experimented with t ...

Prevent Cordova from shrinking the view when focusing on an input

Currently working on developing an app using Cordova/Phonegap (v6.5.0). Platforms where I've installed the app: - IOS (issue identified) - Android (issue identified) - Browser (no issue found) I am facing a known problem without a suitabl ...

[next-auth] encountered an error while fetching from the Google provider: [client_fetch_error]

Hello, I need assistance with integrating Google authentication into my Next.js project. I have obtained my GOOGLE_ID & GOOGLE_SECRET from the Google console. However, when trying to implement it, I encountered the following errors in my console: http:// ...

babel-minify or terser over uglify-js

Exploring ES6+ (modern JavaScript) is a new adventure for me, and I've discovered that in order to use it in browsers, tools like babel-minify or terser are necessary. It's interesting to note that Babili was initially thought to be a separate to ...

What's preventing me from tapping on hyperlinks on my mobile device?

I'm currently working on a website (saulesinterjerai.lt) and everything seems to be functioning properly, except for the fact that on mobile devices, the links aren't clickable and instead navigates to other layers. How can I disable this behavio ...

Tips for utilizing the selected option in the name attribute with Javascript or jQuery

I am looking to use the "selected" attribute in the option element based on the name attribute using JavaScript or jQuery. Essentially, I want the option with name="1" to be automatically selected when the page loads. I have attempted the following code, b ...

What is causing XMLHttpRequest to not accept my JSON data?

I've recently created a basic PHP program that retrieves data from a database, structures it into a PHP array, and then converts it into JSON format: $i = 0; while($row = mysqli_fetch_array($result)) { $output[$i] = array(); $output[$i]["tag"] = ...

Refreshing a node in Jqgrid Treegrid by updating the local source data

I have constructed a Treegrid using local data $("#historyGrid").jqGrid({ datatype: "jsonstring", datastr : treeGridObject , colNames:["Id","Channel","Current","History","Delta"], colModel:[ {name:'id', index:'Id&apo ...

Transforming a cURL command into an HTTP POST request in Angular 2

I am struggling to convert this cURL command into an angular 2 post request curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -H "Authorization: Basic cGJob2xlOmlJelVNR3o4" -H "Origin: http://localhost:4200/form" -H "Postman-Token: fbf7ed ...

Learn to display multiple collections of data on a webpage using Node.js and MongoDB

Struggling with displaying multiple collections on my webpage. After extensive research, I keep encountering an error message saying "Failed to look up view in views directory." Here is the code snippet causing the issue: router.get('/', functio ...

The automated linting process through npm script did not meet the desired expectations

I need help setting up a script that will automatically fix all files in my Vue project like this: "lint": "eslint --fix vue/**/*.vue && eslint --fix vue/**/*.js" The goal is to automatically lint all .vue and .js files within the project. Unfor ...

Vue JSON Response Guide

Inquiry from a beginner. My goal is to display the name of a city using props. When I use {{ props.feed.location }} to fetch: { "latitude": 50.85, "longitude": 4.35, "name": "Brussels, Belgium", "id": 213633143 } However, when I attempt {{ props.feed.l ...

Is it possible to create a unique AJAX function for a button element within a table?

Using an ajax function, I am populating a table with data from a PHP file that returns JSON encoded data. Each row in the table includes data as well as three buttons for delete, edit, and save operations specific to that row. The issue arises when I atte ...

Implementing Flash Messages with jQuery AJAX for Every Click Event

I've been working on integrating Ajax and PHP, successfully fetching data from the database. However, I'm facing an issue where the Ajax response is only displayed in the HTML for the first click. What I actually want is to show a "success/error" ...

Question on AJAX and asp.net security aspects

Questions arise about security measures in asp.net (2.0). Traditionally, I have utilized Forms authentication along with Page.User to verify permissions. However, I now find myself needing to transfer data from client-side javaScript (jQuery) to a WCF se ...

What is the best way to extract the src attribute from an image tag nested within innerHtml?

In the developer tools, navigate to console and enter: var x= document.getElementsByClassName('ad-area')[0].innerHTML; x returns: '<a href="/members/spotlight/311"><img class="block-banner" src="https://tes ...

Adjust the button's background hue upon clicking (on a Wix platform)

I need some help with customizing the button "#button5" on my Wix website. Here are the conditions I'd like to apply: Button color should be white by default; When the user is on the "contact" page, the button color should change to red; Once the use ...