In this episode, we focus on making sure only authenticated users can view certain pages, like the dashboard, using middleware in Nuxt. Right now, anyone can go to the dashboard, even if they're not signed in, which is definitely not ideal! To fix this, we add middleware to the dashboard page so that if someone isn't authenticated, they're automatically redirected to the login page.
We also see how easy it is to use the Nuxt definePageMeta
feature to apply the middleware from our authentication package. With just middleware: sanctum:auth
, we enforce authentication on any page we want. If someone isn't logged in, they're sent to the login screen.
Next, we flip things around: once a user is signed in, it doesn't make sense for them to see the login or register pages. So, we apply guest middleware (sanctum:guest
) to those pages. Now if an authenticated user tries to access the login page, they get redirected straight to the dashboard.
We wrap up by showing a neat trick with definePageMeta
: you can use it to set page titles dynamically! By grabbing the title from the meta info and using Nuxt's useHead
composable, we can automatically update the browser tab title for each page. This keeps your app looking sharp and organized as users navigate around.
Overall, you'll see how middleware and page meta make it super simple to control access and customize your Nuxt app's experience.