Custom server not required for optional dynamic routes in NextJS version 9.5.2

I am attempting to implement localized routes with an optional first parameter in the form of /lang?/../../, all without requiring a custom server. Starting from NextJS version 9.5, there is a new dynamic optional parameters feature that can be set up by creating a folder or file named: [[...param]]. I have implemented this. The issue I am facing is that I have other existing routes and I want all of them to include the language prefix as optional, defaulting to a specified language if none is provided.

I have created a folder called [[...lang]] with an index.js file containing a simple function component for testing purposes. The optional parameter now works for the homepage / and /en. However, I also have other files like about.js which I want to be accessible with the optional language prefix, such as /en/about and /about.

I encountered an error when attempting to place about.js inside [[...lang]]:

Failed to reload dynamic routes: Error: Catch-all must be the last part of the URL.

Although I understand the reason behind this error, I have a predefined list of languages ['en', 'fr'], thus I could easily check for the presence of a language parameter.

Is there a method, without resorting to a custom server, to make use of an optionally dynamic initial path segment, such as

/en/about and /about?

Answer №2

Expanding on @Vibhav's response, the following adjustments can be made in next.config.js:

const nextConfig = {

    async rewrites(){
        return [
// URLs without a base route lang param like /my-page
            {
                source: '/',
                destination: '/'
            },
// URLs with a base route lang param like /en/my-page

            {
                source: '/:lang*/:page*',
                destination: '/:page*'
            },
// URLs `/en/post/post_id`
            {
                source: '/:lang/:path/:page',
                destination: '/:path/:page'
            },
        ]
    }
};

module.exports = withBundleAnalyzer(nextConfig);
  • All pages are located in the pages folder. This may have limitations as it only works up to a certain depth like /pages/another-folder/file.

You can also access the lang parameter in your pages or _app.js:

....
const router = useRouter();

if(router.query.lang){
    pageProps.lang = router.query.lang;
}
console.log(pageProps.lang);

return (
    <Layout>
        <Component {...pageProps} />
    </Layout>
)

For URL - /en/my-page, router.query.lang will be equal to en. For URL - /my-page, router.query.lang will be undefined, but you can set a default lang.

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

Using PHP to dynamically update image source upon clicking an upload button:

Is it possible to dynamically display a new image after uploading it using an ajax-upload script on a 'edit product' page for a shop products? On load, all thumbnails are fetched from the DB but when a user uploads a new file, I want the new imag ...

JavaScript - Navigating through JSON object in reverse (from leaf to root) direction

FamilyTree= { "name":"Family", "photo":"images/family.jpg", "members":[ { "name":"Parent", "photo":"images/parent.jpg", "relationships":[ { "name":"Spouse", "photo":"images/spouse.jpg" }, ...

What is the method for checking the pathname condition?

Hello, I am attempting to create an if statement for the pathname, but I am having trouble getting it to work properly. if (pathname == "/") { category = 'home'; pagetype = 'homepage'; } If the pathname matches "/", the script ...

Having difficulty implementing Jquery UI effects within an HTML Dialog in Google Apps Script

Looking for a scrolling effect in an HTML Dialog with Google Apps Script. I've already tried this link and placed the code in the editor. However, when highlight buttons are clicked, they work but do not cause scrolling within the HTML dialog. < ...

Bypassing the "Your connection is not private" error in NodeJS + Express with fetch() using Javascript

Presently, I have a setup with a NodeJS + ExpressJS client-side server that communicates with the back-end server via API calls. However, every time I make a call, I need to manually navigate to the URL of the API back-end server and click on Advanced -> ...

What is the correct way to dynamically switch between RTL and LTR in React with Material UI?

I recently learned that in order to support right-to-left (RTL) languages with Material UI, you need to follow these steps. I have a select input that allows users to switch between languages, changing the overall direction of the app. The core of my appl ...

Storing Images in MySQL Database with JavaScript and Node.js: A Step-by-Step Guide

I am using Javascript to capture an image and store it in a MySQL Database. Below is the code I have written for this: <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device- ...

The issue of fonts module resolution in React-Native remains unsolved

I am embarking on a basic build project using 'create-react-native-app' and yarn as the package manager. My main goal is to incorporate 'native-base' for enhancing the user interface. So far, the only addition to my app.js file is a B ...

achieving initial value to show upon page load

I'm trying to set a default value that is visible when the page loads. My goal is to have the first button always displayed by default in the "display-donation" div whenever someone visits the form. Currently, when the page loads, 10 is highlighted ...

How can a chat script be created efficiently without needing Server Root Access?

I currently have a hosting account (cPanel or DirectAdmin) where I don't have root access and am unable to use exec() or shell_exec() functions due to restrictions set by the server administrator. While I understand that socket programming is conside ...

Establish a connection between the MySql database in WHM (phpmyadmin) and a node.js application

Our team has been working on setting up the database connection with Mysql using node.js in Cpanel. Although I didn't create the database myself, I have all the necessary information such as the host, user, password, name of the database, and port nu ...

Top method for implementing select all checkboxes in a table

Hey there! I'm new to VueJS and I've been working on creating a data table component. So far, I have built two components called ui-datatable and ui-checkbox, which allow me to select all rows in the table. It's functioning perfectly fine, b ...

Specialized hover mission

Do you have a question? Imagine you have 3 spans where the default color is black. When you hover over a span, its color changes to red. But what if I told you that at the start, the first span has an orange color. Now, I want to hover over the orange on ...

Using Angular JS to manage multiple views with a single controller

Would it be considered best practice to use one controller, yet have two distinct HTML file templates that present the same data in different formats? Essentially, I require a slightly altered template for displaying content in a modal dialog and another ...

Unable to utilize a custom function within JQuery

I'm facing an issue with using the function I created. The codes are provided below and I keep encountering a "not a function error." var adjustTransparency = function () { //defining the function if ($(this).css('opacity&apo ...

Executing the `process.nextTick` function throws an error, causing the message: "Headers cannot be set once they have been sent."

I'm attempting to retrieve data from MongoDB within a Node.js file. I am encountering the following error: /home/jay/node_project/user_data_manag/node_modules/mongodb/lib/utils.js:98 process.nextTick(function() { throw err; }); Error: Can't ...

Undefined React custom hooks can be a tricky issue to troub

Just delving into the world of React and trying to wrap my head around custom hooks, but I keep hitting roadblocks. Here's the latest hurdle that I'm facing, hoping for some guidance. I'm taking a step-by-step approach to creating a functio ...

When using JQuery's :first selector, it actually chooses the second element instead of the first

I'm facing an issue with a JQuery script that makes an AJAX request to the following URL https://djjohal.video/video/671/index.html#gsc.tab=0, which holds information about a video song. My goal is to extract and retrieve all the details from the HTM ...

Filtering the data in the table was successful, but upon searching again, nothing was found. [Using Angular, Pagination, and

Having a table with pagination, I created a function that filters the object and displays the result in the table. The issue arises when I perform a new search. The data from the initial search gets removed and cannot be found in subsequent searches. Bel ...

What is the method for selecting an element using CSS code in Protractor?

Having trouble clicking on the element with CSS Selector: <button _ngcontent-c16="" class="btn btn-flat btn-no-text btn-kebab-view"> <i _ngcontent-c16="" class="zmdi zmdi-more-vert"></i> </button> This is what I've t ...