I have a strange bug with Next i18Next just in production. Here are some images that can describe better the issue.
Here on localhost, the home page link
And then on search page
Here on production, home page
And then the search page on production
i18n.js
const NextI18Next = require('next-i18next').default;
const { localeSubpaths } = require('next/config').default().publicRuntimeConfig;
const path = require('path');
module.exports = new NextI18Next({
otherLanguages: ['fr_BE', 'nl_BE'],
defaultLanguage: 'en',
ns: ['common'],
defaultNS: 'common',
strictMode: false,
browserLanguageDetection: false,
serverLanguageDetection: false,
localePath: path.resolve('./public/static/locales'),
localeSubpaths
});
next.config.js
const { nextI18NextRewrites } = require('next-i18next/rewrites');
const localeSubpaths = {
en: 'en',
fr_BE: 'fr_BE',
nl_BE: 'nl_BE'
};
module.exports = {
// experimental: {
// reactMode: 'concurrent'
// },
reactStrictMode: true,
publicRuntimeConfig: {
localeSubpaths
},
rewrites: async () => nextI18NextRewrites(localeSubpaths)
};
Thank you all for your attention and your help.
Related
I am using nx.dev for maintaining monorepo, my project demands MFE with Nextjs.
Following #module-federation/nextjs-mf it says it is moved to paid plugin, still i want some solution with open code (without #module-federation/nextjs-mf plugin).
I tried to configure webpack property for ModuleFedration which is generating remoteEntry file. but still it is not getting in my browser network calls.
How can i make it available for public access ?
I tried to change the publicPath for webpack, but still it is same.
next.config.js
// eslint-disable-next-line #typescript-eslint/no-var-requires
const withNx = require('#nrwl/next/plugins/with-nx');
/**
* #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,
},
distDir: 'build',
webpack:(config, options) =>{
config.plugins.push(
new options.webpack.container.ModuleFederationPlugin({
name:"fe2",
filename:'remoteEntry_2.js',
remoteType:"var",
exposes:{
"./remote2":"./components/hello.tsx"
},
shared:[
{
react: {
eager: true,
singleton: true,
requiredVersion: false,
}
},
{
"react-dom": {
eager: true,
singleton: true,
requiredVersion: false,
}
}
]
})
)
return {
output: {
...config.output,
publicPath: 'http://localhost:4002/',
},
...config
};
}
};
module.exports = withNx(nextConfig);
remoteEntry is getting generated in build dir
RemoteEntry is not there in browser's network
I am a bit in the same case as you, was not understanding why it's not showing up on the network.
When running the nextjs app, you cannot access static that are directly on you build folder output, you have to put them in the static folder of your output folder (that was my conclusion)
Here how the nextjs configs looks
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
productionBrowserSourceMaps: true,
distDir: 'build',
webpack: (config, context) => {
return {
...config,
experiments: {
...config.experiments,
topLevelAwait: true,
},
plugins: config.plugins.concat(
new context.webpack.container.ModuleFederationPlugin({
name: 'microfrontend',
filename: 'static/chunks/remotes.js', // this is where the magic happen
remoteType: 'var',
exposes: {
// expose all component here.
'./component1': path.resolve(process.cwd(), './src/components/component1'),
'./component2': path.resolve(process.cwd(), './src/components/component2'),
},
shared: {
react: {
singleton: true,
strictVersion: true,
eager: true,
requiredVersion: dependencies.react,
},
'react-dom': {
singleton: true,
strictVersion: true,
eager: true,
requiredVersion: dependencies['react-dom'],
},
...deps, // coming from a script outside
},
}),
),
};
},
};
in my host app i can then target
${process.env.REMOTE_URL}/static/chunks/remotes.js.
I stil have some issues going on but it seems linked to my remote and its dependencies.
I hope it helps a bit !
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',
},
]
}
}
I have added the app next-i18next for internationalisation. After that, all pages in vercel become 404 pages.
By the way, it works perfectly in locally.
WHY??
const { i18n } = require("./next-i18next.config");
module.exports = {
i18n: {
locales: ["en", "fr", "nl-NL", "nl-BE", "de", "ja"],
defaultLocale: "ja",
https://skripts.vercel.app/
Above is the URL of my site. There is a this error in the log.
Failed to load resource: the server responded with a status of 500 ()
Maybe you need to add "getStaticProps" to Dynamic Routing Pages?
// pages/blog/[slug].js
export const getStaticPaths = ({ locales }) => {
return {
paths: [
// if no `locale` is provided only the defaultLocale will be generated
{ params: { slug: 'post-1' }, locale: 'en-US' },
{ params: { slug: 'post-1' }, locale: 'fr' },
],
fallback: true,
}
}
This described here:
https://nextjs.org/docs/advanced-features/i18n-routing#dynamic-routes-and-getstaticprops-pages
I have React + Next.js + next-i18next + Vercel application. And when I deployed to the Vercel I start getting an errors in console:
Internal Server Error 500 with all *.json files.
I just added "locale" keys->values and this is solve my problem.
SOLVED
Please read https://github.com/i18next/next-i18next#vercel-and-netlify this will solve all the problemas
const path = require('path');
module.exports = {
i18n: {
defaultLocale: 'en',
locales: ['en', 'es'...],
},
...(typeof window === undefined
? { localePath: path.resolve('./public/locales') }
: {}),
};
code by #stophecom
It happened to me and the only solution that I found is to generate all the pages (4000), almost 20 minutes to do a deploy :(
const getStaticPaths = async () => {
const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/xxx`);
const projects = await res.json();
const slugs = projects.map((p) => slugifyForFront(p.slug));
const { locales } = i18n;
const paths = slugs.flatMap((slug) =>
locales.map((locale) => ({
params: { slug },
locale: locale,
}))
);
return { paths, fallback: false };
};
Probably is not the best solution but I could not make it work using fallback: true | blocking always 404
I hope some one post a better solution
I'm following Microsoft's Tutorial:
Deploy static-rendered Next.js websites on Azure Static Web Apps
The problem is, I'm trying to add to my next.config.js file this code:
const data = require('./utils/projectsData');
module.exports = {
trailingSlash: true,
exportPathMap: async function () {
const { projects } = data;
const paths = {
'/': { page: '/' },
};
projects.forEach((project) => {
paths[`/project/${project.slug}`] = {
page: '/project/[path]',
query: { path: project.slug },
};
});
return paths;
},
};
but my next.config.js already has some existing content:
require('dotenv').config()
const withFonts = require('next-fonts')
module.exports = withFonts({
serverRuntimeConfig: {},
trailingSlash: true,
exportPathMap: function() {
return {
'/': { page: '/' }
};
},
publicRuntimeConfig: {
API_URL: process.env.API_URL,
PORT: process.env.PORT || 3000,
PUBLISHABLE_KEY: process.env.PUBLISHABLE_KEY,
},
})
how can I combine them?
Just combine them like that?
require('dotenv').config()
const data = require('./utils/projectsData'); // Add this line
const withFonts = require('next-fonts')
module.exports = withFonts({
serverRuntimeConfig: {},
trailingSlash: true,
// And override this key
exportPathMap: async function () {
const { projects } = data;
const paths = {
'/': { page: '/' },
};
projects.forEach((project) => {
paths[`/project/${project.slug}`] = {
page: '/project/[path]',
query: { path: project.slug },
};
});
return paths;
},
publicRuntimeConfig: {
API_URL: process.env.API_URL,
PORT: process.env.PORT || 3000,
PUBLISHABLE_KEY: process.env.PUBLISHABLE_KEY,
},
})
I tried to find a way to change the language by changing the site's sub-path in the next-i18next package, I searched the Internet (https://github.com/isaachinman/next-i18next/issues/32 , https://github.com/i18next/i18next-browser-languageDetector#detector-options) for an answer to this question, but it did not work. After changing the subpath in the url it is duplicated and redirects me to a page that does not exist.
my code:
// path-to-my-project/i18n.js
const NextI18Next = require('next-i18next').default;
const i18nextBrowserLanguageDetector = require('i18next-browser-languagedetector').default;
const { localeSubpaths } = require('next/config').default().publicRuntimeConfig;
const path = require('path');
module.exports = new NextI18Next({
otherLanguages: ['ru'],
defaultNS: 'common',
localeSubpaths,
localePath: path.resolve('./public/static/locales'),
use: [i18nextBrowserLanguageDetector],
});
// path-to-my-project/pages/_app.js
import '../styles/main.scss';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import Router from 'next/router';
import App from 'next/app';
import { appWithTranslation } from '../i18n';
Router.events.on('routeChangeStart', () => NProgress.start());
Router.events.on('routeChangeComplete', () => NProgress.done());
Router.events.on('routeChangeError', () => NProgress.done());
const MyApp = ({ Component, pageProps }) => (
<Component {...pageProps} />
);
MyApp.getInitialProps = async (appContext) => ({ ...await App.getInitialProps(appContext) });
export default appWithTranslation(MyApp);
maybe I just missed something, because it's my first project on next.js, so I'm asking for help in the community and would be grateful for any help or hint.
By default next-i18next will try to detect the language to show from users browser.
Try to disable it.
const NextI18Next = require('next-i18next').default
const { localeSubpaths } = require('next/config').default().publicRuntimeConfig
const path = require('path')
module.exports = new NextI18Next({
browserLanguageDetection: false, // <---
serverLanguageDetection: false, // <---
otherLanguages: ['de'],
localeSubpaths,
localePath: path.resolve('./public/static/locales')
})
in file next.config.js i have this settings:
// path/to/project/next.config.js
const { nextI18NextRewrites } = require('next-i18next/rewrites');
const localeSubpaths = {
ru: 'ru',
};
module.exports = {
rewrites: async () => nextI18NextRewrites(localeSubpaths),
publicRuntimeConfig: {
localeSubpaths,
},
devIndicators: {
autoPrerender: false,
},
};
but there was not enough configuration for English localization, so you just need to add it:
// path/to/project/next.config.js
const { nextI18NextRewrites } = require('next-i18next/rewrites');
const localeSubpaths = {
en: 'en', // <------
ru: 'ru',
};
module.exports = {
rewrites: async () => nextI18NextRewrites(localeSubpaths),
publicRuntimeConfig: {
localeSubpaths,
},
devIndicators: {
autoPrerender: false,
},
};