How to redirect to an external site with a Nuxt middleware?
Asked Answered
P

2

5

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.

Phosgene answered 20/8, 2021 at 6:57 Comment(0)
P
10

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

Porter answered 20/8, 2021 at 7:12 Comment(1)
You can add the midleware globally for any route you hit, but you need to add this to nuxt.config file. js router: { middleware: [ "google"], base: `${process.env.ROUTER_BASE}`, } Garlic
S
0

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

Stoker answered 28/3 at 15:10 Comment(1)
it's nuxt2 questionCoy

© 2022 - 2024 — McMap. All rights reserved.