Search code examples
vue.jshttp-redirectnuxt.jsmiddlewareserver-side-rendering

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.


Solution

  • 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