Route middleware
Some pages should not render for every visitor. An admin page needs a signed-in user; a settings page may need a feature flag. Nuxt lets you run code before a route is entered with route middleware.
A middleware is a file in the middleware/ directory that exports a function
using defineNuxtRouteMiddleware. It receives the route being entered (to) and
the route being left (from):
// middleware/auth.js
export default defineNuxtRouteMiddleware((to) => {
if (!isLoggedIn()) {
return navigateTo('/login');
}
});
Returning navigateTo('/login') redirects before the page renders, so the
protected component never mounts.
Attach a named middleware to a page with definePageMeta:
<script setup>
definePageMeta({ middleware: 'auth' });
</script>
A file whose name ends in .global runs on every route with no per-page
registration. Middleware runs on the server for the first request and in the
browser for later client-side navigation, so the same guard protects both.
You are about to answer a short quiz on route middleware.