10 Nuxt 3 Tips and Tricks for Better Development
Level up your Nuxt 3 development with these powerful tips and tricks that will improve your workflow and application performance.
Table of Contents
1 Auto-imports for Composables
Leverage Nuxt 3 auto-import feature for cleaner code
Nuxt 3 automatically imports your composables from the composables/ directory. This means you can use them anywhere in your application without explicit imports.
// composables/useCounter.ts
export const useCounter = () => {
const count = ref(0)
const increment = () => count.value++
const decrement = () => count.value--
return {
count,
increment,
decrement
}
}
// Use anywhere in your app
const { count, increment } = useCounter()
Pro Tip
2 Server Routes with Event Handling
Create powerful server routes with event handling
Nuxt 3 server routes can handle events and return different response types. You can use them to create powerful APIs directly in your Nuxt application.
// server/api/events/[id].ts
export default defineEventHandler(async (event) => {
const id = getRouterParam(event, 'id')
const body = await readBody(event)
// Handle different HTTP methods
if (event.method === 'POST') {
return { status: 'created', id }
}
return { status: 'success', id }
})
Pro Tip
3 Dynamic Page Metadata
Optimize SEO with dynamic page metadata
Use useHead composable to dynamically set page metadata for better SEO and social sharing.
// pages/blog/[slug].vue
useHead({
title: computed(() => post.value?.title),
meta: [
{
name: 'description',
content: computed(() => post.value?.description)
},
{
property: 'og:image',
content: computed(() => post.value?.image)
}
]
})
Pro Tip
4 Middleware Shortcuts
Use middleware shortcuts for quick route guards
Nuxt 3 provides a convenient shorthand for defining route middleware inline, perfect for simple auth checks.
// pages/admin.vue
definePageMeta({
middleware: auth => {
if (!auth.isAuthenticated) {
return navigateTo('/login')
}
}
})
Pro Tip
5 State Management with useState
Efficient state management without external libraries
Use the built-in useState composable for persistent state management across components and pages.
// composables/useAppState.ts
export const useAppState = () => useState('app', () => ({
theme: 'light',
sidebar: false,
notifications: []
}))
// Use in components
const appState = useAppState()
appState.value.theme = 'dark'
Pro Tip
6 Custom Plugins with Hooks
Extend Nuxt with custom plugins and hooks
Create plugins that hook into Nuxt's lifecycle for advanced functionality.
// plugins/analytics.ts
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.hook('page:finish', () => {
console.log('Page navigation complete')
})
return {
provide: {
analytics: {
track: (event: string) => {
// Track user events
}
}
}
}
})
Pro Tip
7 Lazy Loading Components
Improve initial load time with lazy loading
Use the lazy prefix to automatically lazy-load components only when they're needed.
<!-- Lazy load heavy components -->
<template>
<div>
<LazyHeavyChart v-if="showChart" :data="chartData" />
</div>
</template>
Pro Tip
8 Runtime Config
Handle environment variables and runtime configuration
Use runtime config to safely expose environment variables to your application.
// nuxt.config.ts
export default defineNuxtConfig({
runtimeConfig: {
apiSecret: '', // Server-only
public: {
apiBase: '' // Client & Server
}
}
})
// Access in components
const config = useRuntimeConfig()
const { data } = await useFetch(config.public.apiBase + '/posts')
Pro Tip
9 Error Handling
Graceful error handling and custom error pages
Create custom error pages and handle errors gracefully throughout your application.
// error.vue
const handleError = () => clearError({ redirect: '/' })
// Example usage in components
try {
await someAsyncOperation()
} catch (error) {
handleError()
}
Pro Tip
10 Asset Handling
Optimize asset loading and management
Use Nuxt's built-in asset handling features for optimized images and other static assets.
// Automatic image optimization
<template>
<nuxt-img
src="/hero.jpg"
sizes="sm:100vw md:50vw lg:400px"
format="webp"
loading="lazy"
placeholder
/>
</template>
Pro Tip
Anton Andresen
Full Stack Developer & Nuxt Enthusiast