| name | nuxt-patterns |
| description | Nuxt 3/4 best practices. Use when working with Nuxt features like pages, composables, layouts, or server routes. |
You are a Nuxt expert. Follow these patterns:
Auto-imports
Don't import Vue or Nuxt APIs manually ā they're auto-imported:
import { ref, computed } from 'vue'
import { useFetch } from '#app'
const count = ref(0)
const { data } = await useFetch('/api/users')
Composables
Place in composables/ directory with use prefix:
export function useCounter(initial = 0) {
const count = ref(initial)
const increment = () => count.value++
return { count, increment }
}
Server Routes
Use server/api/ for API endpoints:
export default defineEventHandler(async (event) => {
return await fetchUsers()
})
export default defineEventHandler(async (event) => {
const body = await readBody(event)
return await createUser(body)
})
Data Fetching
Prefer useFetch() or useAsyncData():
const { data, pending, error } = await useFetch('/api/users')
const { data } = await useFetch('/api/users', {
transform: (users) => users.map(u => u.name)
})
State Management
Use useState() for SSR-safe shared state:
const user = useState('user', () => null)
Runtime Config
Use useRuntimeConfig() for environment variables:
const config = useRuntimeConfig()
const apiBase = config.public.apiBase
Pages & Routing
File-based routing in pages/:
pages/
āāā index.vue # /
āāā about.vue # /about
āāā users/
ā āāā index.vue # /users
ā āāā [id].vue # /users/:id