Utilize middleware
1. Page middleware
You can verify the user in middleware (using cookies or any other method you prefer. In this instance, I utilized the nuxt auth module)
Named middleware
/* pages/_user/home.vue */
export default {
middleware: "auth"
}
Anonymous
/* pages/_user/home.vue */
export default {
middleware({ $auth, redirect }) {
if(!$auth.loggedIn) {
redirect("/www/home")
}
}
}
2. Router middleware
If you wish to apply this logic globally across the project (on every child route of the _user
page, for example), you can specify router middleware in nuxt.config.js
/* nuxt.config.js */
export default {
router: {
middleware: ["auth"] // or "auth" for a single middleware
}
}
/* middleware/auth.js */
export default ({ $auth, route, redirect }) => {
if(funcToDetectUserPage(route.path)) {
if(!$auth.loggedIn) {
redirect("/www/home");
}
}
}