nuxt-i18n-routing icon indicating copy to clipboard operation
nuxt-i18n-routing copied to clipboard

Localized routing with Nuxt.js

nuxt-i18n-routing

Localized routing with Nuxt.js

nuxt-i18n module

Check out nuxt-i18n module which is based on the work you'll find here.

Info

This project showcases a way of achieving localized routing with Nuxt.js. It's not fully tested and you should expect that this might not work for your specific needs. In particular, nested routing has not been tried at all and might require additional work to be properly supported.

Configuration

In ~/config/index.js, we define the i18n configuration:

  • LOCALES is an array of languages available in the app
  • DEFAULT_LOCALE is the app's main language, routes for this language won't have a lang prefix
  • ROUTES_ALIASES is an object where custom paths can be defined for generated routes, each key should match one of Nuxt's original routes name. Use this if you want to translate some URLs in the app, visit the "About" page to see this in action.

Routes generator

In order to "localize" the routes, a generator function overrides all the routes that Nuxt generates by reading the pages/ directory contents. The generator is imported in nuxt.config.js and used in the extendRoutes method.

See the code in ~/utils/router.js.

Store

A small Vuex store module is used to persist user's locale preference accross pages.

See the code in ~/store/i18n/.

Plugin

A simple plugins is used to inialize vue-i18n which provides all translation features in the app.

See the code in ~/plugins/vue-i18n.js.

Middleware

A middleware, heavily inspired by Nuxt's i18n example, handles language switching using the language from the URL.

See the code in ~/middleware/i18n.js.

Mixin

A global mixin provides 2 methods responsible for generating links in the app:

  • getLocalizedRoute (route, locale) – Returns the path corresponding to a given route for the request language. If route is a string, it will be used as the route's name. The route's name should correspond to the original name that was generated by Nuxt. Refer to Nuxt doc to see how it generates routes names. If locale is omitted, the app's current locale is used.
  • getSwitchLocaleRoute (locale) – Returns the URL of the current page for the requested language.

In Vue components, display links as follows:

<!-- Using the route's name -->
<nuxt-link :to="getLocalizedRoute('index')">
  {{ $t('labels.home') }}
</nuxt-link>

<!-- Using a route object with parameters -->
<nuxt-link :to="getLocalizedRoute({ name: 'category-slug', params: { slug: 'landscapes' } })">
  {{ $t('categories.landscapes') }}
</nuxt-link>

See the code in ~/plugins/global-mixin.js.

Build Setup

# install dependencies
$ yarn

# serve with hot reload at localhost:3000
$ yarn dev

# build for production and launch server
$ yarn build
$ yarn start

# generate static project
$ yarn generate

For detailed explanation on how things work, checkout the Nuxt.js docs.