Problem with nuxt-i18n and 404 redirect with nuxt

1.9k Views Asked by At

I'm working on a nuxt project with a custom 404 page. When I install the module nuxt-i18n to have my website in french and english I have encountered a problem with the custom route created for the 404 page.

  • when I let my custom route in extendRoutes, I can't access routes like "page/en/", it gets redirected to 404.
  • when I disable this custom routing I have no problem, my nuxt-i18n is configured correctly.

How can I manage both ?

Here is my nuxt.config.js file :

export default {
  mode: 'universal',
  router: {
    trailingSlash: true,
    extendRoutes(routes, resolve) {
      routes.push({
        name: 'custom',
        path: '*',
        component: resolve(__dirname, 'pages/404.vue'),
        redirect: '/404/'
      })
    }
  },
  generate: {
      fallback: '404.html'
  },
  modules: [
    'nuxt-i18n',
  ],
  i18n: {
    locales: [{
      code: 'fr',
      iso: 'fr-FR',
      file: 'fr.json',
      dir: 'ltr'
    },
    {
      code: 'en',
      iso: 'en-US',
      file: 'en.json',
      dir: 'ltr'
    }],
    prefix_except_default: 'prefix_except_default',
    defaultLocale: 'fr',
    langDir: 'locales/',
  },
}
2

There are 2 best solutions below

1
On

I have the same issue, I think nuxt-i18n is not compatible with a custom 404 page. The only solution I found on my side is edit path by: path: '/:lang/*':

routes.push({
    name: 'custom',
    path: '/:lang/*',
    component: resolve(__dirname, 'pages/404.vue')
})

It works, but create a weird redirection of /en/toto to /en/en/toto

0
On

The reason for this is that extendRoutes runs faster than i18n adds routes. As a result, an ugly route is added as below

routes: [{
  path: "/en*",
  component: resolve(__dirname, 'pages/404.vue'),
  name: "custom"
}, {
  path: "/jp*",
  component: resolve(__dirname, 'pages/404.vue'),
  name: "custom"
},  {
  path: "*",
  component: resolve(__dirname, 'pages/404.vue'),
  name: "custom"
}]]

So I delayed the execution of extendRoutes.

extendRoutes(routes, resolve) {
  setTimeout(()=> {
    routes.push({
      name: 'custom',
      path: '*',
      component: resolve(__dirname, 'pages/404.vue'),
      redirect: '/404/'
    })
  })
}

Build Results

routes: [{
  path: "*",
  component: resolve(__dirname, 'pages/404.vue'),
  name: "custom"
}]