3

I've defined a namespaced middleware for Nuxt like so:

export default function({ store, redirect, app }){
    if (!store.state.isAuth) {
        return redirect(app.i18n.localePath('/auth'))
    }
}

where if the user is not authenticated, they're redirected to the authentication page, located at /auth. However, this is a multilingual site, so I need to generate the path corresponding to the current locale. Normally I'd do this using $i18n.localePath or in this case, using Nuxt's context, app.i18n.localePath(), however I get this error:

 app.i18n.localePath is not a function 

and I'm not sure why, given that there's a context, and console.log(app.i18n) shows me that app.i18n.localePath is a function:

...
localePath: [Function: bound ],
...

Any suggestions? Thanks!

SSBakh
  • 1,487
  • 1
  • 14
  • 27

2 Answers2

3

Yes, for some reason localePath does not work in middleware. You probably should detect current locale manualy.

let locale = app.i18n.locale === app.i18n.defaultLocale ? '' : '/' + app.i18n.locale;

return redirect( locale + '/auth' );
Winns
  • 810
  • 1
  • 9
  • 20
0

Use app.localePath('/auth') instead

  • 3
    It helps more if you supply an explanation why this is the preferred solution and explain how it works. We want to educate, not just provide code. – the Tin Man Sep 28 '21 at 19:51