Middleware: Guarding Routes and Executing Logic
5 min read
Middleware: Guarding Routes and Executing Logic ๐ก๏ธ
Welcome, fellow coder! Ever felt like you need a bouncer for your web pages? Someone to check IDs, see if users are on the guest list, or just announce their arrival? That's precisely what Middleware does in Nuxt. It's your application's friendly neighborhood bouncer, running checks before letting anyone into a specific route.
What is Route Middleware?
In the world of Nuxt, route middleware are functions that run before a user navigates to a particular route. Think of it as a checkpoint. Before a user can access a page, the middleware function is executed, giving you the power to allow, deny, or redirect the navigation.
The Problem: Imagine you have a dashboard page that only logged-in users should see. Without middleware, anyone could potentially access this page, leading to a not-so-great user experience and potential security holes. ๐ฌ
The Solution: Middleware steps in to solve this. You can create a middleware that checks if a user is authenticated. If they are, great, they can proceed to the dashboard. If not, you can redirect them to the login page. Simple, clean, and secure.
Inline vs. Named Middleware
Nuxt offers a couple of ways to implement these bouncers: inline and named. Let's break them down.
Inline Middleware: The "On-the-Spot" Bouncer
Inline middleware is defined directly within the page component where it's used. It's perfect for one-off checks that are specific to a single page.
Imagine you have a special, top-secret page that requires an extra layer of validation, but this logic isn't needed anywhere else.
pages/secret-lair.vue
<script setup>
definePageMeta({
middleware: [
function (to, from) {
const accessCode = prompt('What\'s the secret code?');
if (accessCode !== 'Nuxt is awesome') {
console.log('Access Denied! ๐ซ');
return abortNavigation();
}
},
],
});
</script>
<template>
<h1>Welcome to the Secret Lair! ๐คซ</h1>
</template>In this example, before the "Secret Lair" page is rendered, a prompt will ask for a secret code. If the user enters the wrong code, abortNavigation() is called, and the navigation to the page is stopped.
Named Middleware: The "Regular" Bouncer ๐ฎ
Named middleware are defined in the middleware/ directory of your Nuxt project. These are reusable bouncers that you can apply to any page you want. This is the go-to approach for common checks like authentication.
Let's create an authentication middleware.
middleware/auth.ts
export default defineNuxtRouteMiddleware((to, from) => {
// A simple check for a logged-in user. In a real app, you'd likely check a cookie or a state management store.
const isLoggedIn = false; // Let's pretend the user is not logged in for this example.
if (!isLoggedIn && to.path !== '/login') {
console.log('You shall not pass! ๐งโโ๏ธ');
return navigateTo('/login');
}
});Here, defineNuxtRouteMiddleware is a helper function that provides type-safety for your middleware. navigateTo is a globally available helper that redirects the user.
Now, to use this named middleware on a specific page, you reference it in the definePageMeta block.
pages/dashboard.vue
<script setup>
definePageMeta({
middleware: 'auth' // or ['auth']
});
</script>
<template>
<h1>Welcome to your Dashboard! ๐</h1>
</template>With this setup, anyone trying to access the /dashboard page will be redirected to /login because our auth middleware says they aren't logged in.
Fun Fact: Nuxt automatically converts middleware names from camelCase (myMiddleware) to kebab-case (my-middleware) when you use them in definePageMeta.
Global Middleware: Running Logic on Every Request ๐
What if you need a bouncer at the main entrance, checking everyone who comes in, no matter which room they're going to? That's where global middleware comes in.
Global middleware runs on every single route change in your application. To create one, you simply add a .global suffix to your middleware filename.
middleware/logger.global.ts
export default defineNuxtRouteMiddleware((to, from) => {
console.log(`Navigating from ${from.path} to ${to.path} ๐`);
});Now, every time you navigate between pages, you'll see a message in your console logging the route change. This is incredibly useful for things like analytics, logging, or setting up universal configurations for every page.
A Word of Caution: Use global middleware sparingly. Since they run on every navigation, complex logic within them can slow down your application.
By default, global middleware are executed alphabetically by filename. If you need a specific order, you can prefix the filenames with numbers, like 01-setup.global.ts and 02-analytics.global.ts.
Practical Example: Protecting Authenticated Routes ๐
Let's put our knowledge into practice with a common real-world scenario: protecting routes that require a user to be logged in.
The Goal: We want to have a /profile page that is only accessible to authenticated users. If a non-authenticated user tries to access it, they should be redirected to the /login page.
Step 1: Create the Authentication Middleware
First, let's create our named middleware to handle the authentication check.
middleware/auth.ts
export default defineNuxtRouteMiddleware((to, from) => {
// In a real application, you would use a composable or a store to check the user's authentication state.
// For this example, we'll simulate it with a simple variable.
const { isAuthenticated } = useAuth(); // Imagine this is a composable that returns the auth state.
if (!isAuthenticated() && to.path !== '/login') {
return navigateTo('/login');
}
});(For a real app, useAuth would be a composable you create to manage authentication state, likely interacting with cookies or a state management library like Pinia.)
Step 2: Apply the Middleware to the Protected Page
Now, let's apply our auth middleware to the /profile page.
pages/profile.vue
<script setup>
definePageMeta({
middleware: 'auth'
});
const { user } = useAuth(); // Getting user data from our imaginary auth composable.
</script>
<template>
<div>
<h1>Welcome, {{ user.name }}!</h1>
<p>This is your super secret profile page.</p>
</div>
</template>Step 3: Create the Login Page
Of course, we need a login page for users to be redirected to.
pages/login.vue
<script setup>
const { login } = useAuth(); // Our imaginary composable also has a login function.
function handleLogin() {
login('testuser', 'password');
// After successful login, redirect to the profile page.
navigateTo('/profile');
}
</script>
<template>
<div>
<h1>Login</h1>
<button @click="handleLogin">Log In</button>
</div>
</template>And that's it! With these pieces in place, your /profile route is now protected. Any unauthenticated user trying to access it will be gracefully redirected to the /login page. This is a fundamental and powerful pattern for building secure and user-friendly web applications with Nuxt.
Further Reading & Resources:
- Official Nuxt Documentation on Middleware: https://nuxt.com/docs/guide/directory-structure/middleware
- Video Tutorial on Nuxt Middleware: https://www.youtube.com/watch?v=s9ZEa8_3P3A
- Authentication in Nuxt 3: https://masteringnuxt.com/course/full-stack-unleashed/auth-in-nuxt-3
Challenge
You are tasked with implementing a comprehensive route protection system for a new feature-gated application using Nuxt Middleware. You will need to create global, named, and inline middleware to handle analytics, subscription checks, and pro-feature access.
You have access to a mock composable useUser() which returns a reactive user object: const user = useUser(); user.value will be { name: 'Alex', subscription: 'free' | 'premium' | 'pro' }.
Your Tasks:
Create a Global Analytics Middleware:
In the filemiddleware/analytics.global.ts, define a global middleware that runs on every route change. For this exercise, simulate logging by callingconsole.log(Navigating from {to.path});.Create a Named Subscription Middleware:
In the filemiddleware/subscription-check.ts, define a named middleware. This middleware should:- Use the
useUser()composable to get the current user's subscription status. - If the user's subscription is 'free' AND they are trying to navigate to a path that starts with
/premium, redirect them to the/upgradepage usingnavigateTo('/upgrade').
- Use the
Apply the Named Middleware:
In the page componentpages/premium/dashboard.vue, usedefinePageMetato apply thesubscription-checkmiddleware.Create an Inline Pro-Tier Middleware:
In the page componentpages/pro/settings.vue, usedefinePageMetato define an inline middleware. This middleware must:- Use the
useUser()composable. - Check if the user's subscription is 'pro'.
- If the subscription is not 'pro', block the navigation completely using
abortNavigation()with the error message "Pro plan required for this feature.".
- Use the
Expected result
Your final code should consist of four correctly implemented parts within the provided structure.
middleware/analytics.global.ts: This file should contain adefineNuxtRouteMiddlewarefunction that acceptstoandfromas arguments and logs their paths. The filename's.global.tssuffix makes it a global middleware.middleware/subscription-check.ts: This file should contain adefineNuxtRouteMiddlewarefunction. Inside, it should use theuseUsercomposable, check ifuser.value.subscriptionis 'free' and ifto.path.startsWith('/premium'), and if both are true, callreturn navigateTo('/upgrade').pages/premium/dashboard.vue: This file's script section should contain adefinePageMetacall. The object passed to it must have amiddlewarekey with the value'subscription-check'. Note that Nuxt automatically converts the filename to kebab-case for use here.pages/pro/settings.vue: This file's script section should contain adefinePageMetacall. The object passed to it must have amiddlewarekey whose value is an inline anonymous function. This function should use theuseUsercomposable and callabortNavigation('Pro plan required for this feature.')ifuser.value.subscriptionis not equal to 'pro'.