A D
A D

Reputation: 73

How to redirect to an external site with a Nuxt middleware?

I would like to redirect a certain group of users to another URL (external) before the page is loaded, i.e. with middleware.
Since I use nuxt in ssr-mode and redirect the users in layouts/default via window.location.replace(), you see the "mainsite" for a second.

Upvotes: 5

Views: 9100

Answers (2)

Leo
Leo

Reputation: 109

You can use the navigateTo method with the external options set to true, like the following:

return navigateTo(EXTERNAL_URL, {
  external: true
})

Reference: https://nuxt.com/docs/api/utils/navigate-to#external-url

Upvotes: 1

kissu
kissu

Reputation: 46604

This kind of middleware should do the trick and you won't see any content displayed before because it will be executed before rendering your page.

middleware/google.js

export default ({ redirect }) => {
  if (myCoolCondition === 'cool') {
    redirect('https://www.google.com')
  }
}

To apply it to a specific component/page, use this

<script>
export default {
  middleware: ['google']
}
</script>

Here is the related documentation: https://nuxtjs.org/docs/2.x/directory-structure/middleware#named-middleware

Upvotes: 10

Related Questions