Skip to content

Instantly share code, notes, and snippets.

@theo-bittencourt
Created April 10, 2020 02:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theo-bittencourt/5e089a4888849243bd76ea929b35ead6 to your computer and use it in GitHub Desktop.
Save theo-bittencourt/5e089a4888849243bd76ea929b35ead6 to your computer and use it in GitHub Desktop.
/**
* This middleware redirects routes without locale to a prefixed ones.
* Useful for links included on email templates.
*/
export default function(context) {
const { route, redirect, app } = context
const { path, query } = route
const previousLocaleCode = app.i18n.getLocaleCookie()
const localeCodes = app.i18n.locales.map(l => l.code)
/**
* Bypass auth related URLs. `nuxt-auth` and `nuxt-i18n` doesn't seem to work together when
* redirection to the original URL is needed (`rewriteRedirects`).
*/
if (path.startsWith('/auth/')) return
/**
* Return when locale is already in URL.
*/
// eslint-disable-next-line prettier/prettier
if (new RegExp(`^/(${localeCodes.join('|')}).*$`).test(path)) return;
/** [Nuxt] Workaround beacuase $loading.finish() is not been called as like it should be.
* Related issues:
* https://github.com/nuxt/nuxt.js/issues/4452
* https://github.com/nuxt/nuxt.js/issues/4456
*/
;(((window.$nuxt || {}).$loading || {}).finish || function() {})()
const redirectLocalePath = previousLocaleCode || app.i18n.fallbackLocale.substring
console.log(`[redirectRoutesWithoutLocale] Will redirect: /${redirectLocalePath}${path}`)
// Prepend the URL with the previously selected code or the default one.
return redirect(307, `/${redirectLocalePath}${path}`, query)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment