NuxtN
Nuxt16mo ago
iamntz

Translate custom routes with i18n?

I'm trying to create a custom route that's also translatable, but for some reasons it doesnt quite work.

whenever i'm trying to use it:

const localePath = useLocalePath()
localePath('miau') 

I'll get the translated path name, not the translation. I.e. i'll get
/en/miau
(instead of
/en/miau-translated
). The path DO WORK, the translation is the only problem

const router = useRouter();
router.getRoutes()

will list the right route, similar to the pages that are working:

[
{
  "path": "/en/miau",
  "name": "miau___en",
  "meta": {},
  "props": {
    "default": false
  },
  "children": [],
  "instances": {},
  "leaveGuards": {
    "Set(0)": []
  },
  "updateGuards": {
    "Set(0)": []
  },
  "enterCallbacks": {},
  "components": {},
  "__vd_id": "46"
},
// ... same for IT
{
    "path": "/en/about-us",
    "name": "about___en",
    "meta": {},
    "props": {
      "default": false
    },
    "children": [],
    "instances": {},
    "leaveGuards": {
      "Set(0)": []
    },
    "updateGuards": {
      "Set(0)": []
    },
    "enterCallbacks": {},
    "components": {},
    "__vd_id": "24"
  },
]
Solution
i managed to make it work by ditching
custom-routes
module and using
app/router.options.ts
instead, like so:

import type { RouterConfig } from "nuxt/schema";

import routes_i18n from "../config/routes";

const customRoutes = {
  miau: {
    route: routes_i18n.miau,
    component: () => import("~/pages/custom-component-page.vue"),
  },
};

export default {
  routes: (_routes) => {
    const routes = [..._routes]; // <<< because _routes is readonly

    Object.entries(customRoutes).forEach(
      ([routeName, { route, component }]) => {
        Object.entries(route).forEach(([lang, path]) => {
          routes.push({
            path: `/${lang}${path}`,
            name: `${routeName}___${lang}`,
            component,
          });
        });
      }
    );
    return routes;
  }
} satisfies RouterConfig;
Was this page helpful?