Middleware
Middleware
Inline Middleware
<script setup>
definePageMeta({
middleware: function (to, from) {
if (to.path === '/admin' && user.admin === false) {
return navigateTo('/login')
}})
</script>
Named Middleware
📄 middleware/admin.js
export default function (to, from) {
if (to.path === '/admin' && user.admin === false) {
return navigateTo('/login')
}
}
📄 adminView.vue
<script setup>
definePageMeta({
middleware: ['admin'] //this can be a single middleware string or an array
})
</scrpt>
Global Middleware
把📁 middleware/admin.js改为📁 middleware/admin.global.js即可
export default function (to, from) {
if (to.path === '/admin' && user.admin === false) {
return navigateTo('/login')
}
}
Server Middleware
📁 pages/login.vue
<script setup lang="ts">
const authCookie = useCookie('user-auth')
function authenticate() {
authCookie.value = '1f38d'
}
</script>
<template>
<h1>Login Page</h1>
<button @click="authenticate">Authenticate</button>
</template>
📁 server/middleware/auth.js
export default defineEventHandler(async event => {
const auth = getCookie(event, 'auth')
const url = getRequestURL(event)
if (auth || url.pathname === '/login') {
return
} else {
return sendRedirect(event, '/login', 302)
}
})