|
| 1 | +# Nuxt Middleware & Plugins |
| 2 | + |
| 3 | +## When to Use |
| 4 | + |
| 5 | +Working with `middleware/` or `plugins/` directories, route guards, app extensions. |
| 6 | + |
| 7 | +## Route Middleware |
| 8 | + |
| 9 | +Route middleware runs before navigation. Used for auth checks, redirects, logging. |
| 10 | + |
| 11 | +### Global Middleware |
| 12 | + |
| 13 | +Runs on every route change. **REQUIRED: Use `.global.ts` suffix:** |
| 14 | + |
| 15 | +```ts |
| 16 | +// middleware/auth.global.ts |
| 17 | +export default defineNuxtRouteMiddleware((to, from) => { |
| 18 | + const auth = useAuthStore() |
| 19 | + |
| 20 | + if (to.meta.requiresAuth && !auth.isAuthenticated) { |
| 21 | + return navigateTo('/login') |
| 22 | + } |
| 23 | +}) |
| 24 | +``` |
| 25 | + |
| 26 | +**Without `.global.ts` suffix, middleware is named (not global).** |
| 27 | + |
| 28 | +## Red Flags - Stop and Check Skill |
| 29 | + |
| 30 | +If you're thinking any of these, STOP and re-read this skill: |
| 31 | + |
| 32 | +- "Suffix doesn't matter, it's about where I put it" |
| 33 | +- "I'll redirect() instead of return navigateTo()" |
| 34 | +- "I remember Nuxt 3 middleware patterns" |
| 35 | +- "Export default function is simpler" |
| 36 | + |
| 37 | +All of these mean: You're using outdated patterns. Use Nuxt 4 patterns instead. |
| 38 | + |
| 39 | +### Named Middleware |
| 40 | + |
| 41 | +Runs only when explicitly applied. No `.global` suffix: |
| 42 | + |
| 43 | +```ts |
| 44 | +// middleware/admin.ts |
| 45 | +export default defineNuxtRouteMiddleware((to, from) => { |
| 46 | + const auth = useAuthStore() |
| 47 | + |
| 48 | + if (!auth.isAdmin) { |
| 49 | + return navigateTo('/') |
| 50 | + } |
| 51 | +}) |
| 52 | +``` |
| 53 | + |
| 54 | +Apply in page: |
| 55 | + |
| 56 | +```vue |
| 57 | +<script setup lang="ts"> |
| 58 | +definePageMeta({ |
| 59 | + middleware: ['admin'] |
| 60 | +}) |
| 61 | +</script> |
| 62 | +``` |
| 63 | + |
| 64 | +### Middleware Return Values |
| 65 | + |
| 66 | +```ts |
| 67 | +export default defineNuxtRouteMiddleware((to, from) => { |
| 68 | + // Allow navigation |
| 69 | + return |
| 70 | + |
| 71 | + // Redirect |
| 72 | + return navigateTo('/login') |
| 73 | + |
| 74 | + // Abort navigation |
| 75 | + return abortNavigation() |
| 76 | + |
| 77 | + // Abort with error |
| 78 | + return abortNavigation('Not authorized') |
| 79 | +}) |
| 80 | +``` |
| 81 | + |
| 82 | +### Middleware Order |
| 83 | + |
| 84 | +1. Global middleware (alphabetical by filename) |
| 85 | +2. Layout middleware (if layout defines middleware) |
| 86 | +3. Page middleware (defined in definePageMeta) |
| 87 | + |
| 88 | +## Plugins |
| 89 | + |
| 90 | +Plugins extend Vue app with global functionality. Run during app initialization. |
| 91 | + |
| 92 | +### Basic Plugin |
| 93 | + |
| 94 | +```ts |
| 95 | +// plugins/my-plugin.ts |
| 96 | +export default defineNuxtPlugin((nuxtApp) => { |
| 97 | + return { |
| 98 | + provide: { |
| 99 | + hello: (name: string) => `Hello ${name}!` |
| 100 | + } |
| 101 | + } |
| 102 | +}) |
| 103 | +``` |
| 104 | + |
| 105 | +Use in components: |
| 106 | + |
| 107 | +```vue |
| 108 | +<script setup lang="ts"> |
| 109 | +const { $hello } = useNuxtApp() |
| 110 | +console.log($hello('World')) // "Hello World!" |
| 111 | +</script> |
| 112 | +``` |
| 113 | + |
| 114 | +### Plugin with Vue Plugin |
| 115 | + |
| 116 | +```ts |
| 117 | +import type { PluginOptions } from 'vue-toastification' |
| 118 | +// plugins/toast.client.ts |
| 119 | +import Toast from 'vue-toastification' |
| 120 | +import 'vue-toastification/dist/index.css' |
| 121 | + |
| 122 | +export default defineNuxtPlugin((nuxtApp) => { |
| 123 | + nuxtApp.vueApp.use(Toast, { |
| 124 | + position: 'top-right', |
| 125 | + timeout: 3000 |
| 126 | + } as PluginOptions) |
| 127 | +}) |
| 128 | +``` |
| 129 | + |
| 130 | +### Plugin with Hooks |
| 131 | + |
| 132 | +```ts |
| 133 | +// plugins/init.ts |
| 134 | +export default defineNuxtPlugin((nuxtApp) => { |
| 135 | + nuxtApp.hook('app:created', () => { |
| 136 | + console.log('App created') |
| 137 | + }) |
| 138 | + |
| 139 | + nuxtApp.hook('page:finish', () => { |
| 140 | + console.log('Page finished loading') |
| 141 | + }) |
| 142 | +}) |
| 143 | +``` |
| 144 | + |
| 145 | +### Client-Only or Server-Only |
| 146 | + |
| 147 | +Use file suffix: |
| 148 | + |
| 149 | +- `.client.ts` - runs only on client |
| 150 | +- `.server.ts` - runs only on server |
| 151 | + |
| 152 | +```ts |
| 153 | +// plugins/analytics.client.ts |
| 154 | +export default defineNuxtPlugin(() => { |
| 155 | + // Only runs in browser |
| 156 | + if (window.analytics) { |
| 157 | + window.analytics.init() |
| 158 | + } |
| 159 | +}) |
| 160 | +``` |
| 161 | + |
| 162 | +### Plugin Order |
| 163 | + |
| 164 | +Use numeric prefix for execution order: |
| 165 | + |
| 166 | +``` |
| 167 | +plugins/ |
| 168 | +├── 01.first.ts |
| 169 | +├── 02.second.ts |
| 170 | +└── 03.third.ts |
| 171 | +``` |
| 172 | + |
| 173 | +### Async Plugins |
| 174 | + |
| 175 | +```ts |
| 176 | +// plugins/api.ts |
| 177 | +export default defineNuxtPlugin(async (nuxtApp) => { |
| 178 | + const config = await fetch('/api/config').then(r => r.json()) |
| 179 | + |
| 180 | + return { |
| 181 | + provide: { |
| 182 | + config |
| 183 | + } |
| 184 | + } |
| 185 | +}) |
| 186 | +``` |
| 187 | + |
| 188 | +## Best Practices |
| 189 | + |
| 190 | +**Middleware:** |
| 191 | + |
| 192 | +- **Return navigation or nothing** - don't mutate state heavily |
| 193 | +- **Keep logic minimal** - delegate to composables/stores |
| 194 | +- **Use for guards & redirects** only |
| 195 | +- **Check meta properly** - `to.meta.requiresAuth` |
| 196 | +- **Global = `.global.ts`** suffix required |
| 197 | + |
| 198 | +**Plugins:** |
| 199 | + |
| 200 | +- **Use for app-wide functionality** only |
| 201 | +- **Provide via `provide`** for type safety |
| 202 | +- **Consider client/server context** - use `.client`/`.server` |
| 203 | +- **Minimize work** in plugin initialization |
| 204 | +- **Use hooks** for lifecycle events |
| 205 | + |
| 206 | +## Common Mistakes |
| 207 | + |
| 208 | +| ❌ Wrong | ✅ Right | |
| 209 | +| ------------------------------------ | ------------------------------------------------------------ | |
| 210 | +| `export default function({ route })` | `export default defineNuxtRouteMiddleware((to, from) => {})` | |
| 211 | +| Mutate route object | Return navigateTo() or nothing | |
| 212 | +| `middleware/auth.ts` (not global) | `middleware/auth.global.ts` (global) | |
| 213 | +| `redirect('/login')` | `return navigateTo('/login')` | |
| 214 | +| Plugin without defineNuxtPlugin | Wrap in defineNuxtPlugin() | |
| 215 | + |
| 216 | +## Middleware Example: Auth |
| 217 | + |
| 218 | +```ts |
| 219 | +// middleware/auth.global.ts |
| 220 | +export default defineNuxtRouteMiddleware((to, from) => { |
| 221 | + const auth = useAuthStore() |
| 222 | + |
| 223 | + // Public routes |
| 224 | + const publicRoutes = ['/', '/login', '/register'] |
| 225 | + if (publicRoutes.includes(to.path)) { |
| 226 | + return |
| 227 | + } |
| 228 | + |
| 229 | + // Check auth |
| 230 | + if (!auth.isAuthenticated) { |
| 231 | + return navigateTo('/login') |
| 232 | + } |
| 233 | + |
| 234 | + // Check role |
| 235 | + if (to.meta.requiresAdmin && !auth.isAdmin) { |
| 236 | + return abortNavigation('Access denied') |
| 237 | + } |
| 238 | +}) |
| 239 | +``` |
| 240 | + |
| 241 | +## Plugin Example: API Client |
| 242 | + |
| 243 | +```ts |
| 244 | +// plugins/api.ts |
| 245 | +export default defineNuxtPlugin((nuxtApp) => { |
| 246 | + const config = useRuntimeConfig() |
| 247 | + |
| 248 | + const api = $fetch.create({ |
| 249 | + baseURL: config.public.apiBase, |
| 250 | + onRequest({ request, options }) { |
| 251 | + const auth = useAuthStore() |
| 252 | + if (auth.token) { |
| 253 | + options.headers = { |
| 254 | + ...options.headers, |
| 255 | + Authorization: `Bearer ${auth.token}` |
| 256 | + } |
| 257 | + } |
| 258 | + }, |
| 259 | + onResponseError({ response }) { |
| 260 | + if (response.status === 401) { |
| 261 | + navigateTo('/login') |
| 262 | + } |
| 263 | + } |
| 264 | + }) |
| 265 | + |
| 266 | + return { |
| 267 | + provide: { |
| 268 | + api |
| 269 | + } |
| 270 | + } |
| 271 | +}) |
| 272 | +``` |
| 273 | + |
| 274 | +## Resources |
| 275 | + |
| 276 | +- Nuxt middleware: https://nuxt.com/docs/guide/directory-structure/middleware |
| 277 | +- Nuxt plugins: https://nuxt.com/docs/guide/directory-structure/plugins |
| 278 | +- Route middleware: https://nuxt.com/docs/getting-started/routing#route-middleware |
0 commit comments