deotalandAi/.shared/ui-ux-pro-max/data/stacks/nuxtjs.csv

16 KiB

1NoCategoryGuidelineDescriptionDoDon'tCode GoodCode BadSeverityDocs URL
21RoutingUse file-based routingCreate routes by adding files in pages directorypages/ directory with index.vueManual route configurationpages/dashboard/index.vueCustom router setupMediumhttps://nuxt.com/docs/getting-started/routing
32RoutingUse dynamic route parametersCreate dynamic routes with bracket syntax[id].vue for dynamic paramsHardcoded routes for dynamic contentpages/posts/[id].vuepages/posts/post1.vueMediumhttps://nuxt.com/docs/getting-started/routing
43RoutingUse catch-all routesHandle multiple path segments with [...slug][...slug].vue for catch-allMultiple nested dynamic routespages/[...slug].vuepages/[a]/[b]/[c].vueLowhttps://nuxt.com/docs/getting-started/routing
54RoutingDefine page metadata with definePageMetaSet page-level configuration and middlewaredefinePageMeta for layout middleware titleManual route meta configurationdefinePageMeta({ layout: 'admin', middleware: 'auth' })router.beforeEach for page configHighhttps://nuxt.com/docs/api/utils/define-page-meta
65RoutingUse validate for route paramsValidate dynamic route parameters before renderingvalidate function in definePageMetaManual validation in setupdefinePageMeta({ validate: (route) => /^\d+$/.test(route.params.id) })if (!valid) navigateTo('/404')Mediumhttps://nuxt.com/docs/api/utils/define-page-meta
76RenderingUse SSR by defaultServer-side rendering is enabled by defaultKeep ssr: true (default)Disable SSR unnecessarilyssr: true (default)ssr: false for all pagesHighhttps://nuxt.com/docs/guide/concepts/rendering
89DataFetchingUse useFetch for simple data fetchingWrapper around useAsyncData for URL fetchinguseFetch for API calls$fetch in onMountedconst { data } = await useFetch('/api/posts')onMounted(async () => { data.value = await $fetch('/api/posts') })Highhttps://nuxt.com/docs/api/composables/use-fetch
910DataFetchingUse useAsyncData for complex fetchingFine-grained control over async datauseAsyncData for CMS or custom fetchinguseFetch for non-URL data sourcesconst { data } = await useAsyncData('posts', () => cms.getPosts())const { data } = await useFetch(() => cms.getPosts())Mediumhttps://nuxt.com/docs/api/composables/use-async-data
1011DataFetchingUse $fetch for non-reactive requests$fetch for event handlers and non-component code$fetch in event handlers or server routesuseFetch in click handlersasync function submit() { await $fetch('/api/submit', { method: 'POST' }) }async function submit() { await useFetch('/api/submit') }Highhttps://nuxt.com/docs/api/utils/dollarfetch
1112DataFetchingUse lazy option for non-blocking fetchDefer data fetching for better initial loadlazy: true for below-fold contentBlocking fetch for non-critical datauseFetch('/api/comments', { lazy: true })await useFetch('/api/comments') for footerMediumhttps://nuxt.com/docs/api/composables/use-fetch
1213DataFetchingUse server option to control fetch locationChoose where data is fetchedserver: false for client-only dataServer fetch for user-specific client datauseFetch('/api/user-preferences', { server: false })useFetch for localStorage-dependent dataMediumhttps://nuxt.com/docs/api/composables/use-fetch
1314DataFetchingUse pick to reduce payload sizeSelect only needed fields from responsepick option for large responsesFetching entire objects when few fields neededuseFetch('/api/user', { pick: ['id', 'name'] })useFetch('/api/user') then destructureLowhttps://nuxt.com/docs/api/composables/use-fetch
1415DataFetchingUse transform for data manipulationTransform data before storing in statetransform option for data shapingManual transformation after fetchuseFetch('/api/posts', { transform: (posts) => posts.map(p => p.title) })const titles = data.value.map(p => p.title)Lowhttps://nuxt.com/docs/api/composables/use-fetch
1516DataFetchingHandle loading and error statesAlways handle pending and error statesCheck status pending error refsIgnoring loading states<div v-if="status === 'pending'">Loading...</div>No loading indicatorHighhttps://nuxt.com/docs/getting-started/data-fetching
1617LifecycleAvoid side effects in script setup rootMove side effects to lifecycle hooksSide effects in onMountedsetInterval in root script setuponMounted(() => { interval = setInterval(...) })<script setup>setInterval(...)</script>Highhttps://nuxt.com/docs/guide/concepts/nuxt-lifecycle
1718LifecycleUse onMounted for DOM accessAccess DOM only after component is mountedonMounted for DOM manipulationDirect DOM access in setuponMounted(() => { document.getElementById('el') })<script setup>document.getElementById('el')</script>Highhttps://nuxt.com/docs/api/composables/on-mounted
1819LifecycleUse nextTick for post-render accessWait for DOM updates before accessing elementsawait nextTick() after state changesImmediate DOM access after state changecount.value++; await nextTick(); el.value.focus()count.value++; el.value.focus()Mediumhttps://nuxt.com/docs/api/utils/next-tick
1920LifecycleUse onPrehydrate for pre-hydration logicRun code before Nuxt hydrates the pageonPrehydrate for client setuponMounted for hydration-critical codeonPrehydrate(() => { console.log(window) })onMounted for pre-hydration needsLowhttps://nuxt.com/docs/api/composables/on-prehydrate
2021ServerUse server/api for API routesCreate API endpoints in server/api directoryserver/api/users.ts for /api/usersManual Express setupserver/api/hello.ts -> /api/helloapp.get('/api/hello')Highhttps://nuxt.com/docs/guide/directory-structure/server
2122ServerUse defineEventHandler for handlersDefine server route handlersdefineEventHandler for all handlersexport default functionexport default defineEventHandler((event) => { return { hello: 'world' } })export default function(req, res) {}Highhttps://nuxt.com/docs/guide/directory-structure/server
2223ServerUse server/routes for non-api routesRoutes without /api prefixserver/routes for custom pathsserver/api for non-api routesserver/routes/sitemap.xml.tsserver/api/sitemap.xml.tsMediumhttps://nuxt.com/docs/guide/directory-structure/server
2324ServerUse getQuery and readBody for inputAccess query params and request bodygetQuery(event) readBody(event)Direct event accessconst { id } = getQuery(event)event.node.req.queryMediumhttps://nuxt.com/docs/guide/directory-structure/server
2425ServerValidate server inputAlways validate input in server handlersZod or similar for validationTrust client inputconst body = await readBody(event); schema.parse(body)const body = await readBody(event)Highhttps://nuxt.com/docs/guide/directory-structure/server
2526StateUse useState for shared reactive stateSSR-friendly shared state across componentsuseState for cross-component stateref for shared stateconst count = useState('count', () => 0)const count = ref(0) in composableHighhttps://nuxt.com/docs/api/composables/use-state
2627StateUse unique keys for useStatePrevent state conflicts with unique keysDescriptive unique keys for each stateGeneric or duplicate keysuseState('user-preferences', () => ({}))useState('data') in multiple placesMediumhttps://nuxt.com/docs/api/composables/use-state
2728StateUse Pinia for complex statePinia for advanced state management@pinia/nuxt for complex appsCustom state managementuseMainStore() with PiniaCustom reactive store implementationMediumhttps://nuxt.com/docs/getting-started/state-management
2829StateUse callOnce for one-time async operationsEnsure async operations run only oncecallOnce for store initializationDirect await in componentawait callOnce(store.fetch)await store.fetch() on every renderMediumhttps://nuxt.com/docs/api/utils/call-once
2930SEOUse useSeoMeta for SEO tagsType-safe SEO meta tag managementuseSeoMeta for meta tagsuseHead for simple metauseSeoMeta({ title: 'Home', ogTitle: 'Home', description: '...' })useHead({ meta: [{ name: 'description', content: '...' }] })Highhttps://nuxt.com/docs/api/composables/use-seo-meta
3031SEOUse reactive values in useSeoMetaDynamic SEO tags with refs or gettersComputed getters for dynamic valuesStatic values for dynamic contentuseSeoMeta({ title: () => post.value.title })useSeoMeta({ title: post.value.title })Mediumhttps://nuxt.com/docs/api/composables/use-seo-meta
3132SEOUse useHead for non-meta head elementsScripts styles links in headuseHead for scripts and linksuseSeoMeta for scriptsuseHead({ script: [{ src: '/analytics.js' }] })useSeoMeta({ script: '...' })Mediumhttps://nuxt.com/docs/api/composables/use-head
3233SEOInclude OpenGraph tagsAdd OG tags for social sharingogTitle ogDescription ogImageMissing social previewuseSeoMeta({ ogImage: '/og.png', twitterCard: 'summary_large_image' })No OG configurationMediumhttps://nuxt.com/docs/api/composables/use-seo-meta
3334MiddlewareUse defineNuxtRouteMiddlewareDefine route middleware properlydefineNuxtRouteMiddleware wrapperexport default functionexport default defineNuxtRouteMiddleware((to, from) => {})export default function(to, from) {}Highhttps://nuxt.com/docs/guide/directory-structure/middleware
3435MiddlewareUse navigateTo for redirectsRedirect in middleware with navigateToreturn navigateTo('/login')router.push in middlewareif (!auth) return navigateTo('/login')if (!auth) router.push('/login')Highhttps://nuxt.com/docs/api/utils/navigate-to
3536MiddlewareReference middleware in definePageMetaApply middleware to specific pagesmiddleware array in definePageMetaGlobal middleware for page-specificdefinePageMeta({ middleware: ['auth'] })Global auth check for one pageMediumhttps://nuxt.com/docs/guide/directory-structure/middleware
3637MiddlewareUse .global suffix for global middlewareApply middleware to all routesauth.global.ts for app-wide authManual middleware on every pagemiddleware/auth.global.tsmiddleware: ['auth'] on every pageMediumhttps://nuxt.com/docs/guide/directory-structure/middleware
3738ErrorHandlingUse createError for errorsCreate errors with proper status codescreateError with statusCodethrow new Errorthrow createError({ statusCode: 404, statusMessage: 'Not Found' })throw new Error('Not Found')Highhttps://nuxt.com/docs/api/utils/create-error
3839ErrorHandlingUse NuxtErrorBoundary for local errorsHandle errors within component subtreeNuxtErrorBoundary for component errorsGlobal error page for local errors<NuxtErrorBoundary @error="log"><template #error="{ error }">error.vue for component errorsMediumhttps://nuxt.com/docs/getting-started/error-handling
3940ErrorHandlingUse clearError to recover from errorsClear error state and optionally redirectclearError({ redirect: '/' })Manual error state resetclearError({ redirect: '/home' })error.value = nullMediumhttps://nuxt.com/docs/api/utils/clear-error
4041ErrorHandlingUse short statusMessageKeep statusMessage brief for securityShort generic messagesDetailed error info in statusMessagecreateError({ statusCode: 400, statusMessage: 'Bad Request' })createError({ statusMessage: 'Invalid user ID: 123' })Highhttps://nuxt.com/docs/getting-started/error-handling
4143LinkConfigure prefetch behaviorControl when prefetching occursprefetchOn for interaction-basedDefault prefetch for low-priority<NuxtLink prefetch-on="interaction">Always default prefetchLowhttps://nuxt.com/docs/api/components/nuxt-link
4244LinkUse useRouter for programmatic navigationNavigate programmaticallyuseRouter().push() for navigationDirect window.locationconst router = useRouter(); router.push('/dashboard')window.location.href = '/dashboard'Mediumhttps://nuxt.com/docs/api/composables/use-router
4345LinkUse navigateTo in composablesNavigate outside componentsnavigateTo() in middleware or pluginsuseRouter in non-component codereturn navigateTo('/login')router.push in middlewareMediumhttps://nuxt.com/docs/api/utils/navigate-to
4446AutoImportsLeverage auto-importsUse auto-imported composables directlyDirect use of ref computed useFetchManual imports for Nuxt composablesconst count = ref(0)import { ref } from 'vue'; const count = ref(0)Mediumhttps://nuxt.com/docs/guide/concepts/auto-imports
4547AutoImportsUse #imports for explicit importsExplicit imports when needed#imports for clarity or disabled auto-importsimport from 'vue' when auto-import enabledimport { ref } from '#imports'import { ref } from 'vue'Lowhttps://nuxt.com/docs/guide/concepts/auto-imports
4648AutoImportsConfigure third-party auto-importsAdd external package auto-importsimports.presets in nuxt.configManual imports everywhereimports: { presets: [{ from: 'vue-i18n', imports: ['useI18n'] }] }import { useI18n } everywhereLowhttps://nuxt.com/docs/guide/concepts/auto-imports
4749PluginsUse defineNuxtPluginDefine plugins properlydefineNuxtPlugin wrapperexport default functionexport default defineNuxtPlugin((nuxtApp) => {})export default function(ctx) {}Highhttps://nuxt.com/docs/guide/directory-structure/plugins
4850PluginsUse provide for injectionProvide helpers across appreturn { provide: {} } for type safetynuxtApp.provide without typesreturn { provide: { hello: (name) => `Hello ${name}!` } }nuxtApp.provide('hello', fn)Mediumhttps://nuxt.com/docs/guide/directory-structure/plugins
4951PluginsUse .client or .server suffixControl plugin execution environmentplugin.client.ts for client-onlyif (process.client) checksanalytics.client.tsif (process.client) { // analytics }Mediumhttps://nuxt.com/docs/guide/directory-structure/plugins
5052EnvironmentUse runtimeConfig for env varsAccess environment variables safelyruntimeConfig in nuxt.configprocess.env directlyruntimeConfig: { apiSecret: '', public: { apiBase: '' } }process.env.API_SECRET in componentsHighhttps://nuxt.com/docs/guide/going-further/runtime-config
5153EnvironmentUse NUXT_ prefix for env overrideOverride config with environment variablesNUXT_API_SECRET NUXT_PUBLIC_API_BASECustom env var namesNUXT_PUBLIC_API_BASE=https://api.example.comAPI_BASE=https://api.example.comHighhttps://nuxt.com/docs/guide/going-further/runtime-config
5254EnvironmentAccess public config with useRuntimeConfigGet public config in componentsuseRuntimeConfig().publicDirect process.env accessconst config = useRuntimeConfig(); config.public.apiBaseprocess.env.NUXT_PUBLIC_API_BASEHighhttps://nuxt.com/docs/api/composables/use-runtime-config
5355EnvironmentKeep secrets in private configServer-only secrets in runtimeConfig rootruntimeConfig.apiSecret (server only)Secrets in public configruntimeConfig: { dbPassword: '' }runtimeConfig: { public: { dbPassword: '' } }Highhttps://nuxt.com/docs/guide/going-further/runtime-config
5457PerformanceUse useLazyFetch for non-blocking dataAlias for useFetch with lazy: trueuseLazyFetch for secondary datauseFetch for all requestsconst { data } = useLazyFetch('/api/comments')await useFetch for comments sectionMediumhttps://nuxt.com/docs/api/composables/use-lazy-fetch
5558PerformanceUse lazy hydration for interactivityDelay component hydration until neededLazyComponent with hydration strategyImmediate hydration for all<LazyModal hydrate-on-visible/><Modal/> in footerLowhttps://nuxt.com/docs/guide/going-further/experimental-features