Comments (1)
This is very problematic, because accessing the index page of any website that uses Nuxt i18n leads to a 404 error.
Based on your workaround, I've created a little module to automatically redirect the user to its preferred language. Create a modules/i18n-fix-index.ts
file with the following content.
import * as fs from 'fs'
import { createResolver, defineNuxtModule, useLogger } from '@nuxt/kit'
import type { PrerenderRoute, Nitro } from 'nitropack'
/**
* Options for the module.
*
* @interface
*/
export interface ModuleOptions {
/**
* Accepted languages codes.
*/
acceptedLanguages: string[]
/**
* The cookie name.
*/
i18nCookieName: string
}
/**
* The name of the module.
*/
const name = 'i18n-fix-index'
/**
* The logger instance.
*/
const logger = useLogger(name)
/**
* TODO: Should be removed once "https://github.com/nuxt-modules/i18n/issues/3016" is fixed.
*/
export default defineNuxtModule<ModuleOptions>({
meta: {
name,
version: '0.0.1',
compatibility: { nuxt: '^3.0.0' },
configKey: 'i18nFixIndex'
},
defaults: {
acceptedLanguages: ['en', 'fr'],
i18nCookieName: 'i18n_redirected'
},
setup: async (options, nuxt) => {
const defaultLanguage = options.acceptedLanguages[0]
const indexPageContent = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="refresh" content="3; url=/${defaultLanguage}/">
<script type="text/javascript">
const getCookieValue = (name) => (
document.cookie.match('(^|;)\\\\s*' + name + '\\\\s*=\\\\s*([^;]+)')?.pop() || ''
)
const acceptedLanguages = ${JSON.stringify(options.acceptedLanguages)}
const i18nCookieValue = getCookieValue('${options.i18nCookieName}')
let wantedLanguage = acceptedLanguages[0]
if (acceptedLanguages.includes(i18nCookieValue)) {
wantedLanguage = i18nCookieValue;
} else {
const userLanguage = navigator.language || navigator.userLanguage
const languageCode = userLanguage.indexOf('-') === -1 ? userLanguage : userLanguage.split('-')[0]
if (acceptedLanguages.includes(languageCode)) {
wantedLanguage = languageCode
}
}
document.querySelector('meta[http-equiv="refresh"]').setAttribute('content', '0; /' + wantedLanguage + '/')
document.querySelector('p > a').setAttribute('href', '/' + wantedLanguage + '/')
</script>
</head>
<body>
<p style="margin-bottom: 0;">
Redirecting you... Please wait or click <a href="/${defaultLanguage}/">here</a> if you're not being redirected.
</p>
</body>
</html>`
const resolver = createResolver(import.meta.url)
const hooks = nuxt.options.nitro.hooks ?? {}
// @ts-expect-error: We're not in nuxt.config.ts.
hooks['prerender:generate'] = (route: PrerenderRoute, nitro: Nitro) => {
if (route?.route === '/200.html') {
logger.info('Fixing index...')
const outputPath = resolver.resolve(
nitro.options.output.publicDir,
'index.html'
)
fs.writeFileSync(outputPath, indexPageContent)
logger.success('Done. Don\'t forget to delete this module once https://github.com/nuxt-modules/i18n/issues/3016 is closed.')
}
}
nuxt.options.nitro.hooks = hooks
}
})
Then, in your nuxt.config.ts
, you have to configure it.
i18nFixIndex: {
acceptedLanguages: ['en', 'fr'], // Put the accepted languages codes. The first of the list will be the default language.
i18nCookieName: 'i18n_redirected' // `cookieKey` (https://i18n.nuxtjs.org/docs/options/browser#cookiekey) of Nuxt i18n.
}
from i18n-module.
Related Issues (20)
- Not able to add i18n config in nuxt.config.ts HOT 2
- Fallback locale not working with mixed code (language & language+region)
- Undesired Route Path Casing Override
- Support for `defineRouteRules` HOT 1
- fix: `node_modules` paths in runtime configuration payload HOT 1
- switchLocalePath returns an empty string when used in middleware HOT 2
- Change BaseURL when using different domains HOT 1
- Custom Route Paths in nuxt.config dont work together with compiler macro defineI18nRoute HOT 3
- Redirect fails with 404 error for non-index pages if SSR is turned off HOT 1
- `detectBrowserLanguage` + Caching
- Access to i18n config in nitro context
- Issue with Default and Current Locale Data Being Fetched Simultaneously in nuxt-i18n
- Custom Route Paths Bug with dynamic Sub-Paths
- localePath not generating route, it's empty HOT 4
- DetectBrowserLanguage rollback to default locale when using `prefix_except_default`
- navigateTo without locale prefix resets locale to default
- Experimental switchLocalePathLinkSSR causing possible XSS vector HOT 1
- Ability to disable the module
- Switching locale using page transitions fetches with the old locale
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from i18n-module.