Nuxt 3 Middleware issue

middleware/auth.js
export default defineNuxtRouteMiddleware((to,from)=>{
const cookie = useCookie('__session')
if(!cookie.value){
console.log("cookie.value is none")
return navigateTo('/admin/login')
}
console.log('Cookie found:', cookie.value)
})
export default defineNuxtRouteMiddleware((to,from)=>{
const cookie = useCookie('__session')
if(!cookie.value){
console.log("cookie.value is none")
return navigateTo('/admin/login')
}
console.log('Cookie found:', cookie.value)
})
Dashboard.vue
<template>
<h1>Dashboard</h1>

</template>

<script setup>
definePageMeta({
middleware: ['auth'],
})
</script>
<template>
<h1>Dashboard</h1>

</template>

<script setup>
definePageMeta({
middleware: ['auth'],
})
</script>
- Navigate to is getting fired regardless if cookie value exist or not - When cookie value exists it doesn't do console.log("cookie.value is none") still navigate to works - I tried opening the dashboard from different url, it lands to /admin/login
2 Replies
Holy De Mello
Holy De MelloOP4mo ago
nvm i found the solution turns out i need to make sure its running in server side
export default defineNuxtRouteMiddleware((to,from)=>{
if (process.server) {
console.log('This is running on the server')
const cookie = useCookie('__session')
console.log(cookie.value)
if(!cookie.value){
console.log("cookie.value is none")
// return navigateTo('/admin/login')
}
}
})
export default defineNuxtRouteMiddleware((to,from)=>{
if (process.server) {
console.log('This is running on the server')
const cookie = useCookie('__session')
console.log(cookie.value)
if(!cookie.value){
console.log("cookie.value is none")
// return navigateTo('/admin/login')
}
}
})
Cake
Cake4mo ago
checking only if a cookie exists or not doesn't seem secure you should be checking the cookie value if it's valid or not
Want results from more Discord servers?
Add your server