Currently, I am utilizing NextJs
version 10.0.5 in conjunction with next-i18next
version 8.1.0 to localize my application. With the introduction of subpath routing for internationalized routing in NextJs
10, I encountered a situation where I needed to modify page names based on language preferences. For instance, within the pages folder, there exists a file named contact-us
. When switching the language to Turkish, the URL would typically be localhost:3000/tr/contact-us
. However, I aimed to access the same contact-us
page using the URL localhost:3000/bize-ulasin
when the language is set to Turkish.
I managed to achieve this through custom routing in express js implemented in the server.js file. Despite the success of implementing custom routes, I encountered a challenge when attempting to retrieve the "locale" variable within the getStaticProps
function located in the contact-us
file. It appears that the getStaticProps
method returned an undefined value for the "locale" variable specifically when accessing the URL localhost:3000/bize-ulasin
.
server.js
const { createServer } = require("http");
const { parse } = require("url");
const next = require("next");
const app = next({ dev: process.env.NODE_ENV !== "production" });
const handle = app.getRequestHandler(app);
app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true);
const { pathname, query } = parsedUrl;
if (pathname === "/bize-ulasin") {
app.render(req, res, "/contact-us", query);
}else{
handle(req, res, parsedUrl);
}
}).listen(3000, (err) => {
if (err) throw err;
console.log("> Ready on http://localhost:3000");
});
});
/pages/contact-us-file
import { Fragment } from "react";
import Head from "next/head";
import { useTranslation } from "next-i18next";
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
const ContactUs = () => {
const { t } = useTranslation("common");
return (
<Fragment>
<Head>
<title>Contact-Us</title>
</Head>
</Fragment>
);
};
export const getStaticProps = async ({ locale }) => {
console.log(locale); // Returns undefined when using the URL localhost:3000/bize-ulasin.
return {
props: {
...(await serverSideTranslations(locale, ["common"])),
},
};
};
export default ContactUs;
My primary concern revolves around accessing the "locale" variable within the getStaticProps function. Moreover, I seek insights into how to leverage the following URLs while utilizing the same page file:
->localhost:3000/contact-us
->localhost:3000/bize-ulasin