Well, I'm starting with nuxt and I have following routes:
/home
/dashboard
/login
I want to protect the /dashboard
, but only for users logged in with a token in Cookie.
Then i created a middleware
/middleware/auth.js
import Cookie from 'js-cookie'
export default function({ req, redirect }) {
if (process.server) {
if (!req.headers.cookie) return redirect('/login')
const jwtCookie = req.headers.cookie.split(';').find(c => c.trim().startsWith('jwt='))
if (!jwtCookie) return redirect('/login')
} else {
const jwt = Cookie.get('jwt')
if (!jwt) { window.location = '/login' }
}
}
and register the middleware in my layout or dashboard page
<script>
export default {
middleware: 'auth',
}
</script>
when I access /dashboard
apparently works perfectly
but the problem is that the middleware is being registered globally, it is running on all pages, all routes
So when you access /home
that is a published page, if you do not have the cookie, you end up being redirected to login page
anyone help?