Remove language from URL in Next JS dynamic routes - next.js

I have a website in NextJS with next-i18next, and every page must be translated except for the legal pages.
These legal pages are in markdown, and I have dynamic routing enabled thanks to a [legal].js page and the getStaticPaths and getStaticProps in it.
The problem is that by building my website, my legal pages are prefixed with the language (here en). I would like to remove it as I don't want these pages to be translated.
What am I doing wrong here?
Thanks a lot 🙏
Folder structure:
pages
|- index.js
|- [legal].js
|- privacy-policy.mdx
next-i18next.config.js
module.exports = {
i18n: {
defaultLocale: 'en',
locales: ['en'],
fallbackLng: 'en',
defaultNS: ['homepage', 'header', 'footer'],
localeDetection: false,
},
}
[legal].js
import matter from 'gray-matter'
import ReactMarkdown from 'react-markdown'
import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
import glob from 'glob'
const LegalPage = ({ markdownBody }) => (
<ReactMarkdown>{markdownBody}</ReactMarkdown>
)
export async function getStaticProps({ locale, params }) {
const { legal } = params
const content = await import(`./${legal}.mdx`)
const data = matter(content.default)
return {
props: {
...(await serverSideTranslations(locale, ['header', 'footer'])),
markdownBody: data.content,
},
}
}
export async function getStaticPaths() {
const blogs = glob.sync('src/pages/**/*.mdx')
const blogSlugs = blogs.map(file => {
const parts = file.split('/')
return parts[parts.length - 1].replace('.mdx', '')
})
const paths = blogSlugs.map(slug => ({
params: { legal: slug },
}))
return {
paths,
fallback: false,
}
}
export default LegalPage
build output:

All static HTML files should be created in separate folders for each locale.
Your default locale can be omitted in the URL, and the following URLs are equivalent:
example.com/my-first-blog
example.com/en/my-first-blog
🎈 As a solution, you can setup app i18n base on domain:
module.exports = {
i18n: {
locales: ['en'],
defaultLocale: 'en',
domains: [
{
domain: 'example.com',
defaultLocale: 'en',
},
]
}
}

Related

nextjs dynamic routes doesn't work with next-i18next

I just added next-i18next in my nextjs project following the official guide and everything seemed to be in order, but when I change the language from default (Italian) to English and I go to the detail of an entity then I get 404. This happens only with the dynamic routes and only with the language that is not the default one.
I am going to show you more details.
My next-i18next.config.js file:
module.exports = {
i18n: {
defaultLocale: "it",
locales: ["it", "en"],
},
};
[id].tsx
//My NextPage component...
export async function getStaticPaths() {
const paths = await projects.find()?.map((_project) => ({
params: { id: _project.id + "" },
}));
return {
paths,
fallback: false,
};
}
export async function getStaticProps({
locale,
...rest
}: {
locale: string;
params: { id: string };
}) {
const project = await projects.findOne({id: rest.params.id})
const seo: Seo = {
//...
};
//This row is not the problem, since it persists even if I remove it. Also I am sure that the project exists.
if (!project?.id) return { notFound: true };
return {
props: {
...(await serverSideTranslations(locale, [
"common",
"footer",
"projects",
])),
seo,
project,
},
};
}
index.tsx (under projects folder)
const Projects: NextPage<Props> = ({ /*...*/ }) => {
//...
const router = useRouter();
return <button onClick={() =>
router.push({
pathname: `/projects/[slug]`,
query: { slug: project.slug },
})
}>Read more</button>
}
Also I get the error Error: The provided 'href' (/projects/[slug]) value is missing query values (slug) to be interpolated properly. when I try to change the language while I am in the detail of the project with the italian language set, but I think I did it right according to this doc. As I said before, instead, if I try to go into the dynamic route after having changed the language to "en" then I go to 404 page.
Do you have any suggestions to solve this problem?
I solved this by updating the mothod getStaticPaths to:
export async function getStaticPaths({ locales }: { locales: string[] }) {
const projects = getProjects({ locale: "it" });
const paths = projects.flatMap((_project) => {
return locales.map((locale) => {
return {
params: {
type: _project.slug,
slug: _project.slug,
},
locale: locale,
};
});
});
return {
paths,
fallback: true,
};
}
So there must be passed the locale into the paths.

NextJS ServerSideProps translation don't work properly in dynamic routes

Hi everyone I have a NextJS app ( main host ) inside a NX Project.
I have the need to translate the pages inside the app, and i'm using next-i18next package installed.
I have several dynamic pages like:
pages
|- projects
| |- index.js
| |- [id]
| | | - index.js
|
| index.js
| _app.js
And locally everything works just fine, but when I deploy to Vercel the translations inside the dynamic pages don't work.
I really don't understand why it's happening, one solution I've found was to transform all dynamic rendered pages into static ones, but this is not possible since new ids are generated during the usage of the application.
Packages I'm using:
"i18next": "^22.0.6",
"next": "13.0.0",
"next-i18next": "^13.0.0",
Code inside dynamic route:
export async function getServerSideProps({ locale }) {
return {
props: {
...(await ssrTranslations(locale, [
'projects',
'shared',
'newgateway-file',
'gatewaysummary',
])),
},
};
}
Next-i18next.config.js
module.exports = {
i18n: {
defaultLocale: 'en',
locales: ['en', 'it', 'de', 'es', 'fr', 'ja'],
},
defaultNs: 'shared',
fallbackLng: { default: ['en'] },
localePath: 'apps/host/public/locales'
};
Next.config.js
const { withNx } = require('#nrwl/next/plugins/with-nx');
const { i18n } = require('./next-i18next.config');
/**
* #type {import('#nrwl/next/plugins/with-nx').WithNxOptions}
*
**/
const nextConfig = {
nx: {
// Set this to true if you would like to to use SVGR
// See: https://github.com/gregberge/svgr
svgr: false,
},
reactStrictMode: true,
swcMinify: true,
i18n,
};
module.exports = withNx(nextConfig);

next-i18next fail to load locales from public folder

I migrated to next.js and started to use next-i18next. I would like to know, how to make next-i18next load locales from the public folder? It works only when I place the locales folder in the root directory not in public.
i18n.json ;
{
"locales": ["en", "fr", "ar"],
"defaultLocale": "en",
"pages": {
"*": ["common"]
}
}
next.config.js ;
// next.config.js
const nextTranslate = require("next-translate");
module.exports = {
...nextTranslate(),
};
Create i18n.js file root add this code inside:
const path = require('path');
module.exports = {
i18n: {
locales: ['en', 'ru', 'tm'],
defaultLocale: 'en',
localeDetection: false,
localePath: path.resolve('./public/locales'),
},
};
and add config next.config.js file this:
const { i18n } = require('./i18n');
const nextConfig = {
reactStrictMode: true,
i18n,
};
module.exports = nextConfig;
after every page add transalition code. example: index.file
import React, { useContext, useEffect } from 'react';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import { useTranslation } from 'next-i18next';
import Router from 'next/router';
import { Title } from '../components';
import i18n from '../i18n';
const Home = () => {
const { t } = useTranslation('');
useEffect(() => {
if (!user) {
Router.push('/login');
}
});
return (
<>
<Title title={`${t('page.home')} | Trillo`} />
<div className="min-h-screen">Home</div>
</>
);
};
export const getServerSideProps = async ({ locale }) => (
{ props: {
...(await serverSideTranslations(
locale,
['common'],
i18n,
)),
} }
);
export default Home;
After you create these files inside public folder like this. see this and see this 2

Next.js middleware get available locales

i created i18n.json
i18n.json
{
"locales": ["en-US", "tr-TR"],
"defaultLocale": "tr-TR",
"defaultNS": "common",
"pages": {
"*": ["common"]
}
}
i want to get locales ["en-US", "tr-TR"] values in _middleware.tsx
i created _middleware.tsx and
I have read the directions in this document
https://nextjs.org/docs/api-reference/next/server#nextrequest
nextUrl includes i18n
so i want to reach locales in i18n object but I get undefined value.
import { NextResponse, NextRequest } from "next/server";
export async function middleware(req: NextRequest) {
const { i18n } = req.nextUrl;
const { locales } = i18n;
console.log(locales);
return NextResponse.next();
}
How can I get the available locales values?
I'm not quite sure why you need middleware for this case, you can get all locales from the SSR props, but you need to configure
First, you need to define your locales in next-18next.config.js
module.exports = {
i18n: {
defaultLocale: "de",
locales: ["de", "en"],
},
};
Then in next page get all locales with SSR Props
export const getServerSideProps: GetServerSideProps = async ({ locales }) => {
console.log(locales) // You should get an array of all locales
}
For now, best way to do this is importing next-i18next.config.js manually.
next-i18next.config.js
module.exports = {
i18n: {
defaultLocale: "en",
locales: ["en", "tr"],
localeDetection: false,
},
};
middleware.js
import { i18n } from "./next-i18next.config.js";
export function middleware(req) {
const availableLocales = i18n.locales;
}
You can import your i18n.json to achieve same.

next-i18next is not working with serversideprops in dynamic pages after deploying on vercel

I'm using next-i18next module for multilingual support.
I have some static pages and dynamic pages as well. both working fine on local.
I deployed all static pages on vercel, all worked fine on vercel. But dynamic page is not working on vercel. it shows 404 page for that dynamic page.
Below is the code of the dynamic page. (pages/test-page/[questionId].js)
import { useState, useEffect } from "react";
import {Layout} from "#components/common";
import { useRouter } from 'next/router';
import { useTranslation } from 'next-i18next'
import { serverSideTranslations } from 'next-i18next/serverSideTranslations'
import { TestComponent } from '#components/TestComponent'
const TestPage = () =>
{
const { t } = useTranslation('common')
const router = useRouter()
const {questionId} = router.query;
const [isApiLoaded,setIsApiLoaded] = useState(false)
return (
<TestComponent
t={t}
isApiLoaded={isApiLoaded}
setIsApiLoaded={setIsApiLoaded}
/>
)
}
TestPage.Layout = Layout
export const getServerSideProps = async ({ locale }) => ({
props: {
...(await serverSideTranslations(locale, ['home', 'common']))
}
});
export default TestPage;
How to fix this issue?
Adding localePath in next-i18next.config.js did help in my case.
const path = require('path')
module.exports = {
i18n: {
defaultLocale: 'en',
locales: ['en', 'de'],
localePath: path.resolve('./public/locales')
}
};
I was facing the same issue and for a temporary fix I used the i18n object from next-i18next that has a function called getResource that gets the current locale with its translations
// import { i18n } from 'next-i18next';
// import { useRouter } from 'next/router';
const [translation, setTranslation] = useState({});
useEffect(() => {
const bundle = i18n.getResource(locale, 'common');
setTranslation(bundle);
}, []);
And to avoid rewrite the code with the t function, you could use
// LINK https://stackoverflow.com/a/43849204/14263138
const t = (word) => word
.split('.')
.reduce((p, c) => (p && p[c]) || null, translation);
With this applied, you don't need to use the getServerSideProps
Although the post is now old, I share the solution that solved the problem in my project (focus on the addition of localePath):
const path = require('path');
module.exports = {
i18n: {
defaultLocale: 'en',
locales: ['en', 'it', 'de', 'es', 'fr', 'ja']
},
defaultNs: 'shared',
fallbackLng: { default: ['en', 'it', 'de', 'es', 'fr', 'ja'] },
localePath: path.resolve('./public/locales'),
};
I specify that localePath should not be included among the properties of i18n as indicated in another answer as doing so produces a type error.
Also make sure to use getServerSideProps and not getStaticProps on pages, for example:
export async function getServerSideProps({ locale }) {
return {
props: {
...(await ssrTranslations(locale, ['login', 'shared'])),
},
};
}
Import the serverSideTranslations
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
Now from the getServerSideProps, pass the ..(await serverSideTranslations(locale, ["common"])), with the props.
export const getServerSideProps: GetStaticProps = async ({
locale,
locales,
query
}: any) => {
return {
props: {
...(await serverSideTranslations(locale, ["common"])),
}
}
};
Now add your language strings inside
/public/locales/en/common.json
For example
{
"home": {
"Test": "Test"
}
}
You can add more language strings inside the locales directory.
Restart your Next.js app. It will work.

Resources