middleware/auth.js:
export default defineNuxtRouteMiddleware((to) => {
const user = useUserStore()
if (!user.loggedIn) {
return navigateTo({ path: '/login', query: { redirect: to.fullPath } })
}
})
Opt a page in:
<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.