Nextjs keep redirecting with double locale - reactjs

We trying to redirect client if client's wish locale is not provided in the page.
So i added
redirect: !isPossibleLang
? {
destination: `/${locale}/main/${id}`,
statusCode: 301,
}
: undefined,
In the return of getStaticProps.
But next.js keep adding current language in the url.
like /ko/main/ID => /en/ko/main/ID
My next.config.js
module.exports = {
reactStrictMode: true,
i18n: {
locales: ['en', 'ko'],
defaultLocale: 'ko',
},
...
};
How to stop redirect with double locale ?

I advise you to include more code in the question, without giving readers undefined variables or without context. To help us better understand the problem and help you.
In my opinion you are passing unnecessarily the locale variable in the template string.
Maybe this is better like a comment but have no allow to comment yet.

Related

Is it possible to rewrite the route of a static .txt file in Next.js

I have a Next.js application which has a robots-staging.txt file in the root of the public folder. I'm looking to add this to the rewrites function in next.config. This is what I have
async rewrites() {
const rewriteList = [
{
source: '/robots-staging.txt',
destination: '/robots.txt',
},
];
return rewriteList;
},
My initial expectation was that when I hit localhost:3000/robots.txt this would serve the staging file, however it's not working. Am I missing something?
If I understood correctly that you want to proxy /robots.txt to /robots-staging.txt, you need to make the latter the destination and not the source.
Besides that, I've experienced the same issue, and I'm not sure if this is a bug or a feature, but I found that using absolute paths/URLs works as a workaround as relative paths seem to be interpreted as pages:
async rewrites() {
{
source: "/robots.txt",
destination:
process.env.NODE_ENV === "development"
? "http://localhost:3000/robots-staging.txt"
: "https://YOUR_URL/robots-staging.txt",
},
];
},

Gatsby V4: How to implement gatsby-plugin-react-i18next for client only routes

I'm trying to implement client routes in Gatsby together with gatsby-plugin-react-i18next for two languages. I followed officel Gataby documentation and there is no client only path implementation explained.
Below is the code i implemeted.
gatsby-node.js
function langPrefix(page) {
return page.context.language === page.context.i18n.defaultLanguage &&
!page.context.i18n.generateDefaultLanguagePage
? ''
: `/${page.context.language}`
}
exports.onCreatePage = ({ page, actions }) => {
const { createPage } = actions
// Removing the ^ skips an optional /:lang prefix
if (page.path.match(/\/app/)) {
// adding lang if it's not the default page.
page.matchPath = `${langPrefix(page)}/app/*`
createPage(page)
}
}
Appjs
src/app/app.js
function App() {
return (
<>
<Router basepath="/:lang/app">
<PrivateRoute path="/accounthome" component={AccountHome} location=""/>
</Router>
<Router basepath="/app">
<PrivateRoute path="/accounthome" component={AccountHome} location=""/>
</Router>
</>)
}
export default App
Gatsby config
{
resolve: `gatsby-plugin-react-i18next`,
options: {
localeJsonSourceName: `locale`, // name given to `gatsby-source-filesystem` plugin.
languages: ["en", "fr"],
defaultLanguage: `en-us`,
fallbackLanguage: `en-us`,
// if you are using Helmet, you must include siteUrl, and make sure you add http:https
siteUrl: `https://my.costco.com/`,
ns: langTranslationConfig,
// you can pass any i18next options
i18nextOptions: {
interpolation: {
escapeValue: false // not needed for react as it escapes by default
},
nsSeparator: false
},
pages: [
{
matchPath: '/:lang/app/accounthome',
getLanguageFromPath: true,
excludeLanguages: ['en-ca']
},
{
matchPath: '/preview',
languages: ['en']
}
]
}
}
Router path : http://localhost:8000/en-us/app/accounthome
When am accessing this rote in browser This code show Gatsby.js development 404 page not found. Any pointer what am missing and am not sure how to access the translation contents in client only route page example account home page. Do i need to write the graph query in account home page or i dont need to ?
I think your regex is leaking your code. I guess it should look like:
if (page.path.match(/^\/app/)) {
page.matchPath = `${langPrefix(page)}/app/*`
createPage(page)
}
Either way, check the created page list by accessing the 404 page in development mode. By default, there should be a list of all created pages. Check the paths there to see if you can spot any mistakes or trailing slash issues.
The problem here is that your page is not being generated properly, that's why it throws a 404, so checking the created pages may help you to spot the mistake or at least, a thread to pull.
After a few research I've seen that you are basing your approach in: Gatsby can't find client routes when using gatsby-plugin-react-i18next
In their case, the langPrefix function is only prefixing the language to the page slug if it's the default one:
function langPrefix(page) {
return page.context.language === page.context.i18n.defaultLanguage &&
!page.context.i18n.generateDefaultLanguagePage
? ''
: `/${page.context.language}`
}
In your case, I'm not sure the plugin supports en-us (it's en-US according to https://github.com/microapps/gatsby-plugin-react-i18next/issues/100) and I think that's the reason why there's a leak in your page creation. Try using en instead of en-us or directly looking for en-US paths.

Next.js next-i18next is always routing to EN

I have a simple project that supposed to work with English and Dutch(default). I have copied everything from the original example but somehow it doesn't work as expected.
Even though I have browserLanguageDetection: false, it is forcing me to /enendpoint.
I would like to show the NL text on / but currently I couldn't.
Could you please check the sandbox and tell me what is wrong here?
https://codesandbox.io/s/pensive-galileo-zifjm?file=/pages/index.js
There is solution in the docs. Here it is: https://nextjs.org/docs/advanced-features/i18n-routing
As I found out from the docs you should declare localeDetection: false then you should declare your own domain paths. It will work.
i18n: {
defaultLocale: 'en',
locales: ['en'],
localeDetection: false, // Important!
domains: [
{
domain: 'example.com', // <-
defaultLocale: 'en' // This locale will be appeared at the exact above domain.
},
{
// 2nd locale goes here in the same way.
}
]
}
I hope, it helps.
It is important to know that in Next.js, the first loading is always done on the server side. In i18n.js you have defined browserLanguageDetection: false but you have not defined serverLanguageDetection: false that's why you are always redirected to /en
In the index page, replace this line export default withTranslation('common')(IndexPage); with this one export default withTranslation(['common'])(IndexPage); to avoid this warning

Got an error Invalid src prop ('here is a link') on `next/image`, hostname "localhost" is not configured under images in your `next.config.js`

I am using the Image component from Next.js (it's a new feature of Next.js). I've tried to give the source URL:
{`${API}/user/photo/${blog.postedBy.username}`}
But it shows me this error. I also make changes in my next.config.js as
module.exports = {
images: {
domains: ['localhost'],
},
}
but nothing works for me. Please help if you know anything about this.
const src = `${API}/user/photo/${blog.postedBy.username}`;
<Image loader={() => src} src={src} width={500} height={500}/>
Here, loader is a function that generates the URLs for your image. It appends a root domain to your provided src, and generates multiple URLs to request the image at different sizes. These multiple URLs are used in the automatic srcset generation, so that visitors to your site will be served an image that is the right size for their viewport.
Edit next.config.js :
module.exports = {
reactStrictMode: true,
images: {
domains: ['example.com'],
},
}
Yes, I finally got the answer. Make loader function to load it from the destination of the image.
const myLoader=({src})=>{
return `${API}/user/photo/${blog.postedBy.username}`;
}
Use this loader function the loader attribute of an Image tag.
<Image loader={myLoader} src={`${API}/user/photo/${blog.postedBy.username}`} width={500}
height={500}/>
This works for me perfectly
I had the same issue, You need to restart your dev server, you need to do that each time you make changes on your next.config.js file.
The API string should include the port. e.g. localhost:3001
There are a whole bunch of out-of-date answers here that suggest setting the domains key in next.config.js. As of Next 12.3.0 this is no longer correct; see: https://nextjs.org/docs/messages/next-image-unconfigured-host
Instead, one should use a remotePatterns property, which is a little more complicated than the old domains:
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'example.com',
port: '',
pathname: '/account123/**',
},
],
},
}
Inside next.config.js file.
Add Image src domain name:
const nextConfig = {
reactStrictMode: true,
images : {
domains : ['sangw.in', 'localhost', 'picsum.photos'] // <== Domain name
}
}
module.exports = nextConfig
Adding 'localhost' in the domains array will fix the issue,
Unfortunately nextJS didn't refresh the server automatically after configuration file(next.config.js) change.
You have to restart the server manually to reflect the changes.
You can also try by set reactStrictMode value reactStrictMode: true,
here is the full export object
module.exports = {
reactStrictMode: true,
images: {
domains: [
"localhost",
process.env.WORDPRESS_API_URL.match(/(http(?:s)?:\/\/)(.*)/)[2], // Valid WP Image domain.
"2.gravatar.com",
"0.gravatar.com",
"secure.gravatar.com",
],
},
};
First of all add and restart the dev server.
domains: ['localhost']
And be sure to return the image link with http(s) protocole
image link with localhost:port/... is wrong , return as http://localhost/... ( or with https )
I've faced the same issue, and my domains were correct. Deleting .next and node_modules folders, and running yarn/npm install fixed the issue.
For me, in next.config.js,
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
images: {
domains: [ "abc.def.org", ]
},
}
module.exports = nextConfig
and then in my Image tag
<Image
unoptimized // for image caching, else error
src={profile.picture}
alt={profile.picture || "IMG"}
width={60}
height={60}
/>

404 for all routes with included locale - NextJS with next-i18next

Hi I am following the docs from here: github docs
, but all URLs with locales return 404.
For the example:
localhost:3000/de/second-page = 404
localhost:3000/en/second-page = 404
localhost:3000/de = 404
localhost:3000/en = 404
same for the default locale.
localhost:3000/second-page = 200
localhost:3000 = 200
I guess, this is because there is no pages/de/second-page.js, for the example, but what's the purpose then of this library, if it doesn't solve this problem.
I have searched a lot and I know about localSubpaths, but seems that it doesn't work:
module.exports = new NextI18Next({
otherLanguages: ['fr'],
//localeSubpaths: localeSubpathVariations[localeSubpaths],
localeSubpaths: {
de: 'de',
en: 'en',
}
})
It doesn't work in my app, but it doesn't work in their sample, too: their sample
Have you checked these two steps ?
After creating and exporting your NextI18Next instance, you need to
take the following steps to get things working:
Create an _app.js file inside your pages directory, and wrap it with
the NextI18Next.appWithTranslation higher order component (HOC). You
can see this approach in the examples/simple/pages/_app.js. Your app
component must either extend App if it's a class component or define a
getInitialProps if it's a functional component (explanation here).
Create a next.config.js file inside your root directory if you want to
use locale subpaths. You can see this approach in the
examples/simple/next.config.js (Next.js 9.5+ required).
const { nextI18NextRewrites } = require('next-i18next/rewrites')
const localeSubpaths = {
de: 'de',
en: 'en',
};
module.exports = {
rewrites: async () => nextI18NextRewrites(localeSubpaths),
publicRuntimeConfig: {
localeSubpaths,
},
}

Resources