Redirect from a route middleware in Nuxt

Send people who aren't logged in to the login page before the page even renders.

SNP 067 #694 Filed js nuxt

middleware/auth.js:

javascript
export default defineNuxtRouteMiddleware((to) => {
  const user = useUserStore()

  if (!user.loggedIn) {
    return navigateTo({ path: '/login', query: { redirect: to.fullPath } })
  }
})

Opt a page in:

vue
<script setup>
definePageMeta({ middleware: 'auth' })
</script>

Name the file auth.global.js instead and it runs on every route. return abortNavigation() stops the navigation without going anywhere. Middleware runs on the server for the first request and in the browser after that, so don't touch window in it.