Nuxt.js: How to redirect with vue-router?

Created on 13 Oct 2017  路  5Comments  路  Source: nuxt/nuxt.js

So i have a SPA where the base path has to redirect to a locale folder. Normally i would do this by defining two paths that are pointing to the same page in the router:

  routes: [
    {
      path: '/',
      redirect: { name: 'index' }
    },
    {
      path: '/en/',
      name: 'index',
      component: index
    }
  ]

E.g. http://test.com/ is redirected to http://test.com/en.

Following solved the issue, but i am not sure if this is best-practice?

<script>
export default {
  fetch ({ params, redirect }) {
    redirect(301, '/en')
  }
}
</script>

This question is available on Nuxt.js community (#c1656)

Most helpful comment

Hi @maziarz,
It's the recommended solution and the easiest one 馃憤

All 5 comments

Hi @maziarz,
It's the recommended solution and the easiest one 馃憤

In the most recent version of nuxt you're also able to accomplish this via a middleware:

File: middlewares/locale-redirect.js:

export default function ({params, route, redirect}) {
    // hypothetical set of all supported locales
    const locales = ['en', 'ge'];

    // if the current prefix is neither 'en' nor 'ge'
    if (!locales.indexOf(params.locale)) {
        // redirect to the same path with default locale as prefix
        redirect('301', '/' + locales[0] + route.fullPath);
    }
}

File: nuxt-config.js:

module.exports = {
    // ...
    router: {
        middleware: ['locale-redirect']
    }
}

Would love to see this in the documentation!! Example using dynamic routes:

export default {
  fetch ({ params, redirect }) {
    redirect(301, `/v/${params.title}/${params.id}`)
  }
}

I used

 fetch ({ params, redirect }) {
    redirect(301, `/v/${params.title}/${params.id}`)
  }

but, I find I cant use this.$router.push(). When I use this.$router.push(),my browser will die .

Does it have any other way to redirect ?

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

gary149 picture gary149  路  3Comments

vadimsg picture vadimsg  路  3Comments

jaredreich picture jaredreich  路  3Comments

bimohxh picture bimohxh  路  3Comments

nassimbenkirane picture nassimbenkirane  路  3Comments