[{"data":1,"prerenderedAt":688},["ShallowReactive",2],{"all-questions-nuxt":3},{"beginner":4,"intermediate":318,"advanced":479},[5,19,31,44,54,65,76,88,98,111,121,131,144,156,168,180,191,203,213,225,237,250,262,274,286,298,308],{"id":6,"category":7,"question":8,"answer":9,"level":10,"tags":11,"interviewTip":16,"commonFollowUp":17,"realWorldExample":18},1,"Core Concepts","What is Nuxt.js?","**Concept Explanation:** Nuxt.js is an open-source framework built on top of Vue.js that simplifies the development of universal (server-side rendered), static, or single-page applications. It provides a powerful set of conventions, modules, and built-in features like file-based routing, auto-imports, and server engine (Nitro).\n\n**Internal Working:** Nuxt uses a modular architecture: the `nuxt` module handles the build process and development server, while Nitro (the server engine) manages server-side rendering, API routes, and deployment adapters. The framework abstracts complex configurations like Webpack\u002FVite, Vue Router, and Vue Server Renderer into a zero-config experience.\n\n**Request Flow (SSR mode):** 1) User requests a page → 2) Nitro server receives request → 3) Nuxt runs middleware and route validation → 4) Vue component renders on server (async data fetched via `useFetch`\u002F`useAsyncData`) → 5) HTML string generated and sent to client → 6) Client hydrates the page (makes it interactive).\n\n**Lifecycle:** Build time (`nuxi build`) → Server start → On each request: `serverMiddleware` → route middleware → component `setup` (server) → render → send HTML → client hydration → client-side navigation.\n\n**Syntax & Code Example:**\n```vue\n\u003C!-- pages\u002Findex.vue -->\n\u003Ctemplate>\n  \u003Cdiv>{{ message }}\u003C\u002Fdiv>\n\u003C\u002Ftemplate>\n\u003Cscript setup>\nconst message = 'Hello Nuxt!'\n\u003C\u002Fscript>\n```\nNo router configuration needed—just create a `.vue` file in `pages\u002F`.\n\n**Practical Example:** A blog with dynamic posts: create `pages\u002Fposts\u002F[id].vue`, Nuxt automatically generates routes like `\u002Fposts\u002F1`.\n\n**Common Mistakes:** Forgetting to use `definePageMeta` for layout overrides; using browser APIs in server context without checking `process.client`.\n\n**Edge Cases:** When using `ssr: false`, the page renders like an SPA – no server HTML, hydration happens after JS loads.\n\n**Interview Follow-ups:** \"How does Nuxt differ from a custom Vue + Vue Router + Vuex setup?\" \"What problem does Nitro solve?\"\n\n**Best Practices:** Use Nuxt layers for code reuse; leverage auto-imports; keep pages focused on presentation, move logic to composables.\n\n**Performance Considerations:** Nuxt automatically splits code by route; static assets are fingerprinted; Nitro enables caching headers out of the box.\n\n**SEO Considerations:** SSR provides full HTML to crawlers; use `useHead` for meta tags; SSG pre-renders content for lightning-fast SEO.\n\n**Production Recommendations:** Deploy with appropriate Nitro adapter (Node.js, Vercel, Cloudflare); enable CDN caching; use `nuxt generate` for static sites.\n\n**Latest Nuxt Patterns:** Nuxt 3 uses Vue 3 Composition API as default; Nitro universal server; built-in TypeScript support.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F Use definePageMeta with typed route params\ndefinePageMeta({\n  validate: async (route) => {\n    return \u002F\\d+\u002F.test(route.params.id as string)\n  }\n})\n```\n\n**Interview Tip:** Emphasize that Nuxt is not just a Vue wrapper—it's a full-stack framework with its own server engine (Nitro), making it comparable to Next.js but for Vue.\n\n**Common Follow-up:** \"Can I use Nuxt without server-side rendering?\"\n\n**Real-world Example:** An e-commerce site using Nuxt: product pages pre-rendered (SSG) for static data, cart uses client-side rendering (`ssr: false`), and checkout uses SSR for security.","beginner",[12,13,14,15],"nuxt","framework","vue","basics","Emphasize that Nuxt is not just a Vue wrapper—it's a full-stack framework with its own server engine (Nitro), making it comparable to Next.js but for Vue.","Can I use Nuxt without server-side rendering?","An e-commerce site using Nuxt: product pages pre-rendered (SSG) for static data, cart uses client-side rendering (`ssr: false`), and checkout uses SSR for security.",{"id":20,"category":7,"question":21,"answer":22,"level":10,"tags":23,"interviewTip":28,"commonFollowUp":29,"realWorldExample":30},2,"Why use Nuxt? What problems does it solve?","**Concept Explanation:** Nuxt solves the main pain points of building Vue applications: manual routing configuration, lack of SEO for SPAs, complex SSR setup, performance optimizations, and deployment concerns. It provides a convention-over-configuration approach that boosts developer productivity.\n\n**Internal Working:** Nuxt integrates Vue Router, Vue Server Renderer, Vite\u002FWebpack, and a server engine (Nitro) into one seamless system. It generates routes from the `pages\u002F` folder, pre-configures code splitting, and provides auto-imports for composables and components.\n\n**Request Flow (Benefit perspective):** With plain Vue SPA, browser downloads empty HTML then JS, causing slow initial paint and poor SEO. Nuxt with SSR sends fully-rendered HTML immediately, improving perceived performance and crawler visibility.\n\n**Lifecycle Savings:** No need to manually set up Vue Router routes (file-based), no need to configure server for SSR (Nitro handles it), no need to write `import` statements for components (auto-import).\n\n**Syntax & Code Example (Comparison):**\nPlain Vue + Vue Router:\n```js\n\u002F\u002F router.js – manual route definition\nconst routes = [\n  { path: '\u002F', component: Home },\n  { path: '\u002Fabout', component: About }\n]\n```\nNuxt: just create `pages\u002Findex.vue` and `pages\u002Fabout.vue`.\n\n**Practical Example:** Adding a new page in a large app: In Nuxt, create a file; in Vue, update router config, update navigation menu, ensure lazy-loading is set up. Nuxt reduces boilerplate by ~60%.\n\n**Common Mistakes:** Overusing custom server routes when Nitro server routes suffice; not leveraging Nuxt modules (e.g., `@nuxtjs\u002Ftailwindcss`) that save enormous time.\n\n**Edge Cases:** When using hybrid rendering, need to understand route rules – but Nuxt makes it declarative.\n\n**Interview Follow-ups:** \"What are the trade-offs of using Nuxt vs plain Vue?\" \"How does Nuxt handle code splitting differently?\"\n\n**Best Practices:** Use Nuxt modules for common integrations (Auth, SEO, PWA); follow the `server\u002Fapi` pattern for backend endpoints; leverage `nuxt generate` for static sites.\n\n**Performance Considerations:** Automatic code splitting per route; prefetching of linked pages; asset optimization; image optimization via `@nuxt\u002Fimage`.\n\n**SEO Considerations:** Full control over meta tags via `useHead`; canonical URLs; sitemap generation via module; JSON-LD structured data support.\n\n**Production Recommendations:** Use `nuxt build` for SSR deployments; `nuxt generate` for static hosting; enable `routeRules` for hybrid caching.\n\n**Latest Nuxt Patterns:** Nuxt 3 introduces Nitro – deploy anywhere (serverless, edge, Node); built-in TypeScript; payload extraction for reducing HTML size.\n\n**TypeScript Example:** Nuxt generates types for auto-imports and pages; use `~\u002Ftypes` folder for global types.\n\n**Interview Tip:** Highlight that Nuxt reduces the 'glue code' needed to assemble a production-ready Vue app, often cutting initial setup time from days to minutes.\n\n**Common Follow-up:** \"What are the downsides of using Nuxt?\"\n\n**Real-world Example:** A startup building a content-heavy marketing site needed SEO. With plain Vue, they would need SSR setup (complex). With Nuxt, they had SSR working in 5 minutes and generated static versions for blog posts.",[24,25,26,27],"benefits","productivity","seo","ssr","Highlight that Nuxt reduces the 'glue code' needed to assemble a production-ready Vue app, often cutting initial setup time from days to minutes.","What are the downsides of using Nuxt?","A startup building a content-heavy marketing site needed SEO. With plain Vue, they would need SSR setup (complex). With Nuxt, they had SSR working in 5 minutes and generated static versions for blog posts.",{"id":32,"category":33,"question":34,"answer":35,"level":10,"tags":36,"interviewTip":41,"commonFollowUp":42,"realWorldExample":43},3,"Architecture","Explain Nuxt 3 architecture: how do Vue 3, Vite, and Nitro work together?","**Concept Explanation:** Nuxt 3 architecture is layered: on top, the Vue 3 Composition API drives UI reactivity. The build tool (Vite by default, or Webpack) bundles the client application. Nitro is the server engine that handles SSR, API routes, and deployment adapters. Nuxt itself orchestrates them with conventions.\n\n**Internal Working:** During `nuxt dev` or `nuxt build`, Nuxt uses `unjs\u002Fknitwork` to generate virtual files (e.g., `.nuxt\u002Frouter.ts`). It invokes Vite to build client and server entries. Nitro takes the server entry plus `server\u002F` directory and creates a deployable server output using `rollup`. The three parts run in isolated contexts but share the same TypeScript types.\n\n**Request Flow:** 1) HTTP request → Nitro server (using `h3` server) → 2) Nuxt middleware layer (converted to Nitro plugins) → 3) Nitro routes: API (server\u002Fapi) or SSR (server\u002Frenderer) → 4) Vue 3 component rendering on server → 5) HTML returned → client-side Vue 3 hydration.\n\n**Lifecycle:** Build: Nuxt collects pages\u002Fcomponents → Vite builds client bundle → Nitro builds server bundle. Runtime: Nitro listens → request triggers Vue rendering → Vue 3 reactivity tracks dependencies.\n\n**Syntax & Code Example (Nuxt config):**\n```ts\nexport default defineNuxtConfig({\n  ssr: true,          \u002F\u002F Enable SSR\n  nitro: { preset: 'vercel' }, \u002F\u002F Deployment target\n  vite: {            \u002F\u002F Pass Vite options\n    css: { preprocessorOptions: { scss: {} } }\n  }\n})\n```\n\n**Practical Example:** Build a server API endpoint at `server\u002Fapi\u002Fhello.ts` that uses Nitro's storage, while frontend uses `useFetch` – Vite handles hot reload, Nitro serves API without separate server.\n\n**Common Mistakes:** Trying to use Node.js modules (fs, path) directly in Vue components – those should go in `server\u002F` code only. Forgetting that Nitro runs in a sandbox on edge runtimes.\n\n**Edge Cases:** When using `ssr: false`, Nitro still builds a server but bypasses Vue rendering, serving an empty HTML shell that client hydrates.\n\n**Interview Follow-ups:** \"How does Nuxt integrate Vite's server vs Nitro's server?\" \"Can I replace Nitro with a custom server?\"\n\n**Best Practices:** Keep server logic in `server\u002F`; use `useRuntimeConfig` for environment variables; leverage Nitro's `defineEventHandler` for API endpoints.\n\n**Performance Considerations:** Vite's fast HMR improves dev experience; Nitro's lazy-loaded chunks reduce cold start times on serverless.\n\n**SEO Considerations:** Not directly related to architecture but SSR enabled by Nitro ensures crawlers see content.\n\n**Production Recommendations:** Use Nitro presets (e.g., `vercel-edge`, `cloudflare-modules`) for platform-optimized builds; enable `nitro.static` for fully static sites.\n\n**Latest Nuxt Patterns:** Nuxt 3 removed the requirement for a separate server; Nitro supports hybrid rendering at route level, which is unique among meta-frameworks.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F server\u002Fapi\u002Fuser.ts – typed event handler\nexport default defineEventHandler((event) => {\n  const id = getRouterParam(event, 'id') \u002F\u002F inferred as string | undefined\n  return { id }\n})\n```\n\n**Interview Tip:** Emphasize that Nitro is not just 'Nuxt's server' – it's a standalone server engine that can be used independently, which demonstrates Nuxt's modular design.\n\n**Common Follow-up:** \"Can I use Nuxt without Nitro?\"\n\n**Real-world Example:** A corporate portal needed both public marketing pages (SSR) and an admin dashboard (SPA). Nuxt's architecture allowed the same Vue codebase with Nitro handling routes – \u002Fadmin → ssr: false, everything else SSR.",[37,38,39,40],"architecture","nitro","vite","vue3","Emphasize that Nitro is not just 'Nuxt's server' – it's a standalone server engine that can be used independently, which demonstrates Nuxt's modular design.","Can I use Nuxt without Nitro?","A corporate portal needed both public marketing pages (SSR) and an admin dashboard (SPA). Nuxt's architecture allowed the same Vue codebase with Nitro handling routes – \u002Fadmin → ssr: false, everything else SSR.",{"id":45,"category":7,"question":46,"answer":47,"level":10,"tags":48,"interviewTip":51,"commonFollowUp":52,"realWorldExample":53},4,"Vue vs Nuxt: When should you choose one over the other?","**Concept Explanation:** Vue is a progressive UI library for building interactive interfaces. Nuxt is a framework built on Vue that adds server-side rendering, static site generation, file-based routing, and server API capabilities. Choose Vue when you need a lightweight SPA or are embedding into existing backend. Choose Nuxt when you need SEO, performance, or a full-stack toolchain.\n\n**Internal Working:** Vue alone requires manual setup of Vue Router, Pinia\u002FVuex, and a build tool (Vite). Nuxt bundles these with conventions and adds server-side capabilities via Nitro.\n\n**Request Flow:** With plain Vue SPA, server sends empty HTML, browser downloads JS, then renders. With Nuxt (SSR), server sends fully-rendered HTML, then hydrates. This drastically changes first contentful paint and search engine crawling.\n\n**Lifecycle Differences:** Vue SPA: page loads once, all navigation is client-side. Nuxt: can do both client-side navigation (after hydration) and initial server rendering.\n\n**Syntax & Code Example (Routing):**\nVue Router:\n```js\nconst routes = [{ path: '\u002Fuser\u002F:id', component: User }]\n```\nNuxt: create `pages\u002Fuser\u002F[id].vue` – no route config needed.\n\n**Practical Example:** A simple admin dashboard that users access after login (SEO irrelevant) → Vue is fine. A marketing site with blog, product pages, needing Google rankings → Nuxt required.\n\n**Common Mistakes:** Choosing Nuxt for a simple widget that will be embedded in a WordPress site; this adds unnecessary complexity and bundle size.\n\n**Edge Cases:** Vue can also do SSR via `vue-server-renderer`, but setup is complex. Nuxt abstracts that complexity.\n\n**Interview Follow-ups:** \"Can you incrementally adopt Nuxt in an existing Vue project?\" \"What about performance overhead of Nuxt?\"\n\n**Best Practices:** Use Nuxt for applications requiring SEO, fast initial load, or that will scale to many pages. Use Vue for embedded components, simple SPAs, or when server resources are constrained.\n\n**Performance Considerations:** Nuxt has a larger baseline bundle due to framework overhead (~20KB gzipped). Vue SPA can be smaller but has slower initial paint due to empty HTML.\n\n**SEO Considerations:** Vue SPA is crawlable by Google (since 2018) but not reliably by other crawlers (social media bots, Baidu). Nuxt SSR\u002FSSG guarantees full content visibility.\n\n**Production Recommendations:** For public-facing sites, Nuxt is safer; for authenticated dashboards, Vue SPA is fine. Hybrid (Nuxt with `ssr: false` for certain routes) gives best of both.\n\n**Latest Nuxt Patterns:** Nuxt 3's auto-imports and TypeScript support make it almost as lightweight to develop as plain Vue, reducing the gap.\n\n**TypeScript Example:** Both support TS, but Nuxt generates types for pages, auto-imports, and runtime config, providing better DX.\n\n**Interview Tip:** State that the decision is less about technical capability and more about required features: 'If you need SEO or server-side logic, choose Nuxt; if you need a lightweight component library, choose Vue.'\n\n**Common Follow-up:** \"What about Next.js vs Nuxt?\"\n\n**Real-world Example:** A company built a customer portal (login required) with Nuxt but experienced higher server costs. They migrated to Vue SPA and saved 60% on hosting, with no SEO penalty because the portal was behind auth.",[14,49,50],"comparison","use-case","State that the decision is less about technical capability and more about required features: 'If you need SEO or server-side logic, choose Nuxt; if you need a lightweight component library, choose Vue.'","What about Next.js vs Nuxt?","A company built a customer portal (login required) with Nuxt but experienced higher server costs. They migrated to Vue SPA and saved 60% on hosting, with no SEO penalty because the portal was behind auth.",{"id":55,"category":56,"question":57,"answer":58,"level":10,"tags":59,"interviewTip":62,"commonFollowUp":63,"realWorldExample":64},5,"Rendering Modes","What is SSR (Server-Side Rendering) in Nuxt and how does it work?","**Concept Explanation:** SSR means that when a user requests a page, Nuxt runs the Vue component on the server, generates the full HTML string, and sends it to the browser. The browser then downloads the JavaScript and 'hydrates' the page, making it interactive. This provides fast first paint and full SEO.\n\n**Internal Working:** Nuxt uses Vue's `renderToString` function (via `@vue\u002Fserver-renderer`). The server creates a Vue app instance per request, executes `setup()` and `useAsyncData`, resolves all promises, then serializes the resulting VNode tree to HTML. Data needed for hydration is embedded as `window.__NUXT__`.\n\n**Request Flow:** 1) Browser GET `\u002Fproducts` → 2) Nitro server receives → 3) Nuxt loads `pages\u002Fproducts.vue` component → 4) Runs composables (`useFetch`, `useAsyncData`) and waits for them to resolve → 5) Renders component to HTML string → 6) Injects state and HTML into a template → 7) Sends response → 8) Browser displays HTML instantly → 9) Downloads JS bundle → 10) Hydration: Vue attaches event listeners and makes page interactive.\n\n**Lifecycle:** Server side: `setup()` runs once per request, no `onMounted` yet. Client side: after HTML loads, `onMounted` runs, hydration occurs. Subsequent navigations use client-side routing (SPA mode) unless full page reload.\n\n**Syntax & Code Example:**\n```vue\n\u003Cscript setup>\n\u002F\u002F This code runs on server AND client (during hydration)\nconst { data, pending } = useFetch('\u002Fapi\u002Fproducts')\n\nonMounted(() => {\n  \u002F\u002F This runs only on client\n  console.log('Hydrated!')\n})\n\u003C\u002Fscript>\n```\n\n**Practical Example:** An e-commerce product page with dynamic pricing. SSR ensures the price is visible before JS loads, critical for conversions. Also, crawlers see the full content.\n\n**Common Mistakes:** Using `localStorage` or `window` without `process.client` guard; performing side effects in top-level `setup` that cause hydration mismatches; not handling async data loading (page may render without data if not awaited).\n\n**Edge Cases:** When using `useAsyncData` without `server: true`, data fetching only happens on client, defeating SSR purpose. Also, hydration mismatch if server HTML and client initial render differ (e.g., random IDs).\n\n**Interview Follow-ups:** \"How does Nuxt handle async data during SSR?\" \"What is hydration and why does it matter?\"\n\n**Best Practices:** Use `useFetch` or `useAsyncData` for all data needed for SSR; avoid browser-specific APIs in `setup`; wrap client-only code in `onMounted` or `client-only` component.\n\n**Performance Considerations:** SSR increases server CPU load; each request renders the page. Use caching (routeRules) to mitigate. Also, payload extraction reduces HTML size by sending data separately.\n\n**SEO Considerations:** SSR provides complete HTML to search engines; ensures social media share previews show correct metadata; time-to-first-byte may be higher but content appears immediately.\n\n**Production Recommendations:** Deploy to platforms with SSR support (Node.js hosting, Vercel, Netlify Functions). Enable `routeRules` to cache frequently visited pages (e.g., every 60 seconds). Use CDN for static assets.\n\n**Latest Nuxt Patterns:** Nuxt 3 introduces 'payload extraction' – data fetched in SSR is sent as a separate payload, reducing HTML size and improving performance.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F useAsyncData with typed return\nconst { data } = useAsyncData\u003C{ id: number; name: string }>('product', () => $fetch('\u002Fapi\u002Fproduct\u002F1'))\n```\n\n**Interview Tip:** Emphasize that SSR isn't just about SEO – it improves perceived performance because users see content while JS loads. But it's not a silver bullet: compute-heavy pages may be slower than CSR.\n\n**Common Follow-up:** \"How do you prevent SSR for specific parts of a page?\"\n\n**Real-world Example:** A news website uses SSR to ensure article text appears immediately and Google News crawler indexes the full content. They use `client-only` components for interactive ads that don't need SEO.",[27,60,61,26],"server-side","rendering","Emphasize that SSR isn't just about SEO – it improves perceived performance because users see content while JS loads. But it's not a silver bullet: compute-heavy pages may be slower than CSR.","How do you prevent SSR for specific parts of a page?","A news website uses SSR to ensure article text appears immediately and Google News crawler indexes the full content. They use `client-only` components for interactive ads that don't need SEO.",{"id":66,"category":56,"question":67,"answer":68,"level":10,"tags":69,"interviewTip":73,"commonFollowUp":74,"realWorldExample":75},6,"What is CSR (Client-Side Rendering) in Nuxt and when would you use it?","**Concept Explanation:** CSR means the server sends an almost empty HTML shell, and all content is rendered in the browser after JavaScript loads. In Nuxt, you can enable CSR per route or globally by setting `ssr: false`. This behaves like a traditional Single Page Application (SPA).\n\n**Internal Working:** When `ssr: false`, Nitro still runs but bypasses the Vue SSR renderer. The server responds with a minimal HTML template that includes the `\u003Cdiv id=\"__nuxt\">` container and script tags to load the client bundle. The browser downloads the JS, executes it, mounts the Vue app, and then fetches data and renders the page.\n\n**Request Flow:** 1) Browser requests page → 2) Nitro server returns index.html (empty shell) → 3) Browser downloads JS + CSS bundles → 4) Vue app mounts → 5) `useFetch`\u002F`useAsyncData` run on client → 6) Data fetched and components render → 7) User sees fully interactive page.\n\n**Lifecycle:** No server-side rendering occurs. `setup()` runs only on client. `onMounted` runs as usual. Data fetching happens after JS loads, which may cause layout shifts.\n\n**Syntax & Code Example (Global CSR):**\n```ts\n\u002F\u002F nuxt.config.ts\nexport default defineNuxtConfig({\n  ssr: false  \u002F\u002F Entire app becomes SPA\n})\n```\nPer route CSR using route rules:\n```ts\nrouteRules: {\n  '\u002Fdashboard\u002F**': { ssr: false }  \u002F\u002F All dashboard routes are SPA\n}\n```\n\n**Practical Example:** A user settings page after login, where SEO is irrelevant, and you want to reduce server load. Or an internal admin panel with real-time data, where initial load speed doesn't matter.\n\n**Common Mistakes:** Setting `ssr: false` globally without realizing you lose SEO on all pages; not handling loading states appropriately because content appears later.\n\n**Edge Cases:** CSR pages can still use `useFetch` and composables – they just run on client. Also, `useAsyncData`'s `server` option has no effect when `ssr: false`.\n\n**Interview Follow-ups:** \"How does navigation differ between SSR and CSR pages in Nuxt?\" \"Can you mix CSR and SSR?\"\n\n**Best Practices:** Only use CSR for private areas (behind authentication) or pages where search engine visibility is not needed. Always show loading indicators because initial paint is blank.\n\n**Performance Considerations:** CSR has lower server costs (serving static files) but higher client-side rendering cost and slower First Contentful Paint (FCP). Ideal for low-traffic internal tools.\n\n**SEO Considerations:** CSR is not recommended for public-facing content because search engine crawlers may not execute JavaScript or may see empty HTML. Google can index CSR but with lower priority and potential delays.\n\n**Production Recommendations:** Deploy CSR-only apps to static hosting (CDN) like Netlify or Vercel (static). Combine with `nuxi generate` to pre-render key pages as SSG if needed.\n\n**Latest Nuxt Patterns:** Nuxt 3's hybrid rendering allows per-route CSR, so you don't have to choose globally. Use `routeRules` with `ssr: false` for selective CSR.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F No special TS needed; just set config\ndefineNuxtConfig({ ssr: false })\n```\n\n**Interview Tip:** Clarify that CSR in Nuxt is identical to a Vue SPA but with Nuxt's DX (auto-imports, file routing). The main advantage is you can later switch routes to SSR without refactoring.\n\n**Common Follow-up:** \"What's the difference between CSR and SSG?\"\n\n**Real-world Example:** A CRM application for sales team – pages are behind login, data changes every second (live updates), and SEO is irrelevant. CSR reduces server costs significantly (no SSR compute per request). They used Nuxt with `ssr: false` and deployed static files to S3 + CloudFront.",[70,71,72,61],"csr","spa","client-side","Clarify that CSR in Nuxt is identical to a Vue SPA but with Nuxt's DX (auto-imports, file routing). The main advantage is you can later switch routes to SSR without refactoring.","What's the difference between CSR and SSG?","A CRM application for sales team – pages are behind login, data changes every second (live updates), and SEO is irrelevant. CSR reduces server costs significantly (no SSR compute per request). They used Nuxt with `ssr: false` and deployed static files to S3 + CloudFront.",{"id":77,"category":56,"question":78,"answer":79,"level":10,"tags":80,"interviewTip":85,"commonFollowUp":86,"realWorldExample":87},7,"What is SSG (Static Site Generation) in Nuxt and how does it work?","**Concept Explanation:** Static Site Generation (SSG) pre-renders pages at build time into static HTML files. When a user requests a page, the server immediately serves the pre-built HTML without any server-side processing. Nuxt achieves this via `nuxi generate` command, which crawls your routes and creates `.html` files.\n\n**Internal Working:** During `nuxt generate`, Nuxt starts a Nitro server in memory, visits each route (or routes defined in `nuxt.config.ts`), runs the SSR rendering pipeline, and saves the resulting HTML to `dist\u002F` directory. It also generates a payload (JSON) for client-side hydration. For dynamic routes like `[id].vue`, you must provide `generate.routes` or use `definePageMeta` with `crawlLinks`.\n\n**Request Flow:** Build time → Nuxt renders each route → outputs static HTML + JS bundles → Deploy to CDN → User requests page → CDN serves HTML instantly → Browser hydrates → Client-side navigation uses pre-generated JSON payloads.\n\n**Lifecycle:** Build: each page's `setup()` and data fetching run once, at build time. Runtime: no server-side rendering happens; static files are served.\n\n**Syntax & Code Example (generate):**\n```bash\nnuxi generate\n```\nConfig for dynamic routes:\n```ts\nexport default defineNuxtConfig({\n  nitro: { prerender: { routes: ['\u002Fposts\u002F1', '\u002Fposts\u002F2'] } },\n  \u002F\u002F or use generate.routes (deprecated in Nuxt 3, prefer nitro.prerender)\n})\n```\nOr use `definePageMeta`:\n```vue\n\u003Cscript setup>\ndefinePageMeta({\n  prerender: true  \u002F\u002F force this route to be prerendered even in SSR mode\n})\n\u003C\u002Fscript>\n```\n\n**Practical Example:** A blog with 1000 articles. Instead of generating HTML on each request (SSR), you pre-render all articles at build time. Each article loads instantly with excellent caching.\n\n**Common Mistakes:** Not generating dynamic routes – Nuxt won't know to create `\u002Fposts\u002F1` unless you provide the list. Using server-only features (like `$fetch` with internal API that won't exist at build time).\n\n**Edge Cases:** When using SSG with client-side only data (e.g., user-specific dashboard), you can still use `ssr: false` on those routes. Also, incremental static regeneration (ISR) is not built-in but can be achieved with `routeRules` + CDN revalidation.\n\n**Interview Follow-ups:** \"How does SSG handle frequently changing data?\" \"Can you mix SSG and SSR?\"\n\n**Best Practices:** Use SSG for content that rarely changes (blogs, documentation, marketing pages). For dynamic data, use client-side fetching or hybrid with `ssr: false`. Pre-generate only critical pages, leave others for client-side.\n\n**Performance Considerations:** SSG offers the best performance: no server compute, CDN cached HTML, fast Time To First Byte (TTFB). Build time increases with number of pages; use `crawlLinks` to automatically discover pages.\n\n**SEO Considerations:** SSG is excellent for SEO – full HTML content is served instantly, and crawlers see everything. Combine with `useHead` for meta tags.\n\n**Production Recommendations:** Deploy generated `dist\u002F` folder to any static hosting (Netlify, Vercel, AWS S3, Cloudflare Pages). Set up CI to regenerate on content changes (e.g., webhook from CMS).\n\n**Latest Nuxt Patterns:** Nuxt 3 uses Nitro's prerendering, which is more powerful than Nuxt 2's generate. You can also use `routeRules: { '\u002F': { static: true } }` for hybrid SSG.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F definePageMeta with typed runtime config\ndefinePageMeta({\n  prerender: true,\n  \u002F\u002F SSG only, no runtime config needed\n})\n```\n\n**Interview Tip:** Emphasize that SSG is not 'dead' for dynamic content – you can combine SSG with client-side data fetching (e.g., comments section fetches after load).\n\n**Common Follow-up:** \"What's the difference between SSG and SSR in terms of deployment?\"\n\n**Real-world Example:** A documentation website (like Vue.js docs) uses SSG. Thousands of pages, each needs fast load and SEO. Build runs on every git push, then static files are served via CDN. This costs near zero to host and performs excellently worldwide.",[81,82,83,84],"ssg","static","generation","jamstack","Emphasize that SSG is not 'dead' for dynamic content – you can combine SSG with client-side data fetching (e.g., comments section fetches after load).","What's the difference between SSG and SSR in terms of deployment?","A documentation website (like Vue.js docs) uses SSG. Thousands of pages, each needs fast load and SEO. Build runs on every git push, then static files are served via CDN. This costs near zero to host and performs excellently worldwide.",{"id":89,"category":56,"question":90,"answer":91,"level":10,"tags":92,"interviewTip":95,"commonFollowUp":96,"realWorldExample":97},8,"What is hybrid rendering in Nuxt and how do you configure it?","**Concept Explanation:** Hybrid rendering allows you to choose the rendering mode (SSR, CSR, or SSG) per route or per pattern. For example, you can have your homepage SSR for SEO, your blog posts SSG for speed, and your admin dashboard CSR for interactivity – all in one Nuxt application.\n\n**Internal Working:** Nitro (Nuxt's server engine) evaluates a set of route rules at request time. When a request arrives, Nitro matches the URL against defined patterns (e.g., `\u002Fblog\u002F**`) and applies the corresponding rule: `ssr: false` (CSR), `static: true` (SSG pre-rendered), or `ssr: true` (default SSR). For SSG routes, Nitro serves pre-generated HTML; for CSR routes, it returns the SPA shell.\n\n**Request Flow:** 1) Request `\u002Fblog\u002Fpost-1` → 2) Nitro matches route rule `\u002Fblog\u002F**` with `static: true` → 3) Nitro serves pre-built `blog\u002Fpost-1\u002Findex.html` → 4) Done. Another request `\u002Fdashboard` → matches `ssr: false` → Nitro serves SPA shell → client-side renders. Request `\u002Fproducts` (no rule) → defaults to SSR.\n\n**Lifecycle:** At build time, routes marked `static: true` are pre-rendered. At runtime, Nitro applies rules without re-running SSR logic for CSR\u002FSSG routes.\n\n**Syntax & Code Example (nuxt.config.ts):**\n```ts\nexport default defineNuxtConfig({\n  routeRules: {\n    '\u002F': { ssr: true },                    \u002F\u002F SSR homepage\n    '\u002Fblog\u002F**': { static: true },          \u002F\u002F Pre-render all blog posts\n    '\u002Fadmin\u002F**': { ssr: false },           \u002F\u002F SPA for admin area\n    '\u002Fapi\u002F**': { cors: true, headers: { 'X-Custom': 'value' } }, \u002F\u002F API rules\n    '\u002Fold-page': { redirect: '\u002Fnew-page' }\n  }\n})\n```\n\n**Practical Example:** A SaaS landing page: `\u002F` (SSR for SEO), `\u002Fpricing` (SSG – rarely changes), `\u002Fapp\u002Fdashboard` (CSR – user-specific data), `\u002Fblog\u002F*` (SSG for performance). All in one codebase.\n\n**Common Mistakes:** Forgetting that `static: true` prerenders the page at build time – dynamic data (e.g., user session) will be stale. Using `static: true` for routes that need real-time data. Overlapping route patterns (order matters: first match wins).\n\n**Edge Cases:** When using `static: true` with `ssr: true` mix – a route marked `static: true` will not re-run SSR even if query parameters change; it serves the pre-built version. For parameterized static routes (e.g., `\u002Fblog\u002F[id]`), you must provide all possible IDs via `nitro.prerender.routes` or `crawlLinks`.\n\n**Interview Follow-ups:** \"How does hybrid rendering affect build time?\" \"Can you use different caching headers per route?\"\n\n**Best Practices:** Use route rules to optimize cost and performance: SSG for marketing\u002Fcontent, SSR for personalized or SEO-critical dynamic pages, CSR for interactive dashboards. Combine with `swr` (stale-while-revalidate) for updated content.\n\n**Performance Considerations:** Hybrid rendering reduces server load by offloading static routes to CDN and CSR routes to client. Cold starts affect only SSR routes.\n\n**SEO Considerations:** Ensure critical SEO pages use SSR or SSG; CSR pages (like `\u002Fadmin`) can be disallowed in `robots.txt`.\n\n**Production Recommendations:** Deploy to a platform that supports Nitro (Vercel, Netlify, Cloudflare). Use `routeRules` with `swr: 60` to cache SSR pages for 60 seconds. Monitor which rules are hit using analytics.\n\n**Latest Nuxt Patterns:** Nuxt 3 introduces `island` components (experimental) for partial hydration, but hybrid rendering at route level is stable and recommended.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F typed routeRules\nexport default defineNuxtConfig({\n  routeRules: {\n    '\u002Fapi\u002Fhello': { cors: true, headers: { 'X-API-Key': 'abc' } }\n  } satisfies NitroRouteRules\n})\n```\n\n**Interview Tip:** Emphasize that hybrid rendering is a key differentiator from Next.js – Nuxt allows mixing modes without additional configuration or per-page functions.\n\n**Common Follow-up:** \"What happens if a route matches multiple rules?\"\n\n**Real-world Example:** An e-commerce site: `\u002F` (SSR – dynamic promotions), `\u002Fcategory\u002F**` (SSG – product listings regenerated daily), `\u002Fcart` (CSR – real-time user cart), `\u002Fcheckout` (SSR – security and SEO for payment confirmation). This combination reduced server costs by 70% compared to full SSR.",[93,61,94,27,70,81],"hybrid","route-rules","Emphasize that hybrid rendering is a key differentiator from Next.js – Nuxt allows mixing modes without additional configuration or per-page functions.","What happens if a route matches multiple rules?","An e-commerce site: `\u002F` (SSR – dynamic promotions), `\u002Fcategory\u002F**` (SSG – product listings regenerated daily), `\u002Fcart` (CSR – real-time user cart), `\u002Fcheckout` (SSR – security and SEO for payment confirmation). This combination reduced server costs by 70% compared to full SSR.",{"id":99,"category":100,"question":101,"answer":102,"level":10,"tags":103,"interviewTip":108,"commonFollowUp":109,"realWorldExample":110},9,"Routing","How does the pages folder work in Nuxt?","**Concept Explanation:** The `pages\u002F` directory is the heart of Nuxt's file-based routing. Each `.vue` file in this folder automatically becomes a route in your application. The file structure determines the URL path. This eliminates manual route configuration using Vue Router.\n\n**Internal Working:** During `nuxt dev` or build, Nuxt scans the `pages\u002F` directory, generates a Vue Router configuration based on the file tree, and injects it into the `.nuxt\u002Frouter.ts` virtual file. It also generates code-split chunks for each page automatically. Nuxt uses `unjs\u002Fglobby` to match files and `unjs\u002Fknitwork` to generate the router code.\n\n**Request Flow:** 1) User navigates to `\u002Fabout` → 2) Vue Router matches the route to `pages\u002Fabout.vue` → 3) Nuxt loads the component (code-split chunk) → 4) Renders (SSR or client).\n\n**Lifecycle:** File is added\u002Fremoved\u002Frenamed → Nuxt restarts dev server (or hot updates in Nuxt 3) → Router regenerates.\n\n**Syntax & Code Example:**\n```\npages\u002F\n  index.vue          -> \u002F\n  about.vue          -> \u002Fabout\n  blog\u002F\n    index.vue        -> \u002Fblog\n    [id].vue         -> \u002Fblog\u002F:id\n```\nInside `pages\u002Findex.vue`:\n```vue\n\u003Ctemplate>\n  \u003Ch1>Home\u003C\u002Fh1>\n\u003C\u002Ftemplate>\n```\nNo additional router code needed.\n\n**Practical Example:** A marketing site with pages: Home, Services, Contact, and a Blog with dynamic posts. Create `pages\u002Findex.vue`, `pages\u002Fservices.vue`, `pages\u002Fcontact.vue`, `pages\u002Fblog\u002Findex.vue`, and `pages\u002Fblog\u002F[slug].vue`. Nuxt automatically generates all routes.\n\n**Common Mistakes:** Placing non-page components in `pages\u002F` (use `components\u002F` instead); using uppercase letters in file names (routing is case-sensitive depending on filesystem); forgetting that `index.vue` is required for a route to be accessible at a directory path.\n\n**Edge Cases:** Using special characters in filenames (Nuxt will URL-encode); pages can also be `.js` or `.ts` files (not just `.vue`) returning a Vue component definition.\n\n**Interview Follow-ups:** \"How do you create a catch-all route?\" \"Can you define custom route names?\"\n\n**Best Practices:** Keep pages thin – move logic to composables. Use `definePageMeta` to set layout, middleware, or page-specific configuration. Group related pages in folders.\n\n**Performance Considerations:** Nuxt automatically splits code by page, so each route loads only its own JavaScript. This reduces initial bundle size.\n\n**SEO Considerations:** The page filename and folder structure become the URL, which should be descriptive (e.g., `\u002Fproducts\u002Fblue-widget`). Use `definePageMeta` to set custom `routeName` if needed for redirects.\n\n**Production Recommendations:** Avoid deeply nested folder structures (max 3-4 levels) for maintainability. Use `_` prefix for ignored files (e.g., `_components` – though better to use `components\u002F`).\n\n**Latest Nuxt Patterns:** Nuxt 3 supports `pages\u002F` with TypeScript, and you can also use `~\u002Fpages\u002F[...slug].vue` for catch-all routes.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F pages\u002Fblog\u002F[id].vue – typed route params\nconst route = useRoute()\nconst { id } = route.params \u002F\u002F string | string[] – need to cast\nconst idString = Array.isArray(id) ? id[0] : id\n```\n\n**Interview Tip:** Emphasize that this file-based routing is the number one productivity booster in Nuxt – it eliminates hundreds of lines of router config and prevents route mismatch bugs.\n\n**Common Follow-up:** \"How do you handle nested routes?\"\n\n**Real-world Example:** A large e-commerce platform with 500+ pages. Using Nuxt's `pages\u002F` folder, the team added new routes by simply creating files, with zero router configuration. This reduced development time by 40% compared to their previous Vue Router setup.",[104,105,106,107],"pages","routing","file-based","vue-router","Emphasize that this file-based routing is the number one productivity booster in Nuxt – it eliminates hundreds of lines of router config and prevents route mismatch bugs.","How do you handle nested routes?","A large e-commerce platform with 500+ pages. Using Nuxt's `pages\u002F` folder, the team added new routes by simply creating files, with zero router configuration. This reduced development time by 40% compared to their previous Vue Router setup.",{"id":112,"category":100,"question":113,"answer":114,"level":10,"tags":115,"interviewTip":118,"commonFollowUp":119,"realWorldExample":120},10,"Explain file-based routing in Nuxt with dynamic routes.","**Concept Explanation:** File-based routing means the file system structure defines the URL paths. Dynamic routes are created using square brackets `[param]` in the filename or folder name. This captures variable segments of the URL, like `\u002Fusers\u002F123` where `123` is the user ID.\n\n**Internal Working:** Nuxt scans `pages\u002F` and converts `[param].vue` into a Vue Router dynamic segment `:param`. For a file like `pages\u002Fusers\u002F[id].vue`, Nuxt generates the route `path: '\u002Fusers\u002F:id'`. Multiple dynamic segments are allowed, e.g., `pages\u002F[category]\u002F[product].vue`.\n\n**Request Flow:** 1) User visits `\u002Fusers\u002F42` → 2) Vue Router matches `pages\u002Fusers\u002F[id].vue` → 3) The component receives `params.id = '42'` via `useRoute().params.id` → 4) Page fetches data for user 42.\n\n**Lifecycle:** Dynamic parameter changes (e.g., navigating from `\u002Fusers\u002F1` to `\u002Fusers\u002F2`) will reuse the same component instance, triggering Vue Router's navigation guards and re-running `useAsyncData` based on the new parameter.\n\n**Syntax & Code Example:**\n```\npages\u002F\n  users\u002F\n    [id].vue          -> \u002Fusers\u002F:id\n  [group]\u002F[page].vue  -> \u002F:group\u002F:page\n```\nInside `[id].vue`:\n```vue\n\u003Cscript setup>\nconst route = useRoute()\nconst { data: user } = await useFetch(`\u002Fapi\u002Fusers\u002F${route.params.id}`)\n\u003C\u002Fscript>\n\u003Ctemplate>\n  \u003Ch1>User {{ route.params.id }}\u003C\u002Fh1>\n\u003C\u002Ftemplate>\n```\n\n**Practical Example:** A blog with post slugs: `pages\u002Fblog\u002F[slug].vue`. Visiting `\u002Fblog\u002Fhello-world` captures `slug = 'hello-world'`. Use that to fetch the post content from a CMS.\n\n**Common Mistakes:** Forgetting that `route.params.id` can be an array for catch-all routes (`[...slug].vue`); not handling the case where param is missing; using `params.id` directly in `useFetch` without reactivity (solution: use `computed` or watch).\n\n**Edge Cases:** Nested dynamic routes: `pages\u002F[category]\u002F[id].vue` vs `pages\u002F[id].vue` – order of route matching depends on file system order; use `definePageMeta` with `path` if needed. Also, param validation using `definePageMeta({ validate })`.\n\n**Interview Follow-ups:** \"How do you create a catch-all (404) route?\" \"How do you handle optional parameters?\"\n\n**Best Practices:** Always validate dynamic parameters using `definePageMeta`'s `validate` function. Use `watch` or `computed` with `useRoute` to react to param changes in the same component. Prefer `useAsyncData` with `watch: [route.params.id]`.\n\n**Performance Considerations:** Dynamic routes prevent effective pre-rendering unless you provide all possible param values in `nitro.prerender.routes`. Use `crawlLinks` to automatically discover links.\n\n**SEO Considerations:** Dynamic URLs are fine for SEO, but avoid using IDs only; prefer meaningful slugs (e.g., `\u002Fblog\u002Fwhy-nuxt` instead of `\u002Fblog\u002F123`). Use `useHead` to set canonical URLs.\n\n**Production Recommendations:** For large dynamic sets (e.g., 100k products), consider hybrid: client-side fetch + SSG for top pages, or use ISR\u002Fcaching.\n\n**Latest Nuxt Patterns:** Nuxt 3 supports `[param].vue` and `[...param].vue` (catch-all). Also, you can use `definePageMeta` to set `key` to force component remount on param change.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F typed route params using generic\ndefinePageMeta({\n  validate: (route) => {\n    return \u002F^[a-z0-9]+$\u002F.test(route.params.id as string)\n  }\n})\n\nconst route = useRoute()\nconst id = route.params.id as string \u002F\u002F safe after validation\n```\n\n**Interview Tip:** Emphasize that dynamic routes in Nuxt are more than just URL parameters – they enable powerful patterns like shared layouts and nested routes with the same param scope.\n\n**Common Follow-up:** \"How do you access query parameters?\" (Use `useRoute().query`)\n\n**Real-world Example:** An online store: `pages\u002Fproducts\u002F[category]\u002F[productSlug].vue`. The product page uses `category` and `productSlug` params to fetch from API. This URL structure improves SEO and user understanding of product hierarchy.",[116,117,105],"dynamic-routes","params","Emphasize that dynamic routes in Nuxt are more than just URL parameters – they enable powerful patterns like shared layouts and nested routes with the same param scope.","How do you access query parameters?","An online store: `pages\u002Fproducts\u002F[category]\u002F[productSlug].vue`. The product page uses `category` and `productSlug` params to fetch from API. This URL structure improves SEO and user understanding of product hierarchy.",{"id":122,"category":100,"question":123,"answer":124,"level":10,"tags":125,"interviewTip":128,"commonFollowUp":129,"realWorldExample":130},11,"How do nested routes work in Nuxt using the pages folder?","**Concept Explanation:** Nested routes allow you to render a parent layout with a child component inside a `\u003CNuxtPage>` outlet. In Nuxt, nested routes are created by having a folder with the same name as a `.vue` file. For example, `pages\u002Fparent.vue` with a `pages\u002Fparent\u002Fchild.vue` creates a nested route `\u002Fparent\u002Fchild` where `parent.vue` acts as the layout wrapper.\n\n**Internal Working:** Nuxt scans the `pages\u002F` structure. If it finds both `pages\u002Fparent.vue` and a `pages\u002Fparent\u002F` directory, it treats `parent.vue` as the parent component. The generated Vue Router configuration creates a `children` array. The parent component must include `\u003CNuxtPage \u002F>` to render the child route.\n\n**Request Flow:** 1) Navigate to `\u002Fparent\u002Fchild` → 2) Vue Router matches `parent.vue` as parent and `parent\u002Fchild.vue` as child → 3) Parent component renders, its `\u003CNuxtPage \u002F>` slot is replaced by child's content.\n\n**Lifecycle:** Parent component is created once and kept alive when navigating between children (unless `key` changes). Child components are mounted\u002Funmounted as navigation occurs.\n\n**Syntax & Code Example:**\n```\npages\u002F\n  parent.vue          # parent component\n  parent\u002F\n    child.vue         # \u002Fparent\u002Fchild\n    sibling.vue       # \u002Fparent\u002Fsibling\n```\n`pages\u002Fparent.vue`:\n```vue\n\u003Ctemplate>\n  \u003Cdiv>\n    \u003Ch1>Parent Header\u003C\u002Fh1>\n    \u003CNuxtPage \u002F>  \u003C!-- child components render here -->\n    \u003Cfooter>Parent Footer\u003C\u002Ffooter>\n  \u003C\u002Fdiv>\n\u003C\u002Ftemplate>\n```\n`pages\u002Fparent\u002Fchild.vue`:\n```vue\n\u003Ctemplate>\n  \u003Cdiv>This is the child page\u003C\u002Fdiv>\n\u003C\u002Ftemplate>\n```\n\n**Practical Example:** A settings area: `\u002Fsettings\u002Fprofile`, `\u002Fsettings\u002Fsecurity`, `\u002Fsettings\u002Fbilling`. Create `pages\u002Fsettings.vue` with tabs and `\u003CNuxtPage \u002F>`. Then `pages\u002Fsettings\u002Fprofile.vue`, `pages\u002Fsettings\u002Fsecurity.vue`, etc. The settings layout (tabs) stays constant while the content changes.\n\n**Common Mistakes:** Forgetting to include `\u003CNuxtPage \u002F>` in the parent component – child routes will not render. Using `NuxtPage` without a surrounding layout in non-nested routes is unnecessary but works.\n\n**Edge Cases:** Deep nesting (e.g., `pages\u002Fparent\u002Fchild\u002Fgrandchild.vue`) requires intermediate components at each level that have `\u003CNuxtPage \u002F>`. Also, you can mix dynamic routes with nested routes: `pages\u002F[category]\u002F[subcategory].vue` and a folder `pages\u002F[category]\u002F[subcategory]\u002F[product].vue` creates three-level nesting.\n\n**Interview Follow-ups:** \"How do nested routes affect data fetching?\" \"Can you have multiple named outlets?\"\n\n**Best Practices:** Use nested routes for shared UI that changes based on child route (tabs, sidebar navigation). Keep the parent component lightweight – it re-renders when child changes if reactive data exists, but not the whole page.\n\n**Performance Considerations:** Parent components are not recreated on child navigation, which can improve performance if parent has expensive data fetching. However, stale data in parent may need manual refresh.\n\n**SEO Considerations:** Nested routes produce separate URLs, all indexable. The parent's content is part of the page HTML, good for SEO when parent has relevant keywords.\n\n**Production Recommendations:** Avoid overly deep nesting (more than 3 levels) as it becomes hard to maintain. Use layouts for global structure and nested routes for page-specific subsections.\n\n**Latest Nuxt Patterns:** Nuxt 3 also supports nested routes via `definePageMeta` with `alias` and `path`, but file-based is preferred. `\u003CNuxtPage>` can accept a `name` prop for named views.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F pages\u002Fparent.vue – define page meta for parent\n definePageMeta({\n  layout: 'custom' \u002F\u002F overrides default layout for parent and its children\n})\n```\n\n**Interview Tip:** Emphasize that nested routes in Nuxt are visually similar to layouts but different – layouts wrap entire pages, nested routes share a parent component that can have its own logic and state.\n\n**Common Follow-up:** \"What's the difference between nested routes and layouts?\"\n\n**Real-world Example:** A project management app: `\u002Fproject\u002F1\u002Ftasks`, `\u002Fproject\u002F1\u002Fteam`, `\u002Fproject\u002F1\u002Ffiles`. Using nested route `pages\u002Fproject\u002F[id].vue` with `\u003CNuxtPage \u002F>` and `pages\u002Fproject\u002F[id]\u002Ftasks.vue` etc. This keeps the project header and sidebar visible while navigating between tabs.",[126,104,105,127],"nested-routes","nuxtpage","Emphasize that nested routes in Nuxt are visually similar to layouts but different – layouts wrap entire pages, nested routes share a parent component that can have its own logic and state.","What's the difference between nested routes and layouts?","A project management app: `\u002Fproject\u002F1\u002Ftasks`, `\u002Fproject\u002F1\u002Fteam`, `\u002Fproject\u002F1\u002Ffiles`. Using nested route `pages\u002Fproject\u002F[id].vue` with `\u003CNuxtPage \u002F>` and `pages\u002Fproject\u002F[id]\u002Ftasks.vue` etc. This keeps the project header and sidebar visible while navigating between tabs.",{"id":132,"category":133,"question":134,"answer":135,"level":10,"tags":136,"interviewTip":141,"commonFollowUp":142,"realWorldExample":143},12,"Layouts","What are layouts in Nuxt and how do you use them?","**Concept Explanation:** Layouts are wrapper components that wrap pages, providing a consistent UI structure like headers, footers, and sidebars. Nuxt uses the `layouts\u002F` directory. The default layout is `layouts\u002Fdefault.vue`. Pages can specify a different layout using `definePageMeta`.\n\n**Internal Working:** During rendering, Nuxt wraps the page component inside a layout component. The layout receives the page content via the `\u003Cslot \u002F>` (or `\u003CNuxtLayout>` component). Nuxt automatically uses `default.vue` unless overridden. The layout is part of the Vue component tree and can have its own state, data fetching, and lifecycle.\n\n**Request Flow:** 1) User requests a page → 2) Nuxt determines which layout (from page's `definePageMeta` or default) → 3) Layout component is instantiated → 4) Layout's `\u003Cslot \u002F>` is replaced by the page component's rendered output → 5) Both are rendered together (SSR) or on client.\n\n**Lifecycle:** Layouts are recreated when switching between pages that use different layouts. For the same layout, the layout component may be reused if navigation is client-side (depends on Vue Router's behavior).\n\n**Syntax & Code Example:**\n`layouts\u002Fdefault.vue`:\n```vue\n\u003Ctemplate>\n  \u003Cdiv>\n    \u003CAppHeader \u002F>\n    \u003Cslot \u002F> \u003C!-- page content goes here -->\n    \u003CAppFooter \u002F>\n  \u003C\u002Fdiv>\n\u003C\u002Ftemplate>\n```\n`layouts\u002Fempty.vue`:\n```vue\n\u003Ctemplate>\n  \u003Cslot \u002F> \u003C!-- no header\u002Ffooter -->\n\u003C\u002Ftemplate>\n```\n`pages\u002Flogin.vue` using empty layout:\n```vue\n\u003Cscript setup>\ndefinePageMeta({\n  layout: 'empty'\n})\n\u003C\u002Fscript>\n```\n\n**Practical Example:** A marketing site: default layout includes header, navigation, footer. Login page uses 'empty' layout to hide navigation. Admin dashboard uses 'dashboard' layout with sidebar.\n\n**Common Mistakes:** Forgetting to include `\u003Cslot \u002F>` in layout – page content won't appear. Using `NuxtLayout` component manually in pages (rarely needed, Nuxt auto-wraps). Not setting `layout` in `definePageMeta` correctly (string must match filename without extension).\n\n**Edge Cases:** Nested layouts: a layout can contain another layout via `NuxtLayout` – but generally not recommended. Using layouts with nested routes: the layout wraps the parent component, which then contains `\u003CNuxtPage \u002F>` for children.\n\n**Interview Follow-ups:** \"Can layouts have their own data fetching?\" \"How to change layout dynamically at runtime?\"\n\n**Best Practices:** Keep layouts dumb (just structure) and use composables for layout-specific logic. Use `definePageMeta` to set layout per page. For dynamic layout switching, use `setPageLayout` helper.\n\n**Performance Considerations:** Layouts are included in server rendering, so they add to HTML size. Keep them lean. Avoid heavy data fetching in layouts unless shared across many pages (then it's beneficial).\n\n**SEO Considerations:** Layout content (header\u002Ffooter) is part of every page's HTML, which is fine for SEO. Use `useHead` in layout to set site-wide meta tags (but page meta overrides).\n\n**Production Recommendations:** Use `error.vue` layout for custom error pages (place in `layouts\u002F` or `pages\u002F`). Prefer multiple layouts for different sections (public, authenticated, admin).\n\n**Latest Nuxt Patterns:** Nuxt 3 allows layout overriding via `setPageLayout` inside `definePageMeta` or programmatically. Also, `layouts\u002F` can use `.js` or `.ts` files exporting a component.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F layouts\u002Fdefault.vue with typed props\n\u003Cscript setup lang=\"ts\">\n\u002F\u002F Layout can accept props via slots, not typically needed\n\u003C\u002Fscript>\n```\n\n**Interview Tip:** Clarify that layouts are not the same as nested routes – layouts wrap whole pages, nested routes are components inside a parent page component.\n\n**Common Follow-up:** \"How do you create a layout with dynamic sidebar based on user role?\"\n\n**Real-world Example:** A SaaS application has three layouts: `default` (public marketing pages), `app` (logged-in dashboard with sidebar), and `minimal` (payment pages). Each layout is defined in `layouts\u002F` and pages specify which to use via `definePageMeta`. This keeps UI consistent and code DRY.",[137,138,139,140],"layouts","ui","wrapper","default-layout","Clarify that layouts are not the same as nested routes – layouts wrap whole pages, nested routes are components inside a parent page component.","How do you create a layout with dynamic sidebar based on user role?","A SaaS application has three layouts: `default` (public marketing pages), `app` (logged-in dashboard with sidebar), and `minimal` (payment pages). Each layout is defined in `layouts\u002F` and pages specify which to use via `definePageMeta`. This keeps UI consistent and code DRY.",{"id":145,"category":146,"question":147,"answer":148,"level":10,"tags":149,"interviewTip":153,"commonFollowUp":154,"realWorldExample":155},13,"App Entry","What is app.vue and when should you use it instead of layouts?","**Concept Explanation:** `app.vue` is the main entry component of a Nuxt application. It replaces the default Nuxt wrapper and gives you full control over the root component. If `app.vue` exists, Nuxt will not use the `layouts\u002F` system automatically – you must manually include `\u003CNuxtLayout>` if you still want layouts. It's the outermost component in the Vue tree.\n\n**Internal Working:** By default, Nuxt has an internal `App` component that includes `\u003CNuxtLayout>` and `\u003CNuxtPage>`. When you create `app.vue`, Nuxt uses your component instead. This allows you to add global providers (like Pinia store, i18n, custom error handling) or alter the root template.\n\n**Request Flow:** 1) Nuxt creates Vue app instance → 2) Mounts your `app.vue` as the root component → 3) Everything else renders inside `app.vue`'s template.\n\n**Lifecycle:** `app.vue` is created once per application (SPA) or per request (SSR). It's the first component to mount.\n\n**Syntax & Code Example (app.vue):**\n```vue\n\u003Ctemplate>\n  \u003Cdiv>\n    \u003CGlobalNotification \u002F>\n    \u003CNuxtLayout>\n      \u003CNuxtPage \u002F>\n    \u003C\u002FNuxtLayout>\n  \u003C\u002Fdiv>\n\u003C\u002Ftemplate>\n```\nIf you omit `\u003CNuxtLayout>`, layouts won't work. To completely bypass layout system, just put `\u003CNuxtPage \u002F>` directly.\n\n**Practical Example:** Adding a global toast notification component that should be outside of layouts and pages. Or wrapping the app with a theme provider, or adding a global script loader.\n\n**Common Mistakes:** Forgetting to include `\u003CNuxtPage \u002F>` – nothing renders. Including `\u003CNuxtLayout>` but not having a `layouts\u002F` folder – will cause error. Overusing `app.vue` for things that belong in layouts (like header\u002Ffooter).\n\n**Edge Cases:** When `app.vue` is present, layouts are optional. You can also have `app.vue` without `\u003CNuxtLayout>` and manually handle layout switching using `useRoute` and dynamic components, but that's not recommended.\n\n**Interview Follow-ups:** \"What's the difference between app.vue, layouts, and pages?\" \"Can you have both app.vue and layouts?\"\n\n**Best Practices:** Use `app.vue` only for truly global concerns (providers, root-level scripts, error boundaries). For most apps, omit `app.vue` and rely on layouts and the default Nuxt behavior.\n\n**Performance Considerations:** `app.vue` is part of the server render and client bundle. Keep it minimal; avoid heavy components here because they will be present on every page.\n\n**SEO Considerations:** Content in `app.vue` appears on every page, which is fine for global elements like cookies consent but not for page-specific content.\n\n**Production Recommendations:** Only create `app.vue` when necessary (e.g., adding a Sentry error handler, or a WebSocket connection). Use `plugins\u002F` for most global script injections instead.\n\n**Latest Nuxt Patterns:** Nuxt 3's `app.vue` can use `\u003CNuxtLoadingIndicator \u002F>`, `\u003CNuxtErrorBoundary \u002F>`, and other Nuxt components. It also supports `definePageMeta`? No, page meta only works in pages.\n\n**TypeScript Example:**\n```vue\n\u003C!-- app.vue with typed slots -->\n\u003Cscript setup lang=\"ts\">\n\u002F\u002F You can add app-level logic here\nuseHead({ titleTemplate: '%s - My App' })\n\u003C\u002Fscript>\n```\n\n**Interview Tip:** Emphasize that `app.vue` is optional; most Nuxt beginners should not touch it. It's an escape hatch for advanced root-level control.\n\n**Common Follow-up:** \"How do you add global CSS or fonts without app.vue?\" (Use `css` option in nuxt.config.ts)\n\n**Real-world Example:** A multilingual app using `vue-i18n` needed to provide the i18n instance to the entire app. They created `app.vue` and wrapped the `NuxtLayout` with the i18n provider component, ensuring all pages had translation capabilities.",[150,151,152],"app.vue","entry","root-component","Emphasize that `app.vue` is optional; most Nuxt beginners should not touch it. It's an escape hatch for advanced root-level control.","How do you add global CSS or fonts without app.vue?","A multilingual app using `vue-i18n` needed to provide the i18n instance to the entire app. They created `app.vue` and wrapped the `NuxtLayout` with the i18n provider component, ensuring all pages had translation capabilities.",{"id":157,"category":158,"question":159,"answer":160,"level":10,"tags":161,"interviewTip":165,"commonFollowUp":166,"realWorldExample":167},14,"Components","How does the components folder work with auto-imports in Nuxt?","**Concept Explanation:** The `components\u002F` folder is where you put reusable Vue components. Nuxt automatically imports any component used in your templates – you never need to write an `import` statement. This works for components in subdirectories as well, using a prefix or the full path as the component name.\n\n**Internal Working:** At build time, Nuxt scans the `components\u002F` directory and generates a mapping in `.nuxt\u002Fcomponents.d.ts`. It also creates a virtual module that re-exports all components. During Vue template compilation, Nuxt's custom transform adds imports for any component tag that matches the mapping. This happens at compile time, not runtime, so there's no performance overhead.\n\n**Request Flow:** 1) You write `\u003CMyButton \u002F>` in a template → 2) Nuxt's Vite\u002FWebpack plugin transforms the template → 3) Adds `import MyButton from '~\u002Fcomponents\u002FMyButton.vue'` → 4) Vue compiler processes it as usual.\n\n**Lifecycle:** When you add\u002Fremove\u002Frename a component, Nuxt regenerates the auto-imports during dev (hot reload).\n\n**Syntax & Code Example:**\n```\ncomponents\u002F\n  Button.vue              -> \u003CButton \u002F>\n  forms\u002F\n    Input.vue             -> \u003CFormsInput \u002F> or \u003CFormsInput \u002F> (prefixed)\n    SubmitButton.vue      -> \u003CFormsSubmitButton \u002F>\n  layout\u002F\n    Header.vue            -> \u003CLayoutHeader \u002F>\n```\nUsage in any page\u002Flayout:\n```vue\n\u003Ctemplate>\n  \u003CButton \u002F>\n  \u003CFormsInput \u002F>\n  \u003CLayoutHeader \u002F>\n\u003C\u002Ftemplate>\n```\nNo imports needed.\n\n**Practical Example:** A design system with 50+ components. With auto-imports, developers just use `\u003CCard \u002F>`, `\u003CModal \u002F>`, etc., without manually importing them in every file. This reduces boilerplate and makes refactoring easier.\n\n**Common Mistakes:** Component name conflicts (two components with same name in different folders) – Nuxt will throw an error. Using reserved HTML tag names (e.g., `Select.vue` can conflict, but Nuxt handles). Forgetting that subdirectory components get a prefix (by default the directory name).\n\n**Edge Cases:** Dynamic components (``\u003Ccomponent :is=\"componentName\" \u002F>``) – auto-imports do NOT work for strings unless you explicitly import or use `resolveComponent`. Also, components used in `v-for` or complex expressions may need explicit import.\n\n**Interview Follow-ups:** \"Can you disable auto-imports for performance?\" \"How do you control the naming convention for nested components?\"\n\n**Best Practices:** Keep components focused and co-located with their usage when possible. Use `components\u002F` for shared components. For page-specific components, place them in `pages\u002F` directory alongside the page (not auto-imported by default, but you can configure).\n\n**Performance Considerations:** Auto-imports have no runtime cost; they are resolved at build time. However, many components can increase build time slightly. Nuxt only includes components that are actually used (tree-shaking).\n\n**SEO Considerations:** Not relevant.\n\n**Production Recommendations:** Use `components: { dirs: [...] }` to add additional folders. Set `global: true` for components that should be available everywhere without directory prefix. Use `~\u002Fcomponents\u002Fglobal\u002F` with `global: true` for truly universal components.\n\n**Latest Nuxt Patterns:** Nuxt 3 supports `components\u002F` with `.vue`, `.jsx`, `.tsx`. Also can use `components: { extensions: ['.vue'] }`.\n\n**TypeScript Example:** Nuxt generates `components.d.ts` automatically, so typed components work out of the box.\n\n**Interview Tip:** Emphasize that auto-imports are one of Nuxt's biggest developer experience wins, but they can be confusing when debugging 'component not found' – explain that you can still manually import if needed.\n\n**Common Follow-up:** \"How do you auto-import components from a third-party library?\"\n\n**Real-world Example:** A large e-commerce app with 200+ components, including product cards, modals, forms. Auto-imports saved the team from writing thousands of import statements and reduced merge conflicts. They configured `components\u002F` subdirectories like `product\u002F`, `checkout\u002F`, `ui\u002F` for logical grouping.",[162,163,164],"components","auto-imports","reusability","Emphasize that auto-imports are one of Nuxt's biggest developer experience wins, but they can be confusing when debugging 'component not found' – explain that you can still manually import if needed.","How do you auto-import components from a third-party library?","A large e-commerce app with 200+ components, including product cards, modals, forms. Auto-imports saved the team from writing thousands of import statements and reduced merge conflicts. They configured `components\u002F` subdirectories like `product\u002F`, `checkout\u002F`, `ui\u002F` for logical grouping.",{"id":169,"category":170,"question":171,"answer":172,"level":10,"tags":173,"interviewTip":177,"commonFollowUp":178,"realWorldExample":179},15,"Composables","What are composables in Nuxt and how do they differ from Vue composables?","**Concept Explanation:** Composables in Nuxt are auto-imported functions that encapsulate reactive state and logic, following the Vue Composition API pattern. Nuxt extends this concept by providing built-in composables (`useFetch`, `useState`, `useRoute`, etc.) and allowing you to create your own in the `composables\u002F` folder. They differ from plain Vue composables because Nuxt provides SSR-aware wrappers and lifecycle integration.\n\n**Internal Working:** Nuxt scans the `composables\u002F` directory and generates auto-imports for any exported function. At build time, it adds imports to `.nuxt\u002Fimports.d.ts`. During SSR, Nuxt ensures that composables like `useState` are isolated per request (to avoid cross-request state leaks). Nuxt also transforms composable calls to handle server\u002Fclient context.\n\n**Request Flow:** 1) Page component calls `useMyData()` composable → 2) Nuxt's auto-import injects the function → 3) If composable uses `useAsyncData`, Nuxt tracks promises during SSR and waits for resolution before sending HTML.\n\n**Lifecycle:** Composables can run on server, client, or both. Nuxt's built-in composables automatically adapt (e.g., `useCookie` works on both sides, `useRequestHeaders` only on server).\n\n**Syntax & Code Example (custom composable):**\n`composables\u002FuseCounter.ts`:\n```ts\nexport const useCounter = () => {\n  const count = useState('counter', () => 0)\n  const increment = () => count.value++\n  return { count, increment }\n}\n```\nUsage in any component without import:\n```vue\n\u003Cscript setup>\nconst { count, increment } = useCounter()\n\u003C\u002Fscript>\n```\n\n**Practical Example:** A `useUserSession` composable that fetches user data, checks authentication, and provides login\u002Flogout methods. It can be used across pages and layouts, reusing logic and state.\n\n**Common Mistakes:** Creating a composable that uses browser-only APIs (like `localStorage`) without checking `process.client` – will break SSR. Not understanding that state in composables is not shared across requests unless using `useState` or other Nuxt-specific primitives.\n\n**Edge Cases:** Composables can be nested; Nuxt handles auto-imports recursively. However, circular dependencies between composables can cause build errors. Also, composables called outside of Nuxt context (e.g., plain .ts file) will lack Nuxt's lifecycle and may fail.\n\n**Interview Follow-ups:** \"How do you share state across composables?\" \"Can you use composables in plugins?\"\n\n**Best Practices:** Name composables with `use` prefix. Keep them focused and testable. Use `useState` for shared reactive state across composables. Leverage built-in composables like `useFetch` inside your custom ones.\n\n**Performance Considerations:** Composables are just functions – they have minimal overhead. However, heavy reactive computations inside composables can impact render performance; use `computed` and `watch` judiciously.\n\n**SEO Considerations:** Not directly relevant, but composables that fetch data affect what content is rendered server-side, thus SEO.\n\n**Production Recommendations:** Organize composables by domain (e.g., `useUser.ts`, `useCart.ts`). For large apps, consider splitting into modules. Use TypeScript for better autocompletion.\n\n**Latest Nuxt Patterns:** Nuxt 3 supports composables returning `AsyncData` objects, and the auto-import system now includes `composables\u002F` subdirectories with prefix support similar to components.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F composables\u002FuseApi.ts with generics\nexport const useApi = \u003CT>(url: string) => {\n  return useFetch\u003CT>(url, { key: url })\n}\n```\n\n**Interview Tip:** Emphasize the key difference: Nuxt composables are SSR-aware and auto-imported, whereas Vue composables need manual imports and may not handle server-side rendering correctly.\n\n**Common Follow-up:** \"What's the difference between composables and utils?\" (Utils are plain functions without reactive state, not auto-imported by default but can be configured).\n\n**Real-world Example:** A booking platform has `useAvailabilitySearch`, `useBookingForm`, `usePayment` composables. Each encapsulates complex logic (API calls, form validation, state). The team can reuse these across different pages (search results, booking details, checkout) without duplicating code. Auto-imports mean they never worry about import paths.",[174,175,163,176],"composables","composition-api","state","Emphasize the key difference: Nuxt composables are SSR-aware and auto-imported, whereas Vue composables need manual imports and may not handle server-side rendering correctly.","What's the difference between composables and utils?","A booking platform has `useAvailabilitySearch`, `useBookingForm`, `usePayment` composables. Each encapsulates complex logic (API calls, form validation, state). The team can reuse these across different pages (search results, booking details, checkout) without duplicating code. Auto-imports mean they never worry about import paths.",{"id":181,"category":182,"question":183,"answer":184,"level":10,"tags":185,"interviewTip":188,"commonFollowUp":189,"realWorldExample":190},16,"State Management","What is useState in Nuxt and how does it work for shared state?","**Concept Explanation:** `useState` is an SSR-friendly shared state composable. It creates a reactive reference that is preserved across server and client without causing hydration mismatches. Unlike Vue's `ref`, state created with `useState` is global (by key) and survives the SSR payload transfer. It's ideal for shared state that doesn't need persistence (use `useCookie` for that).\n\n**Internal Working:** On the server, `useState(key, init)` checks if state for that key already exists in the current request context. If not, it creates a `ref` with the initial value and stores it in the request-scoped context (to avoid cross-request leaks). When the server finishes rendering, the state's value is serialized into `window.__NUXT__.state` in the HTML. On the client, `useState` reads the deserialized value from the payload, ensuring the client starts with the same state as the server. Subsequent changes are purely client-side.\n\n**Request Flow (SSR):** 1) Server renders page → calls `useState('user', () => fetchUser())` → stores in request context → HTML sent with embedded state → Client hydrates → `useState` returns the same value without re-fetching.\n\n**Lifecycle:** State is created per request on server; on client, it's created once and persists across client-side navigations (unless page reloads).\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F composables\u002FuseTheme.ts\nexport const useTheme = () => {\n  return useState('theme', () => 'light')\n}\n```\nIn component:\n```vue\n\u003Cscript setup>\nconst theme = useTheme()\nconst toggleTheme = () => theme.value = theme.value === 'light' ? 'dark' : 'light'\n\u003C\u002Fscript>\n```\n\n**Practical Example:** Shopping cart state: `useState('cart', () => [])` that can be accessed from header (cart icon) and product pages. Adding an item updates the cart in both places without prop drilling or complex stores.\n\n**Common Mistakes:** Using `useState` without a unique key – it will create a new state each call. Using it for non-serializable data (like functions, DOM elements) – will break SSR serialization. Not providing an initial value on server (can lead to undefined).\n\n**Edge Cases:** State can be mutated from anywhere, which may cause debugging issues. `useState` is not persistent across page reloads (unlike `useCookie`). On client-side navigation, the state persists unless you manually reset it.\n\n**Interview Follow-ups:** \"How does useState differ from Pinia?\" \"Can you use useState with localStorage?\"\n\n**Best Practices:** Use `useState` for simple app-wide state that doesn't need complex actions or persistence. For larger apps, use Pinia. Always provide a unique key string. Initialize state lazily via a function to avoid recomputation.\n\n**Performance Considerations:** `useState` creates a reactive ref with minimal overhead. However, overusing it (hundreds of keys) can impact serialization size. Keep state minimal; avoid storing large data that can be recomputed.\n\n**SEO Considerations:** The serialized state is embedded in HTML, increasing page size slightly. Use `useState` only for data needed for initial render.\n\n**Production Recommendations:** Combine with `useCookie` for persistence. For sensitive data, avoid storing in state; use server-only state. Clear state on logout.\n\n**Latest Nuxt Patterns:** Nuxt 3's `useState` works with `shallowRef` for performance. You can also use `useState` with `init` function that runs only once.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F typed useState\nconst cart = useState\u003C{ id: number; qty: number }[]>('cart', () => [])\n```\n\n**Interview Tip:** Emphasize that `useState` is the primary tool for shared state that needs to survive SSR hydration, unlike global `ref` which would reset on client. It's like React's `useState` but global.\n\n**Common Follow-up:** \"How does useState handle multiple requests on the server?\"\n\n**Real-world Example:** A multi-step form wizard. The form data is stored in `useState('formData')`. As the user moves between steps (different pages), the state persists. On final submission, the state is sent to the API. Without `useState`, you would need Vuex\u002FPinia or complex URL state.",[186,176,27,187],"usestate","shared-state","Emphasize that `useState` is the primary tool for shared state that needs to survive SSR hydration, unlike global `ref` which would reset on client. It's like React's `useState` but global.","How does useState handle multiple requests on the server?","A multi-step form wizard. The form data is stored in `useState('formData')`. As the user moves between steps (different pages), the state persists. On final submission, the state is sent to the API. Without `useState`, you would need Vuex\u002FPinia or complex URL state.",{"id":192,"category":193,"question":194,"answer":195,"level":10,"tags":196,"interviewTip":200,"commonFollowUp":201,"realWorldExample":202},17,"Data Fetching","What is useFetch in Nuxt and how does it differ from $fetch?","**Concept Explanation:** `useFetch` is a composable that wraps `$fetch` and adds SSR support, automatic caching, and reactive data handling. It's specifically designed for data fetching in Nuxt components, handling double-fetching prevention (fetching on server and client) and providing `pending`, `error`, `refresh`, and `status` states. `$fetch` is a lower-level utility (based on `ofetch`) that makes HTTP requests but does NOT provide SSR deduplication or reactive returns.\n\n**Internal Working:** When you call `useFetch` during SSR, Nuxt's server engine executes the fetch and stores the result in the request context. It also serializes the data into the HTML payload (under `window.__NUXT__`). On the client, `useFetch` first checks if data for the same key already exists in the payload; if so, it uses that instead of making a new request. This prevents the 'double data fetching' problem (server fetched, then client re-fetches). The function returns reactive `ref`s that update when `refresh()` is called.\n\n**Request Flow:** 1) Server renders page → `useFetch` runs → fetch API → data stored in payload → HTML sent. 2) Client hydrates → `useFetch` runs again but sees existing payload → returns cached data immediately → no second network request.\n\n**Lifecycle:** On initial load, runs on server then client (using cached data). On client-side navigation, runs only on client.\n\n**Syntax & Code Example:**\n```vue\n\u003Cscript setup>\n\u002F\u002F useFetch – reactive, SSR-aware\nconst { data, pending, error, refresh } = await useFetch('\u002Fapi\u002Fproducts')\n\n\u002F\u002F $fetch – raw, not reactive\nconst products = await $fetch('\u002Fapi\u002Fproducts') \u002F\u002F SSR runs, but no caching or reactivity\n\u003C\u002Fscript>\n```\n\n**Practical Example:** Fetching a list of blog posts on the homepage. `useFetch` automatically handles loading states and prevents re-fetching on client. If you used `$fetch` directly in `setup`, it would fetch on server AND client (double request).\n\n**Common Mistakes:** Using `$fetch` directly in `setup` without wrapping it in `useAsyncData` – leads to double fetching. Forgetting that `useFetch` is lazy by default in Nuxt 3? Actually, it awaits automatically in `setup` (top-level). Not providing a unique `key` can cause cache collisions.\n\n**Edge Cases:** `useFetch` does not work in client-only contexts (like `onMounted` with `server: false`? Actually it does, but without caching). For POST requests, use `$fetch` directly or `useFetch` with `method: 'POST'`. The `key` option is crucial for cache busting.\n\n**Interview Follow-ups:** \"How do you handle mutations (POST\u002FPUT) with useFetch?\" \"What is the difference between useFetch and useAsyncData?\"\n\n**Best Practices:** Always use `useFetch` for GET requests that need to be SSR-friendly. For mutations (POST\u002FPUT\u002FDELETE), use `$fetch` inside a method. Specify a unique `key` when the URL might be dynamic (e.g., `\u002Fapi\u002Fuser\u002F${id}`) to avoid cache issues.\n\n**Performance Considerations:** `useFetch` caches per key within the same request\u002Finitial load. Use `refresh` to manually revalidate. Set `server: false` to skip SSR fetch (useful for user-specific data).\n\n**SEO Considerations:** Data fetched with `useFetch` is included in the initial HTML if `server: true` (default), which improves SEO for content-heavy pages.\n\n**Production Recommendations:** Use `useFetch` with `immediate: false` if you need to trigger fetch later (e.g., after user action). Set `lazy: true` to avoid blocking navigation (but then handle pending state).\n\n**Latest Nuxt Patterns:** Nuxt 3's `useFetch` supports `watch` option to refetch when reactive sources change, and `transform` to modify response data.\n\n**TypeScript Example:**\n```ts\nconst { data } = useFetch\u003C{ id: number; title: string }[]>('\u002Fapi\u002Fposts')\n\u002F\u002F data.value is inferred as the type\n```\n\n**Interview Tip:** Emphasize the key difference: `useFetch` is for components and SSR with reactivity, `$fetch` is for utility functions, API endpoints (server side), and mutations. The double-fetching prevention is critical for performance.\n\n**Common Follow-up:** \"When would you use $fetch instead of useFetch?\"\n\n**Real-world Example:** A product page uses `useFetch` to load product details SSR. The same page has a \"Add to cart\" button that uses `$fetch` to POST to `\u002Fapi\u002Fcart` (mutation). This separation keeps the code clean and performant.",[197,198,27,199],"usefetch","data-fetching","fetch","Emphasize the key difference: `useFetch` is for components and SSR with reactivity, `$fetch` is for utility functions, API endpoints (server side), and mutations. The double-fetching prevention is critical for performance.","When would you use $fetch instead of useFetch?","A product page uses `useFetch` to load product details SSR. The same page has a \"Add to cart\" button that uses `$fetch` to POST to `\u002Fapi\u002Fcart` (mutation). This separation keeps the code clean and performant.",{"id":204,"category":193,"question":205,"answer":206,"level":10,"tags":207,"interviewTip":210,"commonFollowUp":211,"realWorldExample":212},18,"What is useAsyncData and when should you use it instead of useFetch?","**Concept Explanation:** `useAsyncData` is the lower-level composable for handling async operations during SSR. It provides the same SSR caching and hydration features as `useFetch` but gives you full control over the async function (which can be any promise, not just HTTP requests). `useFetch` is actually a wrapper around `useAsyncData` + `$fetch`. Use `useAsyncData` when you need to fetch from a custom source (GraphQL, localStorage, IndexedDB, or complex async logic) or when you need more control over the fetch key and transform.\n\n**Internal Working:** Similar to `useFetch`: during SSR, Nuxt executes the async function, waits for resolution, stores the result in the payload, and serializes it. On client, it retrieves from payload if available and then runs the function again only if needed. It tracks `pending`, `error`, and `status` states.\n\n**Request Flow:** Identical to `useFetch`, but the async function can be anything: `() => myCustomDataLoader()`, `() => $graphql(query)`, etc.\n\n**Lifecycle:** Same as `useFetch`.\n\n**Syntax & Code Example:**\n```vue\n\u003Cscript setup>\n\u002F\u002F useFetch is simpler for HTTP\nconst { data: products } = await useFetch('\u002Fapi\u002Fproducts')\n\n\u002F\u002F useAsyncData for custom async logic\nconst { data: processedData } = await useAsyncData('customKey', async () => {\n  const raw = await $fetch('\u002Fapi\u002Fraw')\n  return processData(raw) \u002F\u002F some expensive transform\n})\n\n\u002F\u002F GraphQL example\nconst { data: gqlData } = await useAsyncData('gql', () => $fetch('\u002Fgraphql', {\n  method: 'POST',\n  body: { query: '{ posts { title } }' }\n}))\n\u003C\u002Fscript>\n```\n\n**Practical Example:** A dashboard that fetches data from multiple APIs, then aggregates and transforms it. You cannot do that with `useFetch` alone; you would use `useAsyncData` with a custom async function that calls multiple `$fetch` and combines results.\n\n**Common Mistakes:** Not providing a unique key (or relying on auto-generated) for `useAsyncData` – can cause cache collisions. Using `useAsyncData` for simple GET requests when `useFetch` would be simpler. Forgetting to `await` in top-level `setup` (Nuxt allows `await`, but you must handle suspense).\n\n**Edge Cases:** `useAsyncData` can be used with `server: false` to run only on client. It also supports `lazy` mode where it doesn't block navigation. The `default` option provides initial value before async resolves.\n\n**Interview Follow-ups:** \"What's the performance difference between useFetch and useAsyncData?\" \"Can you nest useAsyncData calls?\"\n\n**Best Practices:** Use `useFetch` for 90% of cases (simple HTTP GET). Use `useAsyncData` when you need complex logic, multiple sources, or when the async operation is not an HTTP request. Always provide explicit `key` to avoid issues.\n\n**Performance Considerations:** `useAsyncData` has same caching benefits as `useFetch`. Use `transform` to reduce data size before storing in payload (important for SSR performance).\n\n**SEO Considerations:** Same as `useFetch` – data serialized in HTML.\n\n**Production Recommendations:** Use `pick` option to only include necessary fields from large responses, reducing payload size. Avoid heavy computations inside the async function during SSR; they will block rendering.\n\n**Latest Nuxt Patterns:** Nuxt 3's `useAsyncData` supports `watch` to refetch when reactive sources change, and `immediate` to control when fetch starts.\n\n**TypeScript Example:**\n```ts\nconst { data } = await useAsyncData\u003C{ id: number }>('user', () => $fetch('\u002Fapi\u002Fuser'), {\n  transform: (user) => ({ id: user.id }) \u002F\u002F typed transform\n})\n```\n\n**Interview Tip:** Explain that `useFetch` is a convenience wrapper; `useAsyncData` is more flexible. Interviewers may ask you to implement a custom `useGraphQL` composable using `useAsyncData`.\n\n**Common Follow-up:** \"How would you implement a debounced search using useAsyncData?\"\n\n**Real-world Example:** A reporting dashboard fetches sales data from three different microservices, merges them, calculates KPIs, and then returns. Using `useAsyncData` with an async function that calls `$fetch` three times, then aggregates, ensures the complex logic runs once on server and is cached for client.",[208,198,27,209],"useasyncdata","async","Explain that `useFetch` is a convenience wrapper; `useAsyncData` is more flexible. Interviewers may ask you to implement a custom `useGraphQL` composable using `useAsyncData`.","How would you implement a debounced search using useAsyncData?","A reporting dashboard fetches sales data from three different microservices, merges them, calculates KPIs, and then returns. Using `useAsyncData` with an async function that calls `$fetch` three times, then aggregates, ensures the complex logic runs once on server and is cached for client.",{"id":214,"category":215,"question":216,"answer":217,"level":10,"tags":218,"interviewTip":222,"commonFollowUp":223,"realWorldExample":224},19,"Navigation","How does NuxtLink work and how is it different from \u003Ca> and Vue Router's RouterLink?","**Concept Explanation:** `\u003CNuxtLink>` is Nuxt's wrapper around Vue Router's `\u003CRouterLink>`. It adds automatic prefetching, intelligent preloading, and external link handling. It's the recommended way to navigate between pages in a Nuxt app. Unlike plain `\u003Ca>` tags, it enables client-side navigation (no full page reload). Compared to `\u003CRouterLink>`, it adds performance optimizations out of the box.\n\n**Internal Working:** When a `\u003CNuxtLink>` enters the viewport (or is hovered), Nuxt automatically prefetches the page component's JavaScript and the data payload for that route (using Intersection Observer). This makes navigation feel instant. For external links (starting with `http` or `https`), `\u003CNuxtLink>` behaves like a normal `\u003Ca>` tag, preventing unnecessary prefetch. It also adds `rel=\"noopener noreferrer\"` for security when `target=\"_blank\"`.\n\n**Request Flow:** 1) User clicks `\u003CNuxtLink to=\"\u002Fabout\">` → 2) Nuxt cancels default browser navigation → 3) Calls Vue Router's `push` → 4) Client-side page transition (no full reload) → 5) New page component renders using already prefetched data if available.\n\n**Lifecycle:** Prefetching happens during idle time after initial page load, improving perceived performance.\n\n**Syntax & Code Example:**\n```vue\n\u003Ctemplate>\n  \u003C!-- Internal navigation -->\n  \u003CNuxtLink to=\"\u002Fabout\">About\u003C\u002FNuxtLink>\n  \n  \u003C!-- Dynamic route -->\n  \u003CNuxtLink :to=\"{ name: 'products-id', params: { id: 1 } }\">Product 1\u003C\u002FNuxtLink>\n  \n  \u003C!-- External link (no prefetch) -->\n  \u003CNuxtLink to=\"https:\u002F\u002Fnuxt.com\">Nuxt Website\u003C\u002FNuxtLink>\n  \n  \u003C!-- Disable prefetch -->\n  \u003CNuxtLink to=\"\u002Fcontact\" :prefetch=\"false\">Contact\u003C\u002FNuxtLink>\n\u003C\u002Ftemplate>\n```\n\n**Practical Example:** A blog with a list of 20 post links. Using `\u003CNuxtLink>` on each, when the user scrolls, Nuxt prefetches the next pages in viewport. Clicking a post loads almost instantly.\n\n**Common Mistakes:** Using `\u003Ca href=\"\u002Fabout\">` instead of `\u003CNuxtLink>` – causes full page reload, losing SPA benefits and killing performance. Forgetting to handle external links correctly (they work but prefetch is disabled). Overusing `prefetch` on many links can cause excessive network requests.\n\n**Edge Cases:** Prefetching can be disabled globally in config. For routes that require authentication, prefetching may fetch data that the user shouldn't see (but the component code is still loaded). Use `prefetch: false` for sensitive routes.\n\n**Interview Follow-ups:** \"How does NuxtLink prefetching work with SSR?\" \"Can you customize prefetch threshold?\"\n\n**Best Practices:** Always use `\u003CNuxtLink>` for internal navigation. Use `external` prop explicitly for external links? Actually it auto-detects. For dynamic prefetching, use `prefetchOn` option. Leverage `activeClass` and `exactActiveClass` for styling active links.\n\n**Performance Considerations:** Prefetching improves perceived performance but can waste bandwidth if too aggressive. Nuxt's default (viewport-based) is usually optimal. On mobile data, consider disabling global prefetch with `prefetchLinks: false` in config.\n\n**SEO Considerations:** `\u003CNuxtLink>` renders as an `\u003Ca>` tag with proper `href`, so crawlers follow links correctly. No negative SEO impact.\n\n**Production Recommendations:** Monitor prefetch network usage; if users on slow networks complain, reduce prefetch aggressiveness. Use `noPrefetch` class for links that shouldn't be prefetched (e.g., logout).\n\n**Latest Nuxt Patterns:** Nuxt 3's `\u003CNuxtLink>` supports `custom` prop for using with custom components. Also, `prefetch` is enabled by default in viewport, but you can set `prefetch: { default: false }` globally.\n\n**TypeScript Example:**\n```vue\n\u003Cscript setup lang=\"ts\">\n\u002F\u002F typed route\nconst route = useRoute()\n\u003C\u002Fscript>\n\u003Ctemplate>\n  \u003CNuxtLink :to=\"{ name: 'user-profile', params: { id: route.params.id } }\">\n    Profile\n  \u003C\u002FNuxtLink>\n\u003C\u002Ftemplate>\n```\n\n**Interview Tip:** Highlight the performance advantage of `\u003CNuxtLink>` over plain `\u003CRouterLink>`: automatic prefetching reduces perceived latency dramatically, often to \u003C100ms.\n\n**Common Follow-up:** \"What's the difference between prefetching and preloading?\"\n\n**Real-world Example:** A large documentation site with hundreds of pages. Using `\u003CNuxtLink>`, the next page's assets are prefetched as the user scrolls, so when they click 'Next Page', the new page loads instantly. This made the site feel like a native app, reducing bounce rates.",[219,220,221,105],"nuxtlink","navigation","prefetch","Highlight the performance advantage of `\u003CNuxtLink>` over plain `\u003CRouterLink>`: automatic prefetching reduces perceived latency dramatically, often to \u003C100ms.","What's the difference between prefetching and preloading?","A large documentation site with hundreds of pages. Using `\u003CNuxtLink>`, the next page's assets are prefetched as the user scrolls, so when they click 'Next Page', the new page loads instantly. This made the site feel like a native app, reducing bounce rates.",{"id":226,"category":227,"question":228,"answer":229,"level":10,"tags":230,"interviewTip":234,"commonFollowUp":235,"realWorldExample":236},20,"Middleware","What are middleware basics in Nuxt and how do you define them?","**Concept Explanation:** Middleware in Nuxt are functions that run before rendering a page or a group of pages. They can be used for authentication checks, redirects, logging, or modifying route parameters. Nuxt supports three types: global middleware (runs on every route change), named middleware (runs on specific pages), and route middleware (defined inline in a page).\n\n**Internal Working:** Nuxt collects middleware from the `middleware\u002F` directory and from `definePageMeta`. Before rendering a page, Nuxt runs these functions in sequence. If a middleware returns `false` or calls `abortNavigation()`, the navigation is canceled. Middleware can also return a `navigateTo` to redirect. On the server, middleware runs during SSR; on client, it runs during client-side navigation.\n\n**Request Flow:** 1) Navigation triggered (initial page load or client-side) → 2) Nuxt resolves layout and page components → 3) Runs all applicable middleware in order (global → named → inline) → 4) If no abortion\u002Fredirect, proceeds to render the page.\n\n**Lifecycle:** Middleware runs before component creation, so they cannot access component state but can use composables like `useRoute`, `useRouter`, `useCookie`.\n\n**Syntax & Code Example (named middleware):**\n`middleware\u002Fauth.ts`:\n```ts\nexport default defineNuxtRouteMiddleware((to, from) => {\n  const user = useCookie('user')\n  if (!user.value) {\n    return navigateTo('\u002Flogin')\n  }\n})\n```\nUsage in page:\n```vue\n\u003Cscript setup>\ndefinePageMeta({\n  middleware: 'auth'\n})\n\u003C\u002Fscript>\n```\n\n**Practical Example:** A dashboard page that requires authentication. Create `auth` middleware that checks for a token cookie and redirects to login if missing.\n\n**Common Mistakes:** Forgetting to `export default` the middleware function. Returning `false` without using `abortNavigation` (still works but `false` is deprecated). Using `useState` in middleware without understanding it's per-request (fine, but state won't persist across navigations unless using `useCookie`).\n\n**Edge Cases:** Middleware can be async (return a Promise). Global middleware is defined in `nuxt.config.ts` with `router: { middleware: ['auth'] }`. Middleware ordering: global runs first, then named (in array order), then inline. Middleware can be skipped on server or client using `process.client`.\n\n**Interview Follow-ups:** \"How do you pass data from middleware to page?\" \"Can middleware be used for analytics tracking?\"\n\n**Best Practices:** Keep middleware focused and small. Use `navigateTo` for redirects, not `router.push`. Avoid heavy async operations in middleware (they delay rendering). Use `useCookie` for auth checks.\n\n**Performance Considerations:** Middleware runs on every navigation; keep them fast. For expensive checks (e.g., API validation), do them on the server or in a plugin.\n\n**SEO Considerations:** Middleware redirects happen on server during SSR, so crawlers see the final URL correctly.\n\n**Production Recommendations:** Use global middleware for authentication across the entire app. Use named middleware for role-based access. Avoid inline middleware unless trivial; prefer named for reusability.\n\n**Latest Nuxt Patterns:** Nuxt 3's middleware can be defined as `.ts` or `.js`. The `defineNuxtRouteMiddleware` provides better TypeScript inference. Middleware can also be async and use `useFetch` (but careful with SSR).\n\n**TypeScript Example:**\n```ts\nexport default defineNuxtRouteMiddleware((to, from) => {\n  const user = useCookie\u003C{ role: string }>('user')\n  if (user.value?.role !== 'admin') {\n    return abortNavigation('Access denied')\n  }\n})\n```\n\n**Interview Tip:** Emphasize that middleware is the standard place for authentication and route guards, similar to Vue Router's `beforeEach` but with Nuxt's conventions.\n\n**Common Follow-up:** \"What's the difference between middleware and server middleware?\"\n\n**Real-world Example:** An e-commerce site has `auth` middleware for account pages, `guest` middleware to prevent logged-in users from seeing login page, and `analytics` global middleware that logs every route change to a third-party service.",[231,232,233,105],"middleware","guards","authentication","Emphasize that middleware is the standard place for authentication and route guards, similar to Vue Router's `beforeEach` but with Nuxt's conventions.","What's the difference between middleware and server middleware?","An e-commerce site has `auth` middleware for account pages, `guest` middleware to prevent logged-in users from seeing login page, and `analytics` global middleware that logs every route change to a third-party service.",{"id":238,"category":239,"question":240,"answer":241,"level":10,"tags":242,"interviewTip":247,"commonFollowUp":248,"realWorldExample":249},21,"Plugins","What are plugins in Nuxt and how do you use them?","**Concept Explanation:** Plugins are JavaScript or TypeScript files that run before the root Vue app is created. They are used to inject global functionality, register Vue components\u002Fdirectives, set up third-party libraries (e.g., Pinia, Vuetify, VueQuery), and modify the Vue instance. Plugins live in the `plugins\u002F` directory and are automatically loaded.\n\n**Internal Working:** During Nuxt's initialization, it reads all files in `plugins\u002F` and executes them in order (alphabetically, or you can specify order with `~\u002Fplugins\u002F01-foo.ts`). Plugins have access to the Vue app instance via `provide` and can also inject properties into `nuxtApp`. Plugins can run on server, client, or both.\n\n**Request Flow (SSR):** 1) Nuxt starts → 2) Server plugins run (before render) → 3) Client plugins run (after hydration). For client-only plugins, they run only in browser.\n\n**Lifecycle:** Plugins run once per request on server, once per page load on client. They are the earliest point to interact with the Vue app (before layouts and pages).\n\n**Syntax & Code Example (plugin):**\n`plugins\u002Fvue-query.ts`:\n```ts\nimport { VueQueryPlugin } from '@tanstack\u002Fvue-query'\n\nexport default defineNuxtPlugin((nuxtApp) => {\n  nuxtApp.vueApp.use(VueQueryPlugin)\n  \u002F\u002F Provide a helper\n  return {\n    provide: {\n      hello: (msg: string) => console.log(msg)\n    }\n  }\n})\n```\nUsage in component: `const { $hello } = useNuxtApp()`\n\n**Practical Example:** Adding a global toast notification system. Create a plugin that provides `$toast` with `success()`, `error()` methods using a third-party library.\n\n**Common Mistakes:** Not using `defineNuxtPlugin` wrapper (Nuxt 3 requires it). Overusing plugins for simple composables (composables are auto-imported, plugins are for app-level setup). Forgetting to set `ssr: false` for client-only libraries (like those that use `window`).\n\n**Edge Cases:** Plugins can have dependencies; order matters. You can prefix with `client\u002F` or `server\u002F` directories to restrict where they run (e.g., `plugins\u002Fclient\u002Fanalytics.ts`). Plugins can be async (return a promise).\n\n**Interview Follow-ups:** \"What's the difference between plugins and composables?\" \"How do you inject a global property?\"\n\n**Best Practices:** Use plugins for third-party integrations and global app setup. For reusable logic, prefer composables. Name plugins with a clear prefix (e.g., `pinia.client.ts`). Use `provide` and `inject` via `useNuxtApp` rather than adding to `nuxtApp.vueApp.config.globalProperties`.\n\n**Performance Considerations:** Plugins increase initial JavaScript bundle (especially client plugins). Use `ssr: false` for client-only plugins to reduce server-side bundle. Lazy-load heavy plugins if possible.\n\n**SEO Considerations:** Only relevant if plugin modifies head or content; ensure it works during SSR.\n\n**Production Recommendations:** Use `plugins\u002F` for libraries like Pinia, i18n, Vuetify, etc. Keep plugin code minimal – defer heavy initialization to components. Use `client` mode for analytics, ads, or any window-dependent code.\n\n**Latest Nuxt Patterns:** Nuxt 3 supports `plugins\u002F` subdirectories with `.client.ts` and `.server.ts` suffixes. Plugins can also be defined as `object` with `hooks` to hook into Nuxt lifecycle.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F plugins\u002Fmy-plugin.ts\nexport default defineNuxtPlugin(() => {\n  return {\n    provide: {\n      myMethod: (input: string): string => `Hello ${input}`\n    }\n  }\n})\n\n\u002F\u002F Component\nconst { $myMethod } = useNuxtApp()\n```\n\n**Interview Tip:** Emphasize that plugins are for 'app setup' while composables are for 'logic reuse' – they serve different purposes. A common mistake is using plugins where composables would suffice.\n\n**Common Follow-up:** \"How do you create a plugin that only runs on the client?\"\n\n**Real-world Example:** A Nuxt app integrating Stripe payments. A plugin initializes Stripe.js with publishable key, provides `$stripe` instance for components to use. Since Stripe uses `window`, the plugin is marked `ssr: false` to avoid errors during server rendering.",[243,244,245,246],"plugins","global","vue-app","third-party","Emphasize that plugins are for 'app setup' while composables are for 'logic reuse' – they serve different purposes. A common mistake is using plugins where composables would suffice.","How do you create a plugin that only runs on the client?","A Nuxt app integrating Stripe payments. A plugin initializes Stripe.js with publishable key, provides `$stripe` instance for components to use. Since Stripe uses `window`, the plugin is marked `ssr: false` to avoid errors during server rendering.",{"id":251,"category":252,"question":253,"answer":254,"level":10,"tags":255,"interviewTip":259,"commonFollowUp":260,"realWorldExample":261},22,"Server","What are server API basics in Nuxt? How do you create API endpoints?","**Concept Explanation:** Nuxt includes a built-in server engine (Nitro) that allows you to create API endpoints directly inside your Nuxt project, without needing a separate backend. These endpoints live in the `server\u002Fapi\u002F` directory and automatically get mounted under `\u002Fapi\u002F**`. They can handle requests, connect to databases, and return JSON or other responses.\n\n**Internal Working:** Nitro scans the `server\u002F` directory and generates server routes. Each file in `server\u002Fapi\u002F` becomes an endpoint. The server uses `h3` under the hood, with event handlers that receive the request and return a response. During `nuxt build`, Nitro compiles these endpoints into a standalone server that can be deployed anywhere.\n\n**Request Flow:** 1) Client calls `GET \u002Fapi\u002Fproducts` → 2) Nitro server receives request → 3) Matches `server\u002Fapi\u002Fproducts.get.ts` (or `.js`) → 4) Runs the handler → 5) Returns JSON response.\n\n**Lifecycle:** Endpoint handlers run per request, independent of the Vue rendering lifecycle.\n\n**Syntax & Code Example (API endpoint):**\n`server\u002Fapi\u002Fhello.get.ts`:\n```ts\nexport default defineEventHandler((event) => {\n  return { message: 'Hello World' }\n})\n```\n`server\u002Fapi\u002Fproducts\u002F[id].get.ts`:\n```ts\nexport default defineEventHandler(async (event) => {\n  const id = getRouterParam(event, 'id')\n  \u002F\u002F fetch from database\n  return { id, name: `Product ${id}` }\n})\n```\nCalling from frontend:\n```vue\n\u003Cscript setup>\nconst { data } = await useFetch('\u002Fapi\u002Fproducts\u002F123')\n\u003C\u002Fscript>\n```\n\n**Practical Example:** A blog with comments. Create `server\u002Fapi\u002Fcomments.post.ts` to add a comment, and `server\u002Fapi\u002Fcomments\u002F[id].delete.ts` to delete. The frontend calls these endpoints via `$fetch`.\n\n**Common Mistakes:** Forgetting to use the correct HTTP method suffix (`.get.ts`, `.post.ts`, etc.) – without suffix, it handles all methods. Not using `defineEventHandler` (requires it). Using Node.js-specific modules (like `fs`) without ensuring the deployment runtime supports them (use Nitro storage or `useStorage` instead).\n\n**Edge Cases:** Endpoints can also be defined in `server\u002Froutes\u002F` for custom paths (not prefixed with `\u002Fapi`). You can use `event.context` to pass data between middleware and handlers. API routes have access to Nitro's built-in utilities like `useStorage`, `sendStream`, etc.\n\n**Interview Follow-ups:** \"How do you handle authentication in API routes?\" \"Can you connect to a database from server\u002Fapi?\"\n\n**Best Practices:** Keep API handlers thin; move business logic to `server\u002Futils\u002F` or `server\u002Fservices\u002F`. Use `createError` to throw HTTP errors. Validate request body using `readBody` and a validation library. Use `useRuntimeConfig` for secrets (DB credentials).\n\n**Performance Considerations:** API endpoints run in the same process as SSR (unless deployed separately). Heavy endpoints can block rendering; consider caching with `defineCachedEventHandler`.\n\n**SEO Considerations:** API endpoints are not crawled by default (they return JSON). Use `robots.txt` to disallow if needed.\n\n**Production Recommendations:** Deploy to platforms that support Nitro (Vercel, Netlify, Cloudflare). Set up CORS if needed via `event.node.res.setHeader`. Use rate limiting in production to prevent abuse.\n\n**Latest Nuxt Patterns:** Nuxt 3 supports `server\u002Fapi\u002F` with TypeScript; auto-imports for `defineEventHandler` and utility functions like `getQuery`, `getRouterParam`. Also supports WebSocket via `server\u002Fwebsocket\u002F` (experimental).\n\n**TypeScript Example:**\n```ts\n\u002F\u002F server\u002Fapi\u002Fuser.post.ts\nexport default defineEventHandler(async (event) => {\n  const body = await readBody\u003C{ name: string; email: string }>(event)\n  if (!body.email) {\n    throw createError({ statusCode: 400, message: 'Email required' })\n  }\n  \u002F\u002F save to DB\n  return { success: true }\n})\n```\n\n**Interview Tip:** Emphasize that Nuxt's server API endpoints eliminate the need for a separate backend for many applications, simplifying deployment and reducing costs.\n\n**Common Follow-up:** \"How do you protect API endpoints with authentication?\"\n\n**Real-world Example:** A small e-commerce site built entirely in Nuxt: product data is stored in a headless CMS, but the cart, user authentication, and order processing are handled via `server\u002Fapi` endpoints using a PostgreSQL database. This single codebase serves both frontend and backend, deployed as one unit to Vercel.",[256,257,38,258],"server","api","backend","Emphasize that Nuxt's server API endpoints eliminate the need for a separate backend for many applications, simplifying deployment and reducing costs.","How do you protect API endpoints with authentication?","A small e-commerce site built entirely in Nuxt: product data is stored in a headless CMS, but the cart, user authentication, and order processing are handled via `server\u002Fapi` endpoints using a PostgreSQL database. This single codebase serves both frontend and backend, deployed as one unit to Vercel.",{"id":263,"category":264,"question":265,"answer":266,"level":10,"tags":267,"interviewTip":271,"commonFollowUp":272,"realWorldExample":273},23,"Assets","What is the difference between the assets and public folders in Nuxt?","**Concept Explanation:** The `assets\u002F` folder is for files that need to be processed by the build tool (Vite\u002FWebpack), such as CSS, images, fonts that you import in your components. The `public\u002F` folder is for static assets that are served as-is without processing; they are placed in the root of the built site. Understanding the distinction affects caching, bundling, and referencing.\n\n**Internal Working:** Files in `assets\u002F` are processed by Vite: they can be optimized (image compression), hashed for cache busting, and imported via JavaScript. Files in `public\u002F` are simply copied to the `dist\u002F` folder during build, preserving their names and paths. They are served directly by the web server.\n\n**Request Flow:** For `assets\u002F` images referenced via `~\u002Fassets\u002Flogo.png`, the build system returns a hashed URL (e.g., `\u002Flogo-abc123.png`). For `public\u002F` files referenced via `\u002Flogo.png`, the server serves the exact file.\n\n**Lifecycle:** Build time: `assets\u002F` processed by Vite; `public\u002F` copied. Runtime: both served as static files.\n\n**Syntax & Code Example:**\n```vue\n\u003C!-- Using asset (processed) -->\n\u003Ctemplate>\n  \u003Cimg src=\"~\u002Fassets\u002Flogo.png\" alt=\"Logo\">\n  \u003C!-- or dynamic -->\n  \u003Cimg :src=\"logoUrl\" \u002F>\n\u003C\u002Ftemplate>\n\u003Cscript setup>\nimport logoUrl from '~\u002Fassets\u002Flogo.png'\n\u003C\u002Fscript>\n\n\u003C!-- Using public file -->\n\u003Cimg src=\"\u002Flogo.png\" alt=\"Logo\">\n```\nCSS background in `assets\u002Fcss\u002Fmain.css`:\n```css\n.bg { background-image: url('~\u002Fassets\u002Fbg.jpg'); }\n```\n\n**Practical Example:** Your logo (rarely changed) – could go in `public\u002F` for simple referencing. User-uploaded avatars – can't go in `assets\u002F` because they are dynamic; they go in `public\u002F` or external storage. A CSS file that needs PostCSS processing – put in `assets\u002F`. A favicon – `public\u002Ffavicon.ico`.\n\n**Common Mistakes:** Putting large images in `assets\u002F` that are not imported anywhere – they might be missed by tree-shaking? Actually Vite includes all assets in `assets\u002F` that are referenced, but unreferenced files are not bundled. However, for static files, `public\u002F` is simpler. Referencing `public` files with `~\u002F` prefix (incorrect, use absolute `\u002F`).\n\n**Edge Cases:** Dynamic asset imports: `const img = await import(`~\u002Fassets\u002F${name}.png`)` – works but requires webpack\u002Fvite magic. `public` files cannot be imported dynamically; you must construct the URL string.\n\n**Interview Follow-ups:** \"Which folder is better for performance?\" \"Can I use subdirectories in public?\"\n\n**Best Practices:** Use `assets\u002F` for files that are part of your build pipeline (SCSS, images that need optimization). Use `public\u002F` for static files that don't change often and don't need processing (robots.txt, favicon, manifest.json, third-party scripts). For user uploads, use external storage (S3) not `public\u002F`, because `public\u002F` is overwritten on each build.\n\n**Performance Considerations:** `assets\u002F` files get hashed filenames, enabling long-term caching. `public\u002F` files are not hashed, so you must version them manually (e.g., `style.css?v=1.2`). Asset optimization (image compression) only applies to `assets\u002F`.\n\n**SEO Considerations:** Not directly relevant, but images in `assets\u002F` may have different URLs after build; ensure `public\u002F` for static SEO assets like `sitemap.xml`.\n\n**Production Recommendations:** Use `public\u002F` for static assets that must have predictable URLs (e.g., `\u002Fapple-touch-icon.png`). For everything else, prefer `assets\u002F` for better build optimization.\n\n**Latest Nuxt Patterns:** Nuxt 3 supports both folders; you can also configure additional static directories via `nitro.publicAssets`.\n\n**TypeScript Example:** Not applicable.\n\n**Interview Tip:** Use the analogy: `public\u002F` is like a static file server; `assets\u002F` is like a 'source' folder that goes through a build pipeline.\n\n**Common Follow-up:** \"How do you reference an image from CSS?\"\n\n**Real-world Example:** A marketing site has a hero image that should be optimized (resized, compressed) – placed in `assets\u002F`. The `robots.txt` and `sitemap.xml` must be at the root of the site – placed in `public\u002F`.",[268,269,82,270],"assets","public","build","Use the analogy: `public\u002F` is like a static file server; `assets\u002F` is like a 'source' folder that goes through a build pipeline.","How do you reference an image from CSS?","A marketing site has a hero image that should be optimized (resized, compressed) – placed in `assets\u002F`. The `robots.txt` and `sitemap.xml` must be at the root of the site – placed in `public\u002F`.",{"id":275,"category":276,"question":277,"answer":278,"level":10,"tags":279,"interviewTip":283,"commonFollowUp":284,"realWorldExample":285},24,"Configuration","What is nuxt.config.ts and what can you configure there?","**Concept Explanation:** `nuxt.config.ts` is the main configuration file for a Nuxt application. It controls everything from rendering mode (`ssr`), routing rules, CSS, modules, build options, runtime config, and Nitro settings. It's written in TypeScript and supports autocompletion.\n\n**Internal Working:** At build and runtime, Nuxt reads this file, merges it with defaults and any layers, and generates the final configuration. It's used by both the build tools (Vite\u002FWebpack) and the server (Nitro). Changes require restarting the dev server.\n\n**Request Flow:** Not directly relevant – config is build-time.\n\n**Lifecycle:** Loaded once when Nuxt starts.\n\n**Syntax & Code Example:**\n```ts\nexport default defineNuxtConfig({\n  ssr: true,                        \u002F\u002F Enable SSR\n  nitro: {                          \u002F\u002F Server engine config\n    preset: 'vercel',\n    storage: { \u002F* ... *\u002F }\n  },\n  css: ['~\u002Fassets\u002Fcss\u002Fmain.css'],   \u002F\u002F Global CSS\n  modules: ['@nuxtjs\u002Ftailwindcss'], \u002F\u002F Nuxt modules\n  runtimeConfig: {                  \u002F\u002F Environment variables\n    public: { apiBase: '\u002Fapi' },\n    private: { secretKey: '' }\n  },\n  app: {                            \u002F\u002F App-level config\n    head: { title: 'My App' },\n    layoutTransition: { name: 'layout' }\n  },\n  routeRules: {                     \u002F\u002F Hybrid rendering\n    '\u002F': { ssr: true },\n    '\u002Fblog\u002F**': { static: true }\n  }\n})\n```\n\n**Practical Example:** Setting up Tailwind CSS: add `@nuxtjs\u002Ftailwindcss` to modules, and Nuxt automatically configures it. Setting `runtimeConfig.public.apiBase` to `https:\u002F\u002Fapi.example.com` for production and `http:\u002F\u002Flocalhost:3000` for development.\n\n**Common Mistakes:** Placing secrets in `public` runtimeConfig (exposed to client). Overriding default `app.baseURL` incorrectly (leads to 404s). Not restarting dev server after changing config. Using `env` property (deprecated in Nuxt 3 – use `runtimeConfig` instead).\n\n**Edge Cases:** Config can be overridden by layers, environment-specific files (`.env`, `nuxt.config.override.ts`), and the `--config` CLI flag. Some options are read-only after build (`ssr`, `target`).\n\n**Interview Follow-ups:** \"How do you set different config for production and development?\" \"What is the difference between runtimeConfig and .env?\"\n\n**Best Practices:** Keep config minimal; use modules for complex setups. Use `runtimeConfig` for environment variables. Never hardcode secrets; always use `.env` and `runtimeConfig.private`. Use `defineNuxtConfig` for TypeScript support.\n\n**Performance Considerations:** Some options (like `build.transpile`) affect build performance. `routeRules` with `static: true` impact build time (pre-rendering).\n\n**SEO Considerations:** `app.head` sets global meta tags; individual pages can override via `useHead`.\n\n**Production Recommendations:** Use different config per environment via `NUXT_PUBLIC_*` env variables or `NUXT_*` for runtime config. Enable `sourcemap: false` in production for security. Set `nitro.compressPublicAssets: true` for smaller bundles.\n\n**Latest Nuxt Patterns:** Nuxt 3 uses `defineNuxtConfig` with full TypeScript support. `runtimeConfig` replaces the old `publicRuntimeConfig` and `privateRuntimeConfig`. `imports` option lets you customize auto-imports.\n\n**TypeScript Example:** The config file itself is TypeScript; you get autocomplete for all options.\n\n**Interview Tip:** Emphasize that `nuxt.config.ts` is the control center; knowing key options (`ssr`, `routeRules`, `runtimeConfig`, `nitro`) demonstrates understanding of Nuxt architecture.\n\n**Common Follow-up:** \"How do you access runtimeConfig in a component?\"\n\n**Real-world Example:** A Nuxt app deployed to multiple environments (dev, staging, prod). The `nuxt.config.ts` sets `runtimeConfig.public.apiBase` to an empty string, and `.env` files set `NUXT_PUBLIC_API_BASE` per environment. This allows the same config file to work everywhere.",[280,281,282],"configuration","nuxt-config","runtime-config","Emphasize that `nuxt.config.ts` is the control center; knowing key options (`ssr`, `routeRules`, `runtimeConfig`, `nitro`) demonstrates understanding of Nuxt architecture.","How do you access runtimeConfig in a component?","A Nuxt app deployed to multiple environments (dev, staging, prod). The `nuxt.config.ts` sets `runtimeConfig.public.apiBase` to an empty string, and `.env` files set `NUXT_PUBLIC_API_BASE` per environment. This allows the same config file to work everywhere.",{"id":287,"category":288,"question":289,"answer":290,"level":10,"tags":291,"interviewTip":295,"commonFollowUp":296,"realWorldExample":297},25,"SEO","What are SEO basics in Nuxt and how do you manage meta tags?","**Concept Explanation:** SEO (Search Engine Optimization) in Nuxt is primarily about ensuring search engines can crawl and index your content. Nuxt's SSR and SSG modes help by providing full HTML to crawlers. Meta tags (title, description, keywords, Open Graph, Twitter cards) can be managed using composables like `useHead` and `useSeoMeta`. Nuxt automatically handles canonical URLs and structured data options.\n\n**Internal Working:** The `useHead` composable updates the document's `\u003Chead>` section reactively. During SSR, it collects all head configurations from the page, layout, and `app.vue`, merges them (with page overriding layout), and serializes them into the HTML. On the client, `useHead` can dynamically update head tags as the user navigates.\n\n**Request Flow:** 1) Request for `\u002Fproduct\u002F1` → 2) Nuxt renders page, collects `useHead` calls → 3) Generates `\u003Ctitle>`, `\u003Cmeta>` tags in HTML → 4) Crawler sees complete meta information.\n\n**Lifecycle:** `useHead` can be called in components, pages, layouts, and plugins. It's reactive; changes trigger head updates.\n\n**Syntax & Code Example:**\n```vue\n\u003Cscript setup>\n\u002F\u002F Basic useHead\nuseHead({\n  title: 'My Page',\n  meta: [\n    { name: 'description', content: 'Page description' }\n  ]\n})\n\n\u002F\u002F useSeoMeta (recommended for SEO)\nuseSeoMeta({\n  title: 'My Page',\n  description: 'Page description',\n  ogTitle: 'My Page',\n  ogDescription: 'Open Graph description',\n  twitterCard: 'summary_large_image'\n})\n\u003C\u002Fscript>\n```\n\n**Practical Example:** A blog post page dynamically sets title and description from fetched data:\n```vue\n\u003Cscript setup>\nconst { data: post } = await useFetch('\u002Fapi\u002Fposts\u002F1')\nuseSeoMeta({\n  title: post.value.title,\n  description: post.value.excerpt,\n  ogImage: post.value.image\n})\n\u003C\u002Fscript>\n```\n\n**Common Mistakes:** Not providing unique titles per page (duplicate titles hurt SEO). Overwriting global title template incorrectly. Putting reactive data in `useHead` without computed (can cause update issues). Forgetting to set `og:url` and canonical URL.\n\n**Edge Cases:** `useHead` can be called multiple times; Nuxt merges them (last write wins for conflicting keys). For reactive updates, pass a computed or ref: `useHead({ title: computed(() => pageTitle.value) })`.\n\n**Interview Follow-ups:** \"How do you set a global title template?\" \"What is the difference between useHead and useSeoMeta?\"\n\n**Best Practices:** Use `useSeoMeta` for all SEO tags as it prevents duplication. Set a global title template in `nuxt.config.ts` or `app.vue` with `titleTemplate: '%s - My Site'`. Provide Open Graph and Twitter cards for social sharing. Generate a sitemap using `@nuxtjs\u002Fsitemap` module.\n\n**Performance Considerations:** Head updates during client-side navigation are fast. Avoid large reactive objects inside `useHead`.\n\n**SEO Considerations:** Nuxt's SSR ensures meta tags are present in initial HTML; crawlers don't need to execute JavaScript. Use structured data (JSON-LD) via `useHead` with `script` tag for rich snippets.\n\n**Production Recommendations:** Audit your site with Google Search Console. Use `nuxt generate` for static sites to pre-render all SEO pages. Test social sharing using Open Graph debuggers.\n\n**Latest Nuxt Patterns:** Nuxt 3's `useSeoMeta` is the preferred way; it also supports `og:image:alt`, `og:type`, etc. The `@nuxtjs\u002Fseo` kit provides more advanced features.\n\n**TypeScript Example:**\n```ts\nuseSeoMeta({\n  title: 'My Page',\n  description: 'Description',\n  \u002F\u002F TypeScript will autocomplete known meta names\n})\n```\n\n**Interview Tip:** Emphasize that SSR alone doesn't guarantee SEO; you must also manage meta tags per page. `useSeoMeta` is the modern standard.\n\n**Common Follow-up:** \"How do you handle canonical URLs for duplicate content?\"\n\n**Real-world Example:** An e-commerce product page uses `useSeoMeta` to set dynamic title (`Product XYZ | Store`), description, product image, and price (via `product:price:amount` Open Graph property). This improves click-through rates from social media and search results.",[26,292,293,294],"meta-tags","usehead","useseometa","Emphasize that SSR alone doesn't guarantee SEO; you must also manage meta tags per page. `useSeoMeta` is the modern standard.","How do you handle canonical URLs for duplicate content?","An e-commerce product page uses `useSeoMeta` to set dynamic title (`Product XYZ | Store`), description, product image, and price (via `product:price:amount` Open Graph property). This improves click-through rates from social media and search results.",{"id":299,"category":288,"question":300,"answer":301,"level":10,"tags":302,"interviewTip":305,"commonFollowUp":306,"realWorldExample":307},26,"What is useHead in Nuxt and how does it work?","**Concept Explanation:** `useHead` is a composable that allows you to dynamically set the HTML `\u003Chead>` section (title, meta tags, link tags, scripts, etc.) from anywhere in your Nuxt app – pages, layouts, components, or plugins. It's reactive, meaning head tags update when the provided values change.\n\n**Internal Working:** `useHead` uses Vue's reactivity system to track dependencies. When called, it registers head entries with Nuxt's head manager. During SSR, all registered head entries are collected, deduplicated, and rendered into HTML. On the client, `useHead` can dynamically update the head using `document.title` and `document.head` mutations.\n\n**Request Flow:** 1) Nuxt renders component tree → 2) Each `useHead` call adds to a head stack → 3) At the end of render, Nuxt merges entries (child overrides parent) → 4) Serializes to HTML → 5) Client hydrates and watches for changes.\n\n**Lifecycle:** `useHead` can be called during `setup` (runs on server and client). Reactive updates trigger re-renders of head.\n\n**Syntax & Code Example:**\n```vue\n\u003Cscript setup>\nuseHead({\n  title: 'Homepage',\n  titleTemplate: '%s - My Site', \u002F\u002F adds suffix\n  meta: [\n    { name: 'description', content: 'My awesome site' },\n    { name: 'keywords', content: 'nuxt, vue' }\n  ],\n  link: [\n    { rel: 'canonical', href: 'https:\u002F\u002Fmysite.com\u002Fpage' },\n    { rel: 'icon', type: 'image\u002Fx-icon', href: '\u002Ffavicon.ico' }\n  ],\n  script: [\n    { src: 'https:\u002F\u002Fexample.com\u002Fscript.js', defer: true }\n  ]\n})\n\u003C\u002Fscript>\n```\n\n**Practical Example:** A product page that sets title and description based on product data, and also adds a canonical URL to avoid duplicate content.\n\n**Common Mistakes:** Using `useHead` inside a conditional that runs after initial render (e.g., inside `onMounted`) – head updates will work but won't be included in SSR. Not using `computed` for dynamic values: `title: product.value.name` (this will not update reactively). Forgetting to pass an object.\n\n**Edge Cases:** Multiple `useHead` calls in the same component merge, but arrays are concatenated. To replace an array, use `replace: true`. `useHead` can also accept a function returning the head object for more complex reactivity.\n\n**Interview Follow-ups:** \"How does useHead differ from using the `head` property in pages?\" \"Can you use useHead in middleware?\"\n\n**Best Practices:** Use `useSeoMeta` for SEO meta tags – it's a wrapper around `useHead` with better DX. Set global defaults in `nuxt.config.ts` or `app.vue`. For dynamic titles, use `titleTemplate` to avoid repeating site name.\n\n**Performance Considerations:** Head updates are efficient; avoid large objects or frequent updates. SSR head generation is fast because it's just string concatenation.\n\n**SEO Considerations:** `useHead` ensures meta tags are present in the initial HTML for crawlers. Use `og:title`, `og:image` for social sharing.\n\n**Production Recommendations:** Validate generated head using browser devtools. Ensure no duplicate meta tags. Use `useHead` with `script` for analytics (with `defer` or `async`).\n\n**Latest Nuxt Patterns:** Nuxt 3's `useHead` is powered by `unhead` library, which supports reactive head management and deduplication. It also supports `head` property in `definePageMeta` as an alternative.\n\n**TypeScript Example:**\n```ts\nuseHead({\n  meta: [\n    { name: 'author', content: 'John Doe' } as const \u002F\u002F typed\n  ]\n})\n```\n\n**Interview Tip:** Emphasize that `useHead` is reactive and SSR-friendly, unlike manual `document.title` manipulation which only works client-side and breaks SSR.\n\n**Common Follow-up:** \"How do you set a default title template for all pages?\"\n\n**Real-world Example:** A news article page uses `useHead` to set the article title, publish date (as `article:published_time`), and author. The same component also updates the `\u003Clink rel=\"next\">` and `\u003Clink rel=\"prev\">` for paginated article lists, improving crawler navigation.",[293,26,303,304],"meta","head","Emphasize that `useHead` is reactive and SSR-friendly, unlike manual `document.title` manipulation which only works client-side and breaks SSR.","How do you set a default title template for all pages?","A news article page uses `useHead` to set the article title, publish date (as `article:published_time`), and author. The same component also updates the `\u003Clink rel=\"next\">` and `\u003Clink rel=\"prev\">` for paginated article lists, improving crawler navigation.",{"id":309,"category":288,"question":310,"answer":311,"level":10,"tags":312,"interviewTip":315,"commonFollowUp":316,"realWorldExample":317},27,"What is useSeoMeta and why should you use it over useHead for SEO?","**Concept Explanation:** `useSeoMeta` is a dedicated composable for setting SEO-related meta tags, including standard meta tags (description, keywords), Open Graph (og:title, og:image), and Twitter cards. It's a wrapper around `useHead` that provides a cleaner API and prevents common duplication mistakes (e.g., setting `og:title` and `twitter:title` separately).\n\n**Internal Working:** `useSeoMeta` maps its options to the appropriate `meta` tags in `useHead`. For example, `{ title: 'My Page' }` becomes `\u003Ctitle>My Page\u003C\u002Ftitle>` and also sets `og:title` and `twitter:title` if not explicitly provided. It automatically deduplicates and formats tag names (e.g., `ogImage` becomes `og:image`).\n\n**Request Flow:** Same as `useHead` – called during SSR\u002FCSR, updates head accordingly.\n\n**Lifecycle:** Same as `useHead`.\n\n**Syntax & Code Example:**\n```vue\n\u003Cscript setup>\nuseSeoMeta({\n  title: 'My Page',\n  description: 'This is a description',\n  ogTitle: 'My Page',\n  ogDescription: 'Open Graph description',\n  ogImage: '\u002Fimage.jpg',\n  twitterCard: 'summary_large_image',\n  \u002F\u002F shorthand: ogTitle automatically sets twitter:title if not set\n})\n\u003C\u002Fscript>\n```\nCompare with `useHead`:\n```ts\nuseHead({\n  title: 'My Page',\n  meta: [\n    { name: 'description', content: '...' },\n    { property: 'og:title', content: 'My Page' },\n    { name: 'twitter:title', content: 'My Page' }\n  ]\n})\n\u002F\u002F useSeoMeta is much shorter and less error-prone\n```\n\n**Practical Example:** A blog post page using data from CMS to set all SEO meta tags:\n```vue\n\u003Cscript setup>\nconst { data: post } = await useFetch('\u002Fapi\u002Fpost\u002F1')\nuseSeoMeta({\n  title: post.value.title,\n  description: post.value.excerpt,\n  ogImage: post.value.featuredImage,\n  ogType: 'article',\n  articlePublishedTime: post.value.date\n})\n\u003C\u002Fscript>\n```\n\n**Common Mistakes:** Using `useSeoMeta` but also manually adding duplicate meta tags with `useHead`, causing conflicts. Not using `ogType` for articles\u002Fvideos. Forgetting that `useSeoMeta` does NOT set `titleTemplate` – that's handled separately.\n\n**Edge Cases:** `useSeoMeta` can be used alongside `useHead`; they merge. However, if you set `title` in both, the last one wins. For complex non-SEO head tags (e.g., `link` tags), still use `useHead`.\n\n**Interview Follow-ups:** \"Does useSeoMeta handle `titleTemplate`?\" \"What about structured data (JSON-LD)?\"\n\n**Best Practices:** Always use `useSeoMeta` for SEO meta tags, `useHead` for other head elements (canonical, scripts, styles). Combine with `definePageMeta` if you need static head.\n\n**Performance Considerations:** Same as `useHead` – minimal overhead.\n\n**SEO Considerations:** Using `useSeoMeta` ensures you don't miss important tags like `og:image:alt` or `twitter:description`, improving social sharing.\n\n**Production Recommendations:** Set fallback SEO values in `app.vue` or `nuxt.config.ts` for pages without explicit `useSeoMeta`. Test with Open Graph debugger and Twitter Card validator.\n\n**Latest Nuxt Patterns:** `useSeoMeta` is part of the `@unhead\u002Fvue` integration; it supports `og:image:secure_url`, `og:image:type`, and other advanced properties. Also supports `robots` meta tag via `robots: 'index,follow'`.\n\n**TypeScript Example:**\n```ts\nuseSeoMeta({\n  title: 'Page',\n  robots: 'index, follow', \u002F\u002F typed\n  ogImage: 'https:\u002F\u002F...',\n  ogImageAlt: 'Image description'\n})\n```\n\n**Interview Tip:** Emphasize that `useSeoMeta` is the best practice for SEO because it abstracts away the complexity of Open Graph and Twitter tags, reducing human error.\n\n**Common Follow-up:** \"How do you set a dynamic og:image based on route?\"\n\n**Real-world Example:** A recipe website uses `useSeoMeta` to set recipe-specific meta tags: `ogType: 'article'`, `articleSection: 'Cooking'`, and `ogImage` pointing to the recipe photo. This results in rich snippets on social media, increasing click-through rates.",[294,26,313,314],"opengraph","twitter","Emphasize that `useSeoMeta` is the best practice for SEO because it abstracts away the complexity of Open Graph and Twitter tags, reducing human error.","How do you set a dynamic og:image based on route?","A recipe website uses `useSeoMeta` to set recipe-specific meta tags: `ogType: 'article'`, `articleSection: 'Cooking'`, and `ogImage` pointing to the recipe photo. This results in rich snippets on social media, increasing click-through rates.",[319,331,340,350,360,369,379,388,397,405,415,425,437,448,460,468],{"id":6,"category":320,"question":321,"answer":322,"level":323,"tags":324,"interviewTip":328,"commonFollowUp":329,"realWorldExample":330},"Nitro Basics","What is Nitro and how does it power Nuxt 3's server capabilities?","**Concept Explanation:** Nitro is the server engine that powers Nuxt 3. It's a standalone, cross-platform server toolkit that handles SSR, API routes, static serving, and deployment adapters. Nitro is not exclusive to Nuxt – it can be used independently. It provides a unified interface for deploying to any runtime (Node.js, Deno, Bun, Cloudflare Workers, Vercel Edge, etc.) with zero configuration changes.\n\n**Internal Working:** Nitro uses `h3` (a minimal HTTP framework) for request handling, `unstorage` for universal storage, and `rollup` for bundling. It scans the `server\u002F` directory and builds a server bundle optimized for the target deployment. Nitro also handles route rules (SSR\u002FCSR\u002FSSG), caching, and asset serving. During `nuxt build`, Nitro compiles the server logic into a deployable output (`.output\u002F` directory).\n\n**Request Flow:** 1) HTTP request arrives → 2) Nitro's server (e.g., Node.js listener) receives → 3) Routes matched (API endpoints, SSR renderer, static assets) → 4) Event handlers execute → 5) Response returned. The SSR renderer is just another Nitro route (`\u002F__nuxt\u002Frenderer` by default).\n\n**Lifecycle:** Build time: Nitro bundles server code. Runtime: Nitro initializes once per process (or per request on serverless), then handles requests.\n\n**Syntax & Code Example (Nitro config in nuxt.config.ts):**\n```ts\nexport default defineNuxtConfig({\n  nitro: {\n    preset: 'vercel-edge', \u002F\u002F deployment target\n    storage: {\n      redis: {\n        driver: 'redis',\n        url: process.env.REDIS_URL\n      }\n    },\n    routeRules: {\n      '\u002Fapi\u002F**': { cors: true, headers: { 'X-Custom': 'value' } }\n    }\n  }\n})\n```\n\n**Practical Example:** Deploy the same Nuxt app to Vercel (serverless), Netlify (functions), and Cloudflare Workers just by changing `nitro.preset`. No code changes needed.\n\n**Common Mistakes:** Assuming Nitro runs only on Node.js – it can run on edge runtimes with limitations (e.g., no `fs` module). Forgetting to use `defineEventHandler` in server routes. Using Node.js-specific libraries without ensuring the deployment runtime supports them.\n\n**Edge Cases:** On serverless platforms, Nitro's storage may be ephemeral; use persistent storage (database, Redis) for data that needs to survive. Nitro's `useStorage()` is universal but not all drivers work on all platforms.\n\n**Interview Follow-ups:** \"How does Nitro handle cold starts?\" \"Can I use Nitro without Nuxt?\"\n\n**Best Practices:** Use Nitro's built-in storage for caching and session data. Leverage `defineCachedEventHandler` for automatic response caching. Test your deployment preset locally with `nuxi preview`.\n\n**Performance Considerations:** Nitro's lazy-loaded chunks reduce serverless cold start times. Use `nitro.rollupConfig` to optimize bundle size. The `static` preset generates a fully static output with no server.\n\n**SEO Considerations:** Not directly relevant – Nitro serves the SSR HTML, which is SEO-friendly.\n\n**Production Recommendations:** Choose the right preset for your hosting platform. Enable `nitro.compressPublicAssets` for smaller asset sizes. Use environment variables for configuration, not hardcoded values.\n\n**Latest Nuxt Patterns:** Nitro 2 (in Nuxt 3) supports `openapi` generation from your API routes, and `devStorage` for local development.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F server\u002Fapi\u002Fhello.ts – fully typed\nexport default defineEventHandler(async (event) => {\n  const query = getQuery(event) \u002F\u002F returns Record\u003Cstring, any>\n  const name = query.name || 'World'\n  return { message: `Hello ${name}` }\n})\n```\n\n**Interview Tip:** Emphasize that Nitro is what makes Nuxt 3 a 'full-stack' framework, not just a frontend meta-framework. Understanding Nitro's adapter system shows depth.\n\n**Common Follow-up:** \"How does Nitro differ from Express?\"\n\n**Real-world Example:** A startup built a Nuxt app and initially deployed to Vercel (Node.js preset). Later, they needed to move to Cloudflare Workers for lower latency in Asia. They changed `nitro.preset: 'cloudflare'`, ran `nuxt build`, and redeployed – zero code changes. This flexibility saved weeks of rewriting.","intermediate",[38,256,325,326,327],"deployment","adapters","h3","Emphasize that Nitro is what makes Nuxt 3 a 'full-stack' framework, not just a frontend meta-framework. Understanding Nitro's adapter system shows depth.","How does Nitro differ from Express?","A startup built a Nuxt app and initially deployed to Vercel (Node.js preset). Later, they needed to move to Cloudflare Workers for lower latency in Asia. They changed `nitro.preset: 'cloudflare'`, ran `nuxt build`, and redeployed – zero code changes. This flexibility saved weeks of rewriting.",{"id":20,"category":227,"question":332,"answer":333,"level":323,"tags":334,"interviewTip":337,"commonFollowUp":338,"realWorldExample":339},"What are the different types of route middleware in Nuxt and how do they execute?","**Concept Explanation:** Nuxt has three types of route middleware: global (runs on every route change), named (attached to specific pages), and inline (defined directly in the page). They execute in a specific order: global middleware runs first (in the order defined in `nuxt.config.ts`), then named middleware (in the order listed in `definePageMeta`), and finally inline middleware (if any).\n\n**Internal Working:** Nuxt collects all middleware, normalizes them into functions, and creates a middleware pipeline. When navigation occurs, Nuxt runs this pipeline sequentially. If a middleware returns `navigateTo()` or `abortNavigation()`, the pipeline stops and the navigation is redirected or canceled. The pipeline runs on both server (during SSR) and client (during SPA navigation).\n\n**Request Flow (Initial SSR):** 1) Request received → 2) Nuxt resolves route → 3) Global middleware (from config) executes → 4) Page-specific named middleware executes → 5) Inline middleware executes → 6) Page renders.\n\n**Lifecycle:** Middleware runs before component creation, so no access to component state, but can use Nuxt composables like `useRoute`, `useRouter`, `useCookie`, `useFetch` (with caution).\n\n**Syntax & Code Example:**\n`middleware\u002Fglobal.ts` (global – needs registration in config):\n```ts\nexport default defineNuxtRouteMiddleware((to, from) => {\n  console.log('Global middleware running')\n})\n```\n`nuxt.config.ts` registration:\n```ts\nexport default defineNuxtConfig({\n  router: {\n    middleware: ['global']  \u002F\u002F runs on every route\n  }\n})\n```\nNamed middleware (`middleware\u002Fauth.ts`):\n```ts\nexport default defineNuxtRouteMiddleware((to, from) => {\n  const user = useCookie('user')\n  if (!user.value) return navigateTo('\u002Flogin')\n})\n```\nPage usage:\n```vue\n\u003Cscript setup>\ndefinePageMeta({\n  middleware: ['auth', 'logger'] \u002F\u002F order matters\n})\n\u002F\u002F Inline middleware\ndefinePageMeta({\n  middleware: (to, from) => {\n    console.log('Inline middleware')\n  }\n})\n\u003C\u002Fscript>\n```\n\n**Practical Example:** A dashboard area requires authentication (named `auth` middleware), logging every visit (global analytics middleware), and checking user role (named `admin` middleware). The global middleware logs, then `auth` checks login, then `admin` checks role.\n\n**Common Mistakes:** Forgetting that global middleware needs registration in `nuxt.config.ts` – just placing a file in `middleware\u002F` doesn't make it global. Returning `false` (deprecated) instead of `abortNavigation()`. Using `useFetch` in middleware without handling async properly (middleware can be async, but will delay navigation).\n\n**Edge Cases:** Middleware can be async – the navigation waits for the promise to resolve. If multiple middleware are async, they run sequentially. Middleware can be skipped on client or server using `process.client` \u002F `process.server` checks.\n\n**Interview Follow-ups:** \"How do you conditionally run middleware?\" \"Can middleware access the Vue app instance?\"\n\n**Best Practices:** Keep middleware focused and fast. Use `navigateTo` for redirects, `abortNavigation` for blocking. For complex auth, use `useCookie` and validate on server (middleware runs on server too). Avoid heavy computations.\n\n**Performance Considerations:** Middleware runs on every navigation, including client-side transitions. Keep them lightweight. If middleware makes API calls, they'll block rendering – consider moving those checks to pages with loading states.\n\n**SEO Considerations:** Middleware redirects on server produce correct HTTP redirect status (301\u002F302), good for SEO. `abortNavigation` results in a 404 if the page doesn't exist.\n\n**Production Recommendations:** Use global middleware for analytics, named middleware for auth, inline for trivial guards. Monitor middleware performance; if they cause delays, refactor.\n\n**Latest Nuxt Patterns:** Nuxt 3's middleware supports returning `navigateTo` directly (no need to return a promise). The `defineNuxtRouteMiddleware` provides better TypeScript inference.\n\n**TypeScript Example:**\n```ts\nexport default defineNuxtRouteMiddleware((to, from) => {\n  const user = useCookie\u003C{ role: 'admin' | 'user' }>('user')\n  if (to.meta.requiresAdmin && user.value?.role !== 'admin') {\n    return abortNavigation({ statusCode: 403, message: 'Forbidden' })\n  }\n})\n```\n\n**Interview Tip:** Emphasize the execution order and that global middleware is often underused. Many developers only know named middleware, but global middleware is powerful for analytics and theming.\n\n**Common Follow-up:** \"How do you pass data from middleware to pages?\" (Use `useState` or route meta)\n\n**Real-world Example:** An e-commerce site has global middleware that adds a `correlation-id` header for tracing, named `cart` middleware that checks if the cart is empty before proceeding to checkout, and inline middleware on the product page that redirects to a login page if a 'wishlist' query param is present but user is not logged in.",[231,244,335,336,232],"named","inline","Emphasize the execution order and that global middleware is often underused. Many developers only know named middleware, but global middleware is powerful for analytics and theming.","How do you pass data from middleware to pages?","An e-commerce site has global middleware that adds a `correlation-id` header for tracing, named `cart` middleware that checks if the cart is empty before proceeding to checkout, and inline middleware on the product page that redirects to a login page if a 'wishlist' query param is present but user is not logged in.",{"id":32,"category":276,"question":341,"answer":342,"level":323,"tags":343,"interviewTip":347,"commonFollowUp":348,"realWorldExample":349},"What is runtimeConfig and how do you use it for environment variables in Nuxt?","**Concept Explanation:** `runtimeConfig` is the modern way to handle environment variables and configuration in Nuxt 3. It replaces the deprecated `publicRuntimeConfig` and `privateRuntimeConfig`. It exposes configuration to the rest of your app, with a clear separation between public (exposed to the client) and private (server-only) values. Values are automatically populated from environment variables with the `NUXT_` prefix.\n\n**Internal Working:** During build, Nuxt reads `runtimeConfig` from `nuxt.config.ts` and merges it with environment variables. The `public` part is serialized and sent to the client (embedded in the HTML payload). The `private` part is only available on the server. At runtime, you access the config using `useRuntimeConfig()` composable, which returns an object with both public and private keys (private keys are undefined on the client).\n\n**Request Flow (Server):** `useRuntimeConfig()` returns full config (public + private). **Client:** returns only public keys; private keys are `undefined`. This prevents secret leakage.\n\n**Lifecycle:** Config is set at build time, but environment variable values are read at runtime (for server) or build time for public? Actually, public config is embedded at build time, private config is read at runtime on server. For serverless, private values are read from environment variables on each invocation.\n\n**Syntax & Code Example (nuxt.config.ts):**\n```ts\nexport default defineNuxtConfig({\n  runtimeConfig: {\n    \u002F\u002F Private keys (server-only)\n    apiSecret: 'default-secret',\n    dbUrl: '',\n    public: {\n      \u002F\u002F Public keys (exposed to client)\n      apiBase: '\u002Fapi',\n      appName: 'My App'\n    }\n  }\n})\n```\nEnvironment variables override:\n```bash\n# .env file\nNUXT_API_SECRET=real-secret\nNUXT_PUBLIC_API_BASE=https:\u002F\u002Fapi.example.com\n```\nAccess in component:\n```vue\n\u003Cscript setup>\nconst config = useRuntimeConfig()\n\u002F\u002F Client-side: config.public.apiBase is available, config.apiSecret is undefined\n\u002F\u002F Server-side: both available\nconst { data } = await useFetch(`${config.public.apiBase}\u002Fusers`)\n\u003C\u002Fscript>\n```\n\n**Practical Example:** Store Stripe publishable key in `public.stripePk` (exposed to client) and secret key in `stripeSecret` (server-only). Use the secret in `server\u002Fapi\u002Fcreate-payment.ts`.\n\n**Common Mistakes:** Putting secrets in `public` – they will be exposed to the browser. Using `process.env` directly (works but not recommended, as `runtimeConfig` provides better abstraction and TypeScript support). Forgetting to restart dev server after changing `.env`.\n\n**Edge Cases:** In serverless environments, private runtime config values are read from environment variables on each invocation – they can be updated without rebuilding. Public config values are baked into the client bundle at build time; to change them, you must rebuild.\n\n**Interview Follow-ups:** \"How do you access runtimeConfig in a plugin?\" \"What's the difference between runtimeConfig and .env?\"\n\n**Best Practices:** Always use `runtimeConfig` instead of `process.env`. Define default values in `nuxt.config.ts` so the app works without environment variables. Use `NUXT_` prefix for environment variables. Never commit `.env` file.\n\n**Performance Considerations:** Accessing `useRuntimeConfig()` is fast; it's a simple object lookup. No performance concerns.\n\n**SEO Considerations:** Not relevant.\n\n**Production Recommendations:** Use different `.env` files per environment (`.env.production`, `.env.staging`). For sensitive secrets, use your hosting platform's secret management (e.g., Vercel Secrets, AWS Secrets Manager).\n\n**Latest Nuxt Patterns:** Nuxt 3 automatically loads `.env` files. You can also use `$config` in Nitro event handlers: `event.context.runtimeConfig`.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F Extend runtimeConfig types\ndeclare module 'nuxt\u002Fschema' {\n  interface RuntimeConfig {\n    apiSecret: string\n    public: {\n      apiBase: string\n    }\n  }\n}\n\u002F\u002F Now useRuntimeConfig() is fully typed\n```\n\n**Interview Tip:** Emphasize the security boundary – `public` vs private is critical. Many junior devs expose secrets by putting them in `public`.\n\n**Common Follow-up:** \"How do you set runtimeConfig per route or per request?\"\n\n**Real-world Example:** A Nuxt app uses a headless CMS. The CMS API key is stored in `runtimeConfig.cmsApiKey` (private), and the base URL is in `runtimeConfig.public.cmsBaseUrl`. The server API endpoints use the private key to fetch data, while client-side components use the public base URL to request those endpoints. This keeps the API key secure.",[344,345,346,280],"runtimeconfig","env","environment","Emphasize the security boundary – `public` vs private is critical. Many junior devs expose secrets by putting them in `public`.","How do you set runtimeConfig per route or per request?","A Nuxt app uses a headless CMS. The CMS API key is stored in `runtimeConfig.cmsApiKey` (private), and the base URL is in `runtimeConfig.public.cmsBaseUrl`. The server API endpoints use the private key to fetch data, while client-side components use the public base URL to request those endpoints. This keeps the API key secure.",{"id":45,"category":239,"question":351,"answer":352,"level":323,"tags":353,"interviewTip":357,"commonFollowUp":358,"realWorldExample":359},"How do you create and use plugins in Nuxt 3 with different execution modes (client, server, both)?","**Concept Explanation:** Plugins in Nuxt 3 are modules that run before the Vue app is created. They can be configured to run only on the client, only on the server, or both. You control execution by naming conventions: `plugin.client.ts`, `plugin.server.ts`, or just `plugin.ts` (both). Plugins can also be async, delaying app startup until they resolve.\n\n**Internal Working:** During Nuxt initialization, it collects all plugin files, sorts them by name (alphabetically), and executes them in order. For server plugins, they run during SSR before rendering; for client plugins, they run during hydration. Async plugins (returning a promise) will block app creation until resolved. Plugins receive the `nuxtApp` instance and can access Vue's `app` object.\n\n**Request Flow (SSR with both plugins):** 1) Server starts → runs server plugins → 2) Request arrives → runs global middleware → 3) Server plugins (again? no, only once per process) – Actually, server plugins run once when Nitro server initializes, not per request. Client plugins run once per page load in the browser.\n\n**Lifecycle:** Plugins run before layouts and pages, making them ideal for setting up global providers (Pinia, i18n, etc.).\n\n**Syntax & Code Example:**\n`plugins\u002Fanalytics.client.ts` (client-only):\n```ts\nexport default defineNuxtPlugin(() => {\n  \u002F\u002F window, document are safe here\n  if (process.client) {\n    import('some-analytics').then(analytics => analytics.init())\n  }\n})\n```\n`plugins\u002Fapi.server.ts` (server-only):\n```ts\nexport default defineNuxtPlugin(() => {\n  \u002F\u002F Runs only on server\n  console.log('Server plugin running')\n  return {\n    provide: {\n      serverTime: () => new Date().toISOString()\n    }\n  }\n})\n```\n`plugins\u002Ftoast.ts` (both, but with client-only logic):\n```ts\nexport default defineNuxtPlugin((nuxtApp) => {\n  let toast\n  if (process.client) {\n    toast = createToast()\n    nuxtApp.vueApp.use(toast)\n  }\n  return {\n    provide: {\n      toast: (msg) => toast?.show(msg) || console.log(msg)\n    }\n  }\n})\n```\n\n**Practical Example:** A plugin that sets up Pinia store (both client and server), a plugin that adds Google Analytics (client-only), and a plugin that initializes a database connection (server-only).\n\n**Common Mistakes:** Using client-only APIs in a plugin that runs on server (e.g., `window`, `localStorage`). Forgetting to use `process.client` guard. Making a plugin async unnecessarily, delaying app startup.\n\n**Edge Cases:** Async plugins will block rendering on server, increasing TTFB. Client-only async plugins can cause layout shift if they delay hydration. Multiple plugins with dependencies need manual ordering (prefix with numbers: `01-foo.client.ts`, `02-bar.client.ts`).\n\n**Interview Follow-ups:** \"How do you inject a global property vs a provide\u002Finject key?\" \"Can plugins use composables?\"\n\n**Best Practices:** Use client-only plugins for third-party scripts that depend on `window`. Use server-only plugins for database connections or server initialization. Prefer `provide` over `vueApp.config.globalProperties` for better tree-shaking and TypeScript.\n\n**Performance Considerations:** Client plugins increase initial JS bundle size. Use `ssr: false` or `.client` suffix to exclude them from server bundle (but they still load on client). Lazy load heavy plugins with `import()` inside the plugin.\n\n**SEO Considerations:** Server plugins can inject meta tags or modify head via `useHead` (but head can also be set in pages).\n\n**Production Recommendations:** Keep plugins small. Use Nuxt modules for complex integrations (they are essentially plugins with auto-configuration). Test plugins in both dev and production modes.\n\n**Latest Nuxt Patterns:** Nuxt 3 supports `plugins\u002F` subdirectories and automatic sorting by name. You can also use `addPlugin` in a module.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F plugin with typed provide\nexport default defineNuxtPlugin(() => {\n  return {\n    provide: {\n      myMethod: (input: string): string => `Hello ${input}`\n    }\n  }\n})\n\n\u002F\u002F In component\ndeclare module '#app' {\n  interface NuxtApp {\n    $myMethod: (input: string) => string\n  }\n}\nconst { $myMethod } = useNuxtApp()\n```\n\n**Interview Tip:** Emphasize the execution mode distinction and the importance of `process.client` guards. Many bugs come from plugins assuming client environment.\n\n**Common Follow-up:** \"How do you create a plugin that depends on another plugin?\"\n\n**Real-world Example:** A Nuxt app uses `@vueuse\u002Fhead` (already integrated) and a custom analytics plugin. The analytics plugin needs to track page views. It uses a client-only plugin that listens to `nuxtApp.hook('page:finish')` to send analytics events. The server plugin is not needed because analytics don't run on server.",[243,354,355,356],"client-only","server-only","lifecycle","Emphasize the execution mode distinction and the importance of `process.client` guards. Many bugs come from plugins assuming client environment.","How do you create a plugin that depends on another plugin?","A Nuxt app uses `@vueuse\u002Fhead` (already integrated) and a custom analytics plugin. The analytics plugin needs to track page views. It uses a client-only plugin that listens to `nuxtApp.hook('page:finish')` to send analytics events. The server plugin is not needed because analytics don't run on server.",{"id":55,"category":170,"question":361,"answer":362,"level":323,"tags":363,"interviewTip":366,"commonFollowUp":367,"realWorldExample":368},"How do you create advanced composables in Nuxt that leverage SSR, async data, and auto-imports?","**Concept Explanation:** Advanced composables in Nuxt go beyond simple state encapsulation. They can integrate with Nuxt's SSR lifecycle, use `useAsyncData` or `useFetch` for data fetching, handle hydration, and be automatically imported from the `composables\u002F` directory. They can also accept options for caching, lazy loading, and server\u002Fclient execution control.\n\n**Internal Working:** Nuxt scans `composables\u002F` and generates auto-imports. When a composable uses `useAsyncData`, Nuxt's SSR system tracks the promise and ensures it resolves before sending HTML. The composable's return value is serialized and sent to client. On client, the composable reuses the serialized data.\n\n**Request Flow:** 1) Page uses `useProductList()` composable → 2) Composable calls `useAsyncData` → 3) SSR: fetch runs, data stored in payload → 4) Client: composable returns cached data, no re-fetch.\n\n**Lifecycle:** Composable runs in `setup()` context. If it uses `useAsyncData` with `server: true` (default), it runs on server and client (but client uses cached data).\n\n**Syntax & Code Example (advanced composable):**\n`composables\u002FuseProductList.ts`:\n```ts\nexport const useProductList = (category: string, options?: { lazy?: boolean }) => {\n  \u002F\u002F Reactive params\n  const route = useRoute()\n  const page = computed(() => parseInt(route.query.page as string) || 1)\n\n  const { data, pending, error, refresh } = useAsyncData(\n    `products-${category}-${page.value}`,\n    () => $fetch(`\u002Fapi\u002Fproducts\u002F${category}`, { params: { page: page.value } }),\n    {\n      lazy: options?.lazy || false,\n      watch: [page], \u002F\u002F refetch when page changes\n      transform: (data) => data.products \u002F\u002F reduce payload size\n    }\n  )\n\n  \u002F\u002F Helper methods\n  const nextPage = () => navigateTo({ query: { page: page.value + 1 } })\n  const prevPage = () => navigateTo({ query: { page: page.value - 1 } })\n\n  return { products: data, pending, error, refresh, nextPage, prevPage, page }\n}\n```\nUsage in page:\n```vue\n\u003Cscript setup>\nconst { products, pending, nextPage } = useProductList('electronics', { lazy: false })\n\u003C\u002Fscript>\n```\n\n**Practical Example:** A `useUserSession` composable that fetches user data, provides login\u002Flogout methods, and syncs with `useCookie` for persistence. It handles SSR by fetching user on server and hydrating on client.\n\n**Common Mistakes:** Creating composables that are not SSR-safe (using `localStorage` without guard). Not providing unique keys for `useAsyncData` – causes cache collisions. Overusing composables for simple logic; composables should encapsulate non-trivial reactive logic.\n\n**Edge Cases:** Composables that call other composables – auto-imports handle this recursively. However, circular dependencies between composables can break. Composables called outside of Nuxt context (e.g., in a plain `.ts` file) will not have access to Nuxt's lifecycle.\n\n**Interview Follow-ups:** \"How do you test a composable that uses useAsyncData?\" \"Can composables accept reactive parameters?\"\n\n**Best Practices:** Use `computed` or `watch` inside composables for reactivity. Always provide explicit `key` for `useAsyncData`. Use `transform` to reduce data size. Return a clean API (no internal refs unless needed). Add TypeScript generics for flexibility.\n\n**Performance Considerations:** Composables that fetch data on server should be efficient – avoid heavy computations that block rendering. Use `lazy: true` for non-critical data.\n\n**SEO Considerations:** Data fetched in composables with `server: true` is included in initial HTML, good for SEO.\n\n**Production Recommendations:** Group related composables in subdirectories (e.g., `composables\u002Fproducts\u002FuseProductList.ts`). Use `export default` for single-function composables, or named exports for multiple.\n\n**Latest Nuxt Patterns:** Nuxt 3 auto-imports `composables\u002F` subdirectories with prefixes. You can also create server-only composables in `composables\u002Fserver\u002F` (not auto-imported on client).\n\n**TypeScript Example:**\n```ts\n\u002F\u002F Generic composable\n export const useFetchData = \u003CT>(url: string, key?: string) => {\n  return useAsyncData\u003CT>(key || url, () => $fetch\u003CT>(url))\n}\n```\n\n**Interview Tip:** Emphasize that advanced composables can completely encapsulate complex features, making pages thin and declarative. This is a key pattern for large Nuxt apps.\n\n**Common Follow-up:** \"How do you share state between multiple composable instances?\" (Use `useState`)\n\n**Real-world Example:** An e-commerce app has a `useCart` composable that manages cart state (using `useState`), fetches cart items from API (`useFetch`), adds\u002Fremoves items, and syncs with `useCookie` for persistence. The composable is used in header (cart icon), product page (add to cart), and cart page (list items). It handles SSR by fetching cart on server (if user is logged in) and hydrating on client.",[174,364,365,27],"advanced","async-data","Emphasize that advanced composables can completely encapsulate complex features, making pages thin and declarative. This is a key pattern for large Nuxt apps.","How do you share state between multiple composable instances?","An e-commerce app has a `useCart` composable that manages cart state (using `useState`), fetches cart items from API (`useFetch`), adds\u002Fremoves items, and syncs with `useCookie` for persistence. The composable is used in header (cart icon), product page (add to cart), and cart page (list items). It handles SSR by fetching cart on server (if user is logged in) and hydrating on client.",{"id":66,"category":182,"question":370,"answer":371,"level":323,"tags":372,"interviewTip":376,"commonFollowUp":377,"realWorldExample":378},"How does useCookie work and when should you use it for state persistence?","**Concept Explanation:** `useCookie` is an SSR-friendly composable that reads and writes browser cookies. It provides a reactive reference that syncs with the cookie value. Unlike `useState` (which resets on page reload), `useCookie` persists data across page reloads and even across browser sessions (depending on cookie options). It's ideal for storing user preferences, authentication tokens, and other client-side persistent data.\n\n**Internal Working:** `useCookie` uses Vue's `ref` internally. When you read the value, it parses the cookie from the request headers (on server) or `document.cookie` (on client). When you set the value, it updates the cookie (via `document.cookie` on client, or via `set-cookie` header on server). During SSR, the cookie value is read from the incoming request, ensuring consistency.\n\n**Request Flow (SSR):** 1) Server receives request with cookies → 2) `useCookie('token')` reads from request headers → 3) Reactively bound to component → 4) HTML sent, including `set-cookie` if modified → 5) Client hydrates, reads from `document.cookie`.\n\n**Lifecycle:** Cookie is reactive – changing its value updates the cookie and triggers reactivity in components.\n\n**Syntax & Code Example:**\n```vue\n\u003Cscript setup>\nconst token = useCookie('token', {\n  maxAge: 60 * 60 * 24 * 7, \u002F\u002F 1 week\n  sameSite: 'strict',\n  secure: process.env.NODE_ENV === 'production',\n  httpOnly: false, \u002F\u002F allow client-side access\n  default: () => '' \u002F\u002F default value if cookie doesn't exist\n})\n\n\u002F\u002F Reactive usage\nconst login = async () => {\n  const { token: newToken } = await $fetch('\u002Fapi\u002Flogin')\n  token.value = newToken \u002F\u002F cookie is set automatically\n}\n\nconst logout = () => { token.value = null }\n\u003C\u002Fscript>\n```\n\n**Practical Example:** Store user's theme preference (dark\u002Flight mode). Read on server to render correct theme instantly, avoiding flash of wrong theme.\n\n**Common Mistakes:** Setting `httpOnly: true` – then client-side JavaScript cannot read the cookie, defeating the purpose of `useCookie`. Storing large data in cookies (max 4KB). Forgetting that cookies are sent with every request, affecting performance.\n\n**Edge Cases:** Cookies with `secure: true` are not sent over HTTP (only HTTPS). On the server, `useCookie` reads from the request; if the cookie is not present, it returns `null` or the default. Changes to the cookie on server require a response to set the cookie; for API routes, you must explicitly return the cookie header.\n\n**Interview Follow-ups:** \"How do you delete a cookie?\" \"Can useCookie be used in server API routes?\"\n\n**Best Practices:** Use `useCookie` for small, client-specific data (auth tokens, preferences, session IDs). For larger data, use `useState` + `localStorage` or a backend session. Always set appropriate `maxAge` or `expires`.\n\n**Performance Considerations:** Cookies are sent with every HTTP request, increasing bandwidth. Keep cookie size small. For frequent updates, consider using `localStorage` + `useState` to avoid network overhead.\n\n**SEO Considerations:** Not relevant.\n\n**Production Recommendations:** Use `secure: true` in production, `sameSite: 'lax'` or `'strict'` to prevent CSRF. For auth tokens, consider using `httpOnly: true` for security and expose a server API to read the token client-side (via `useCookie` with `httpOnly: false` is less secure).\n\n**Latest Nuxt Patterns:** Nuxt 3's `useCookie` supports `encode` and `decode` functions for custom serialization (e.g., storing objects). It also supports `watch` option to react to changes.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F Typed cookie\nconst userPref = useCookie\u003C{ theme: 'light' | 'dark'; language: string }>('pref', {\n  default: () => ({ theme: 'light', language: 'en' })\n})\n```\n\n**Interview Tip:** Emphasize the difference between `useState` (runtime, resets on reload) and `useCookie` (persistent across reloads). Many developers misuse `useState` for persistence.\n\n**Common Follow-up:** \"How do you sync useCookie with useRoute?\"\n\n**Real-world Example:** A multilingual site stores the user's language preference in a cookie using `useCookie('lang', { default: 'en' })`. The middleware reads this cookie and redirects to the appropriate language route if not set. On the language switcher, updating the cookie automatically updates the page via reactivity, and the cookie persists across visits.",[373,374,375,176],"usecookie","persistence","cookies","Emphasize the difference between `useState` (runtime, resets on reload) and `useCookie` (persistent across reloads). Many developers misuse `useState` for persistence.","How do you sync useCookie with useRoute?","A multilingual site stores the user's language preference in a cookie using `useCookie('lang', { default: 'en' })`. The middleware reads this cookie and redirects to the appropriate language route if not set. On the language switcher, updating the cookie automatically updates the page via reactivity, and the cookie persists across visits.",{"id":77,"category":100,"question":380,"answer":381,"level":323,"tags":382,"interviewTip":385,"commonFollowUp":386,"realWorldExample":387},"How do you use useRoute and useRouter effectively in Nuxt 3?","**Concept Explanation:** `useRoute` returns the current route object with reactive properties (`params`, `query`, `path`, `name`, `meta`, etc.). `useRouter` returns the Vue Router instance, allowing programmatic navigation (`push`, `replace`, `back`, `go`). Both are auto-imported composables that work during SSR and client-side navigation.\n\n**Internal Working:** `useRoute` is a reactive proxy to the current location. On the server, it gets the route from the incoming request URL; on the client, it syncs with Vue Router's state. `useRouter` provides methods that work both in SSR (for redirects via `navigateTo`) and client (SPA navigation).\n\n**Request Flow:** 1) User clicks a link or programmatic navigation → 2) `router.push()` updates URL → 3) Vue Router navigates (client-side) → 4) `useRoute` reactively updates components.\n\n**Lifecycle:** `useRoute` can be used in `setup()`, middleware, plugins, and composables. It's reactive; watch it with `watch` or `computed`.\n\n**Syntax & Code Example:**\n```vue\n\u003Cscript setup>\nconst route = useRoute()\nconst router = useRouter()\n\n\u002F\u002F Access params and query\nconst productId = route.params.id \u002F\u002F string | string[]\nconst page = route.query.page || 1\n\n\u002F\u002F Watch route changes\nwatch(() => route.params.id, (newId) => {\n  console.log('Product changed to', newId)\n})\n\n\u002F\u002F Programmatic navigation\nconst goToProduct = (id) => {\n  router.push({ path: `\u002Fproduct\u002F${id}`, query: { ref: 'homepage' } })\n}\n\n\u002F\u002F Replace current history entry\nrouter.replace({ name: 'index' })\n\n\u002F\u002F Navigate back\nrouter.back()\n\u003C\u002Fscript>\n```\n\n**Practical Example:** A product page that updates when the route `id` changes, fetching new product data using `useAsyncData` with `watch: [() => route.params.id]`.\n\n**Common Mistakes:** Mutating `route.params` directly (read-only). Using `route.params.id` without handling arrays (catch-all routes produce arrays). Forgetting that `useRoute()` inside a component only updates after navigation; if you need to react, use `watch`.\n\n**Edge Cases:** On server, `useRoute` is available but `router.push` will not cause actual navigation (use `navigateTo` from middleware or `definePageMeta` for redirects). In `setup`, `router.currentRoute` is not reactive – use `useRoute` instead.\n\n**Interview Follow-ups:** \"How do you preserve query parameters across navigations?\" \"What's the difference between router.push and navigateTo?\"\n\n**Best Practices:** Use `router.push` with named routes and params for type safety. Avoid using `router.push` in `setup` directly (use `onMounted` or event handlers). For redirects in middleware, prefer `navigateTo` over `router.push` because it works on server.\n\n**Performance Considerations:** `useRoute` is reactive and efficient. Avoid deep watching the entire route object; watch specific properties.\n\n**SEO Considerations:** `router.push` on client doesn't affect initial SSR; for redirects on server, use `navigateTo` in middleware to send proper HTTP redirect status.\n\n**Production Recommendations:** Use `router.beforeEach` in a plugin for global navigation guards, but Nuxt's middleware is usually sufficient.\n\n**Latest Nuxt Patterns:** Nuxt 3's `useRoute` and `useRouter` are typed automatically from your `pages\u002F` structure (if you use `pages\u002F`).\n\n**TypeScript Example:**\n```ts\n\u002F\u002F pages\u002Fproduct\u002F[id].vue\nconst route = useRoute()\nconst { id } = route.params as { id: string } \u002F\u002F cast after validation\n\u002F\u002F Or use route validation in definePageMeta\ndefinePageMeta({\n  validate: (route) => \u002F^[0-9]+$\u002F.test(route.params.id as string)\n})\n```\n\n**Interview Tip:** Emphasize that `useRoute` is reactive (unlike Vue Router's `$route` in Options API), which integrates seamlessly with `watch` and `computed`.\n\n**Common Follow-up:** \"How do you access route params in middleware?\"\n\n**Real-world Example:** A search page uses `useRoute().query.q` to read the search term and populate a search input. When the user submits a new search, `router.push({ query: { q: newTerm } })` updates the URL and the page automatically re-fetches results (with `watch: [() => route.query.q]` in `useAsyncData`). The URL is shareable and preserves search state.",[383,384,105,220],"useroute","userouter","Emphasize that `useRoute` is reactive (unlike Vue Router's `$route` in Options API), which integrates seamlessly with `watch` and `computed`.","How do you access route params in middleware?","A search page uses `useRoute().query.q` to read the search term and populate a search input. When the user submits a new search, `router.push({ query: { q: newTerm } })` updates the URL and the page automatically re-fetches results (with `watch: [() => route.query.q]` in `useAsyncData`). The URL is shareable and preserves search state.",{"id":89,"category":288,"question":389,"answer":390,"level":323,"tags":391,"interviewTip":394,"commonFollowUp":395,"realWorldExample":396},"How do you use useRequestHeaders for server-side SEO and API calls?","**Concept Explanation:** `useRequestHeaders` is a server-only composable (returns empty object on client) that gives you access to the incoming HTTP request headers. It's useful for forwarding headers to API calls (e.g., authentication, user-agent, accept-language) to maintain context between the client request and server-side API calls. For SEO, you can read headers like `user-agent` to customize rendering for crawlers.\n\n**Internal Working:** On the server, Nitro extracts headers from the incoming request and makes them available via `useRequestHeaders()`. On the client, it returns an empty object (or a proxy that warns). The composable is designed to be called during SSR, not client-side.\n\n**Request Flow:** 1) Browser sends request with headers (Cookie, Authorization, User-Agent) → 2) Nuxt server receives → 3) `useRequestHeaders()` called in component or composable → 4) Headers forwarded to external API via `$fetch` options → 5) API response used to render page.\n\n**Lifecycle:** Only available during SSR phase; on client, it's a no-op.\n\n**Syntax & Code Example:**\n```vue\n\u003Cscript setup>\n\u002F\u002F Get all headers\nconst headers = useRequestHeaders()\n\n\u002F\u002F Get specific headers\nconst userAgent = useRequestHeaders(['user-agent'])\n\n\u002F\u002F Forward headers to an API call\nconst { data } = await useFetch('https:\u002F\u002Fapi.example.com\u002Fprofile', {\n  headers: useRequestHeaders(['cookie', 'authorization'])\n})\n\u003C\u002Fscript>\n```\n\n**Practical Example (SEO):** Detect Googlebot user-agent and serve a simplified version of the page with only essential content, improving crawl efficiency.\n```vue\n\u003Cscript setup>\nconst userAgent = useRequestHeaders(['user-agent'])['user-agent']\nconst isBot = userAgent?.includes('Googlebot') || userAgent?.includes('bingbot')\nif (isBot) {\n  \u002F\u002F Load only SEO-critical data, skip heavy components\n}\n\u003C\u002Fscript>\n```\n\n**Common Mistakes:** Using `useRequestHeaders` on the client (it returns empty, causing silent failures). Forwarding all headers to external APIs (may expose sensitive headers like `host` or `connection`). Not handling missing headers (they may be undefined).\n\n**Edge Cases:** Headers like `cookie` can be large; forward only what's necessary. Some headers (e.g., `content-length`) should not be forwarded. On serverless platforms, certain headers may be stripped.\n\n**Interview Follow-ups:** \"How do you add a custom header to the response?\" \"Is useRequestHeaders safe for authentication?\"\n\n**Best Practices:** Use `useRequestHeaders` with an array of specific headers you need, not the whole object. For auth, forward only the `authorization` header or a specific token cookie. Combine with `useRuntimeConfig` to add API keys.\n\n**Performance Considerations:** Forwarding headers increases request size but is usually negligible. Avoid forwarding large headers like `cookie` if not needed.\n\n**SEO Considerations:** User-agent detection helps serve optimized content to crawlers, but be careful not to serve different content than users see (cloaking), which is against Google's guidelines.\n\n**Production Recommendations:** Set up logging to see which headers are available in your deployment environment. Use `event.node.req.headers` in Nitro event handlers for more control.\n\n**Latest Nuxt Patterns:** Nuxt 3's `useRequestHeaders` is built on top of `h3`'s `getRequestHeaders`. It can be used in server routes as well.\n\n**TypeScript Example:**\n```ts\nconst headers = useRequestHeaders(['x-api-key', 'authorization']) as {\n  'x-api-key'?: string\n  'authorization'?: string\n}\n```\n\n**Interview Tip:** Emphasize that `useRequestHeaders` is critical for building 'proxy' patterns where Nuxt acts as a BFF (Backend for Frontend), forwarding authentication headers to downstream APIs.\n\n**Common Follow-up:** \"How do you test components that use useRequestHeaders?\"\n\n**Real-world Example:** A Nuxt app calls an external CMS API that requires an API key and also respects the user's language preference via `Accept-Language` header. The component uses `useRequestHeaders(['accept-language'])` to forward the language header to the CMS, ensuring the user receives content in their preferred language, even when the page is server-rendered.",[392,27,393,257,26],"userequestheaders","headers","Emphasize that `useRequestHeaders` is critical for building 'proxy' patterns where Nuxt acts as a BFF (Backend for Frontend), forwarding authentication headers to downstream APIs.","How do you test components that use useRequestHeaders?","A Nuxt app calls an external CMS API that requires an API key and also respects the user's language preference via `Accept-Language` header. The component uses `useRequestHeaders(['accept-language'])` to forward the language header to the CMS, ensuring the user receives content in their preferred language, even when the page is server-rendered.",{"id":99,"category":276,"question":398,"answer":399,"level":323,"tags":400,"interviewTip":402,"commonFollowUp":403,"realWorldExample":404},"How do you access runtimeConfig in different parts of a Nuxt app (components, plugins, middleware, server routes)?","**Concept Explanation:** `useRuntimeConfig` is the composable to access runtime configuration. It can be used in components, composables, plugins, and middleware. In server routes (Nitro event handlers), you access config via `event.context.runtimeConfig` or the `useRuntimeConfig` helper. The behavior differs: client-side sees only `public` keys, server-side sees both `public` and private.\n\n**Internal Working:** During build, Nuxt inlines `public` config into the client bundle. Private config is kept on the server and injected via environment variables. Nitro automatically provides the config to event handlers.\n\n**Request Flow:** Not directly applicable – config is read at runtime.\n\n**Lifecycle:** Config is available as soon as the app initializes.\n\n**Syntax & Code Examples:**\n**In component\u002Fcomposable:**\n```vue\n\u003Cscript setup>\nconst config = useRuntimeConfig()\n\u002F\u002F config.public.apiBase is available\n\u002F\u002F config.somePrivateKey is undefined on client\n\u003C\u002Fscript>\n```\n**In plugin:**\n```ts\nexport default defineNuxtPlugin((nuxtApp) => {\n  const config = useRuntimeConfig()\n  \u002F\u002F use config\n})\n```\n**In middleware:**\n```ts\nexport default defineNuxtRouteMiddleware((to, from) => {\n  const config = useRuntimeConfig()\n  if (config.public.maintenanceMode) return navigateTo('\u002Fmaintenance')\n})\n```\n**In server route (Nitro):**\n```ts\n\u002F\u002F server\u002Fapi\u002Fsecret.ts\nexport default defineEventHandler((event) => {\n  const config = useRuntimeConfig(event) \u002F\u002F pass event\n  \u002F\u002F or event.context.runtimeConfig\n  const apiKey = config.apiSecret \u002F\u002F private key available\n  return { result: 'success' }\n})\n```\n\n**Practical Example:** A server API endpoint that uses a private Stripe secret key to create a payment intent, while the frontend uses the public Stripe publishable key.\n\n**Common Mistakes:** Trying to access private config on the client – it will be `undefined`. Not passing `event` to `useRuntimeConfig` in server routes (results in empty config). Forgetting that changes to `.env` require restarting the dev server.\n\n**Edge Cases:** In serverless environments, private config is read from environment variables on each invocation. If you change environment variables without redeploying, the new values are picked up.\n\n**Interview Follow-ups:** \"How do you make runtimeConfig reactive?\" \"Can you override runtimeConfig per request?\"\n\n**Best Practices:** Define default values in `nuxt.config.ts` to avoid undefined errors. Use descriptive names with `NUXT_` prefix. Never store secrets in `public`. For per-request configuration, use middleware or composables instead.\n\n**Performance Considerations:** Accessing config is fast – it's a plain object.\n\n**SEO Considerations:** Not relevant.\n\n**Production Recommendations:** Use environment-specific `.env` files and never commit them. Use your hosting platform's secret management for sensitive values.\n\n**Latest Nuxt Patterns:** Nuxt 3's `useRuntimeConfig` in server routes requires the `event` argument. The `$config` alias is deprecated.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F Extend type definitions\ndeclare module 'nuxt\u002Fschema' {\n  interface RuntimeConfig {\n    private: {\n      apiKey: string\n    }\n    public: {\n      apiBase: string\n    }\n  }\n}\n\u002F\u002F Now useRuntimeConfig() is typed\n```\n\n**Interview Tip:** Emphasize the difference between component\u002Fruntime access and server route access – the latter needs the `event` parameter. Many developers forget this.\n\n**Common Follow-up:** \"How do you expose runtimeConfig to the client for CSP?\"\n\n**Real-world Example:** A Nuxt app has a `runtimeConfig.public.sentryDsn` for client-side error tracking, and `runtimeConfig.private.emailServiceKey` for the server-side email API. The server API endpoint `server\u002Fapi\u002Fsend-email` uses the private key, while the frontend component initializes Sentry with the public DSN. This keeps the email key secure.",[344,280,256,401],"client","Emphasize the difference between component\u002Fruntime access and server route access – the latter needs the `event` parameter. Many developers forget this.","How do you expose runtimeConfig to the client for CSP?","A Nuxt app has a `runtimeConfig.public.sentryDsn` for client-side error tracking, and `runtimeConfig.private.emailServiceKey` for the server-side email API. The server API endpoint `server\u002Fapi\u002Fsend-email` uses the private key, while the frontend component initializes Sentry with the public DSN. This keeps the email key secure.",{"id":112,"category":406,"question":407,"answer":408,"level":323,"tags":409,"interviewTip":412,"commonFollowUp":413,"realWorldExample":414},"Authentication","How do you implement authentication flow in Nuxt 3, from login to protected routes?","**Concept Explanation:** Authentication in Nuxt 3 typically involves: a login page that submits credentials to a server API endpoint, server-side creation of a session token (JWT or cookie), storing the token in a secure cookie (httpOnly recommended), and protecting routes using middleware. Nuxt does not have a built-in auth module, but you can implement it manually or use community modules like `@sidebase\u002Fnuxt-auth`.\n\n**Internal Working:** 1) User submits login form → 2) Client sends POST to `\u002Fapi\u002Flogin` → 3) Server validates credentials, creates JWT\u002Fsession → 4) Server sets `Set-Cookie` header (httpOnly cookie) → 5) Client automatically includes cookie in subsequent requests → 6) Middleware checks cookie for protected routes → 7) On logout, server clears cookie.\n\n**Request Flow (SSR for protected page):** 1) Browser requests `\u002Fdashboard` with cookie → 2) Nuxt server receives, middleware reads cookie → 3) If valid, render page; if not, redirect to login (HTTP 302) → 4) Client receives HTML (or redirect).\n\n**Lifecycle:** Authentication state is typically stored in `useCookie` (for client access) and `useState` for reactivity. However, for httpOnly cookies, client cannot read token; instead, you can have an endpoint `\u002Fapi\u002Fuser` that returns user info.\n\n**Syntax & Code Example (manual JWT with httpOnly cookie):**\n`server\u002Fapi\u002Flogin.post.ts`:\n```ts\nexport default defineEventHandler(async (event) => {\n  const body = await readBody(event)\n  const user = await verifyCredentials(body.email, body.password)\n  const token = generateJWT(user)\n  setCookie(event, 'auth_token', token, {\n    httpOnly: true,\n    secure: process.env.NODE_ENV === 'production',\n    maxAge: 60 * 60 * 24 * 7,\n    path: '\u002F'\n  })\n  return { user: { id: user.id, email: user.email } }\n})\n```\n`middleware\u002Fauth.ts`:\n```ts\nexport default defineNuxtRouteMiddleware(async (to, from) => {\n  const { data: user } = await useFetch('\u002Fapi\u002Fuser') \u002F\u002F calls endpoint that reads cookie\n  if (!user.value) {\n    return navigateTo('\u002Flogin?redirect=' + to.fullPath)\n  }\n})\n```\n`server\u002Fapi\u002Fuser.get.ts`:\n```ts\nexport default defineEventHandler((event) => {\n  const token = getCookie(event, 'auth_token')\n  if (!token) return null\n  const user = verifyJWT(token)\n  return user\n})\n```\n\n**Practical Example:** A full authentication system with login, protected dashboard, logout, and redirect back to original page after login.\n\n**Common Mistakes:** Storing JWT in `localStorage` (vulnerable to XSS) – prefer httpOnly cookies. Not handling token expiration on server. Forgetting to set `secure: true` in production. Using client-side only checks (middleware runs on both server and client, but client check can be bypassed).\n\n**Edge Cases:** CSRF protection – use `sameSite: 'strict'` or `'lax'`. Token refresh logic – implement a refresh endpoint. Server-side rendering of authenticated content – cookie is available during SSR, so user data can be fetched and rendered.\n\n**Interview Follow-ups:** \"How do you handle token refresh?\" \"What's the difference between session-based and JWT-based auth?\"\n\n**Best Practices:** Use `@sidebase\u002Fnuxt-auth` module for production apps. Use httpOnly cookies for better security. Implement CSRF protection. Use `useFetch` with `credentials: 'include'` to send cookies.\n\n**Performance Considerations:** Each request to protected API will validate the token. Use fast JWT verification (synchronous). Cache user info in `useState` to avoid repeated `\u002Fapi\u002Fuser` calls.\n\n**SEO Considerations:** Protected pages should return 404 or redirect to login (302) for crawlers. Use `X-Robots-Tag: noindex` for private pages.\n\n**Production Recommendations:** Use HTTPS only. Set cookie `maxAge` appropriately. Implement rate limiting on login. Use a library like `jsonwebtoken` or `nuxt-auth-utils`.\n\n**Latest Nuxt Patterns:** Nuxt 3 has an official `nuxt-auth-utils` module that simplifies auth. Also, `@sidebase\u002Fnuxt-auth` supports multiple providers (local, OAuth).\n\n**TypeScript Example:**\n```ts\n\u002F\u002F middleware\u002Fauth.ts typed\nexport default defineNuxtRouteMiddleware(async (to) => {\n  const { data: user, error } = await useFetch\u003CUser>('\u002Fapi\u002Fuser')\n  if (error.value || !user.value) {\n    return navigateTo(`\u002Flogin?redirect=${to.fullPath}`)\n  }\n})\n```\n\n**Interview Tip:** Emphasize the security aspects – httpOnly cookies vs localStorage, and why middleware runs on both server and client (defense in depth).\n\n**Common Follow-up:** \"How do you implement OAuth (Google, GitHub) in Nuxt?\"\n\n**Real-world Example:** A SaaS platform uses `@sidebase\u002Fnuxt-auth` with a local provider. Users log in via email\u002Fpassword; the server returns a JWT in an httpOnly cookie. Protected routes have `definePageMeta({ middleware: 'auth' })`. The app also supports \"Remember Me\" by setting a longer `maxAge`. Session invalidation is done via a server endpoint that clears the cookie.",[233,410,411,375,231],"auth","jwt","Emphasize the security aspects – httpOnly cookies vs localStorage, and why middleware runs on both server and client (defense in depth).","How do you implement OAuth (Google, GitHub) in Nuxt?","A SaaS platform uses `@sidebase\u002Fnuxt-auth` with a local provider. Users log in via email\u002Fpassword; the server returns a JWT in an httpOnly cookie. Protected routes have `definePageMeta({ middleware: 'auth' })`. The app also supports \"Remember Me\" by setting a longer `maxAge`. Session invalidation is done via a server endpoint that clears the cookie.",{"id":122,"category":182,"question":416,"answer":417,"level":323,"tags":418,"interviewTip":422,"commonFollowUp":423,"realWorldExample":424},"How do you integrate Pinia with Nuxt 3 for advanced state management?","**Concept Explanation:** Pinia is the official Vue store library, replacing Vuex. Nuxt 3 has first-class support for Pinia via the `@pinia\u002Fnuxt` module. Pinia provides global stores with reactivity, DevTools support, and SSR compatibility. In Nuxt, Pinia stores are automatically reset per request on the server to avoid cross-request state leaks, and they hydrate on the client.\n\n**Internal Working:** The `@pinia\u002Fnuxt` module registers a plugin that creates a Pinia instance and provides it to the Nuxt app. On the server, a new Pinia store is created for each request. Store state is serialized and sent in the HTML payload (like `useState`). On the client, the state is rehydrated. Pinia's `store.$reset()` is called automatically between SSR requests.\n\n**Request Flow (SSR):** 1) Request arrives → 2) Pinia plugin creates new store instance → 3) Page component calls `useStore()` → 4) Store actions fetch data (during SSR) → 5) State serialized into HTML → 6) Client hydrates, reusing state.\n\n**Lifecycle:** Stores can be used in components, composables, plugins, and middleware. Actions can be async and work with SSR.\n\n**Syntax & Code Example:**\nInstallation:\n```bash\nnpm install @pinia\u002Fnuxt\n```\n`nuxt.config.ts`:\n```ts\nexport default defineNuxtConfig({\n  modules: ['@pinia\u002Fnuxt']\n})\n```\nStore definition (`stores\u002Fcounter.ts`):\n```ts\nexport const useCounterStore = defineStore('counter', {\n  state: () => ({ count: 0 }),\n  actions: {\n    increment() { this.count++ },\n    async fetchInitial() {\n      const data = await $fetch('\u002Fapi\u002Fcount')\n      this.count = data.count\n    }\n  },\n  getters: {\n    double: (state) => state.count * 2\n  }\n})\n```\nUsage in component:\n```vue\n\u003Cscript setup>\nconst counter = useCounterStore()\n\u002F\u002F Call async action during SSR\nawait counter.fetchInitial()\n\u003C\u002Fscript>\n\u003Ctemplate>\n  \u003Cdiv>{{ counter.count }} (double: {{ counter.double }})\u003C\u002Fdiv>\n  \u003Cbutton @click=\"counter.increment\">+\u003C\u002Fbutton>\n\u003C\u002Ftemplate>\n```\n\n**Practical Example:** A shopping cart store that persists in localStorage (via Pinia persistence plugin) and syncs with the server. The store handles adding items, removing, and calculating totals.\n\n**Common Mistakes:** Using Pinia without the module (manually `app.use(pinia)`) – breaks SSR. Not calling `await` on async actions in `setup` – SSR won't wait for them. Using `localStorage` directly in store without checking `process.client` – breaks SSR.\n\n**Edge Cases:** Pinia stores with `useAsyncData` can be combined: fetch data in `useAsyncData` and commit to store. Pinia's `$subscribe` works on client but not during SSR. For cross-request state isolation, never use global variables outside Pinia.\n\n**Interview Follow-ups:** \"How do you reset a Pinia store on logout?\" \"Can you use Pinia with useState?\"\n\n**Best Practices:** Use Pinia for complex state that needs actions, getters, and cross-component sharing. For simple shared state, `useState` is sufficient. Use `store.$reset()` for logout. Use Pinia plugins for persistence, devtools.\n\n**Performance Considerations:** Pinia is efficient; but avoid storing large collections in state without normalization. Use `computed` getters rather than deriving data in components.\n\n**SEO Considerations:** Data fetched in store actions during SSR is included in HTML, good for SEO.\n\n**Production Recommendations:** Use `@pinia\u002Fnuxt` module. Enable `pinia.autoImports` to auto-import stores from `stores\u002F` folder. Set `pinia.disableVuexDevtools` in production for performance.\n\n**Latest Nuxt Patterns:** `@pinia\u002Fnuxt` v0.4+ supports Nuxt 3. Stores can be defined with Composition API (`defineStore('id', () => { ... })`) which offers better TypeScript inference.\n\n**TypeScript Example (Composition API store):**\n```ts\nexport const useUserStore = defineStore('user', () => {\n  const user = ref\u003CUser | null>(null)\n  const login = async (email: string, password: string) => {\n    user.value = await $fetch('\u002Fapi\u002Flogin', { method: 'POST', body: { email, password } })\n  }\n  return { user, login }\n})\n```\n\n**Interview Tip:** Emphasize that `@pinia\u002Fnuxt` automatically handles SSR state serialization, which was a pain with Vuex. This is Pinia's killer feature in Nuxt.\n\n**Common Follow-up:** \"How does Pinia compare to useState for state management?\"\n\n**Real-world Example:** A flight booking app uses Pinia to manage search criteria (departure, destination, dates, passengers), flight results cache, and booking cart. The store provides actions to search flights (calling API), update criteria, and manage selections. The same store is used across multiple pages (search form, results page, passenger details) ensuring consistency. SSR ensures that search results are rendered on the server for SEO and fast initial load.",[419,176,420,27,421],"pinia","store","module","Emphasize that `@pinia\u002Fnuxt` automatically handles SSR state serialization, which was a pain with Vuex. This is Pinia's killer feature in Nuxt.","How does Pinia compare to useState for state management?","A flight booking app uses Pinia to manage search criteria (departure, destination, dates, passengers), flight results cache, and booking cart. The store provides actions to search flights (calling API), update criteria, and manage selections. The same store is used across multiple pages (search form, results page, passenger details) ensuring consistency. SSR ensures that search results are rendered on the server for SEO and fast initial load.",{"id":132,"category":426,"question":427,"answer":428,"level":323,"tags":429,"interviewTip":434,"commonFollowUp":435,"realWorldExample":436},"Performance","What are lazy loading and dynamic imports in Nuxt, and how do you use them to optimize performance?","**Concept Explanation:** Lazy loading in Nuxt refers to deferring the loading of JavaScript for components or pages until they are needed. Dynamic imports allow you to import modules or components asynchronously, reducing the initial bundle size. Nuxt automatically code-splits pages, but you can also lazy load components, composables, and even libraries using `defineAsyncComponent` or dynamic `import()`.\n\n**Internal Working:** When you use `defineAsyncComponent` or `import()` with `v-if`, Nuxt (via Vite\u002FWebpack) creates a separate chunk for that component. The chunk is loaded only when the component is rendered. On the server, async components are rendered synchronously (no lazy loading), but on the client, the component can be loaded on demand.\n\n**Request Flow (client):** 1) Initial page loads without heavy component → 2) User triggers condition (e.g., clicks a button) → 3) Dynamic import fetches chunk → 4) Component renders.\n\n**Lifecycle:** Async components are loaded at runtime when needed, not during initial page load.\n\n**Syntax & Code Examples:**\n**Lazy loading a component (auto-imported):**\n```vue\n\u003Ctemplate>\n  \u003Cdiv>\n    \u003Cbutton @click=\"show = true\">Show Chart\u003C\u002Fbutton>\n    \u003CLazyChart v-if=\"show\" \u002F>\n  \u003C\u002Fdiv>\n\u003C\u002Ftemplate>\n```\n`components\u002FChart.vue` will be lazy-loaded because of the `Lazy` prefix.\n\n**Manual dynamic import:**\n```vue\n\u003Cscript setup>\nconst Chart = defineAsyncComponent(() => import('~\u002Fcomponents\u002FChart.vue'))\nconst show = ref(false)\n\u003C\u002Fscript>\n\u003Ctemplate>\n  \u003Cbutton @click=\"show = true\">Show\u003C\u002Fbutton>\n  \u003CChart v-if=\"show\" \u002F>\n\u003C\u002Ftemplate>\n```\n\n**Lazy loading a composable:**\n```ts\nconst { heavyFunction } = await import('~\u002Fcomposables\u002Fheavy')\nheavyFunction()\n```\n\n**Lazy loading a library:**\n```ts\nconst { default: moment } = await import('moment')\nconst formatted = moment().format()\n```\n\n**Practical Example:** A dashboard page with a heavy chart library (e.g., Chart.js). Lazy load the chart component so it only loads when the user scrolls to that section or clicks a tab.\n\n**Common Mistakes:** Using lazy loading for above-the-fold content – increases perceived latency. Forgetting to handle loading states (the component will appear blank until loaded). Overusing lazy loading (too many chunks, more HTTP requests).\n\n**Edge Cases:** Lazy components are not rendered on server if they are conditionally shown with `v-if` (they are simply skipped). For SEO-critical components, avoid lazy loading. Lazy components can be preloaded manually using `preloadComponents`.\n\n**Interview Follow-ups:** \"How does Nuxt's Lazy prefix differ from defineAsyncComponent?\" \"What is preloading and how is it different from lazy loading?\"\n\n**Best Practices:** Use lazy loading for components below the fold, for modal dialogs, for charts, for third-party widgets. Use `Lazy` prefix for simplicity. Provide a loading indicator skeleton. Use `prefetch` for likely-needed components.\n\n**Performance Considerations:** Lazy loading reduces initial bundle size and improves Time to Interactive (TTI). However, each lazy chunk adds an HTTP request; balance chunk size (not too small). Use `vite.build.rollupOptions.output.manualChunks` for fine control.\n\n**SEO Considerations:** Lazy loading does not affect SEO for client-side only components. For server-rendered content, lazy components that are rendered conditionally may not appear in initial HTML if condition is false during SSR.\n\n**Production Recommendations:** Analyze bundle with `nuxi analyze`. Lazy load any component not visible on initial paint. Use `preloadComponents` for components likely to be needed soon. Set `components: { dirs: [{ path: '~\u002Fcomponents', isAsync: true }] }` to lazy load all components by default? Not recommended.\n\n**Latest Nuxt Patterns:** Nuxt 3's `Lazy` prefix works out of the box. Also supports `defineNuxtComponent` for async components with SSR support.\n\n**TypeScript Example:**\n```ts\nconst HeavyComponent = defineAsyncComponent(\n  () => import('~\u002Fcomponents\u002FHeavy.vue')\n)\n```\n\n**Interview Tip:** Emphasize that lazy loading is not just for components – you can lazy load composables, utils, and libraries. This is often overlooked.\n\n**Common Follow-up:** \"How do you lazy load a page in Nuxt? (Pages are automatically code-split; you don't need to do anything.)\"\n\n**Real-world Example:** A reporting dashboard with 10 different chart types. Only the first chart is visible initially; others are in tabs. Using `LazyChart` for each tab reduces initial bundle from 2MB to 400KB, cutting load time by 60%. When the user clicks another tab, that chart loads on demand.",[430,431,432,433],"lazy-loading","dynamic-imports","performance","async-components","Emphasize that lazy loading is not just for components – you can lazy load composables, utils, and libraries. This is often overlooked.","How do you lazy load a page in Nuxt? (Pages are automatically code-split; you don't need to do anything.)","A reporting dashboard with 10 different chart types. Only the first chart is visible initially; others are in tabs. Using `LazyChart` for each tab reduces initial bundle from 2MB to 400KB, cutting load time by 60%. When the user clicks another tab, that chart loads on demand.",{"id":145,"category":100,"question":438,"answer":439,"level":323,"tags":440,"interviewTip":445,"commonFollowUp":446,"realWorldExample":447},"What are route rules in Nuxt and how can you use them for hybrid caching and redirects?","**Concept Explanation:** Route rules in Nuxt (`routeRules` in `nuxt.config.ts`) allow you to define per-route behavior for rendering mode (SSR\u002FCSR\u002FSSG), caching, redirects, CORS, and headers. They are a powerful feature of Nitro that enables hybrid rendering and fine-grained control without writing custom server code.\n\n**Internal Working:** Nitro reads `routeRules` at build time and generates a route matcher. At request time, it matches the incoming URL against the defined patterns and applies the associated rules. For static prerendering, rules with `static: true` will pre-render those routes. For redirects, Nitro sends a 3xx response. For caching, it sets appropriate `Cache-Control` headers.\n\n**Request Flow:** 1) Request for `\u002Fapi\u002Fdata` → 2) Nitro matches rule `\u002Fapi\u002F**` → 3) Applies `cors: true` and headers → 4) If `redirect` exists, sends redirect → 5) Else processes request normally.\n\n**Lifecycle:** Rules are applied at the Nitro routing layer, before any Nuxt middleware or page rendering.\n\n**Syntax & Code Example:**\n```ts\nexport default defineNuxtConfig({\n  routeRules: {\n    \u002F\u002F Static page (pre-rendered at build time)\n    '\u002Fabout': { static: true },\n    \n    \u002F\u002F SSR with caching\n    '\u002Fproducts\u002F**': { ssr: true, swr: 3600 }, \u002F\u002F cache for 1 hour\n    \n    \u002F\u002F Client-side rendering (SPA)\n    '\u002Fadmin\u002F**': { ssr: false },\n    \n    \u002F\u002F Redirect\n    '\u002Fold-blog': { redirect: '\u002Fblog' },\n    '\u002Fold\u002F*': { redirect: '\u002Fnew\u002F:path*' },\n    \n    \u002F\u002F Add CORS headers to API\n    '\u002Fapi\u002F**': { cors: true, headers: { 'X-Custom': 'value' } },\n    \n    \u002F\u002F Custom cache header\n    '\u002Fstatic\u002F**': { headers: { 'Cache-Control': 'max-age=86400' } }\n  }\n})\n```\n\n**Practical Example:** A blog site: home page SSR (dynamic), blog posts pre-rendered as static (SSG), admin area as SPA, API endpoints with CORS, and redirects for legacy URLs.\n\n**Common Mistakes:** Overlapping rules – first match wins; order in object does not guarantee order (use specificity). Forgetting that `static: true` prerenders at build time; dynamic data will be stale. Using `swr` without understanding that it serves stale content while revalidating in background.\n\n**Edge Cases:** `swr: 0` means no caching. `swr` works only on server-side routes (not API routes by default, but you can apply). `redirect` can use named parameters with `:path*`. Route rules do not affect client-side navigation (they are server-side).\n\n**Interview Follow-ups:** \"How do route rules differ from middleware?\" \"What is SWR and when would you use it?\"\n\n**Best Practices:** Use route rules for SEO-critical caching (`swr` for news sites). Use redirects instead of middleware for permanent redirects (better performance). Use `static: true` for pages that rarely change.\n\n**Performance Considerations:** `swr` dramatically reduces server load by serving cached content. `static: true` eliminates server compute entirely. Use `cors` to avoid preflight requests for same-origin APIs.\n\n**SEO Considerations:** `swr` may serve stale content, but search engines see the cached version; revalidation ensures updated content eventually. Redirects via route rules return proper HTTP status codes (301\u002F302).\n\n**Production Recommendations:** Combine route rules with CDN caching. For user-specific pages, avoid `swr` (except for public parts). Monitor cache hit rates.\n\n**Latest Nuxt Patterns:** Nuxt 3 supports `isr: true` (Incremental Static Regeneration) via `routeRules` with `isr` key. Also supports `swr` with custom TTL.\n\n**TypeScript Example:**\n```ts\nrouteRules: {\n  '\u002Fapi\u002F**': { cors: true } satisfies NitroRouteConfig\n}\n```\n\n**Interview Tip:** Emphasize that route rules are declarative and more efficient than custom server middleware for common tasks like caching, redirects, and CORS.\n\n**Common Follow-up:** \"How do you test route rules locally?\"\n\n**Real-world Example:** A news website uses `routeRules` to cache the homepage (`\u002F`) with `swr: 60` (serve cached for 60 seconds, revalidate in background). Category pages are static (`static: true`) and rebuilt daily. Old article URLs are redirected to new structure (`\u002Fold\u002F:id` → `\u002Farticles\u002F:id`). API endpoints get CORS headers for third-party access. This config reduced server costs by 80% and improved response times.",[441,442,443,93,444],"routerules","caching","redirects","swr","Emphasize that route rules are declarative and more efficient than custom server middleware for common tasks like caching, redirects, and CORS.","How do you test route rules locally?","A news website uses `routeRules` to cache the homepage (`\u002F`) with `swr: 60` (serve cached for 60 seconds, revalidate in background). Category pages are static (`static: true`) and rebuilt daily. Old article URLs are redirected to new structure (`\u002Fold\u002F:id` → `\u002Farticles\u002F:id`). API endpoints get CORS headers for third-party access. This config reduced server costs by 80% and improved response times.",{"id":157,"category":449,"question":450,"answer":451,"level":323,"tags":452,"interviewTip":457,"commonFollowUp":458,"realWorldExample":459},"Optimization","How do you implement image optimization in Nuxt using @nuxt\u002Fimage?","**Concept Explanation:** `@nuxt\u002Fimage` is a module that provides automatic image optimization: resizing, format conversion (WebP\u002FAVIF), lazy loading, and responsive images. It generates multiple sizes and serves the most appropriate image based on device viewport and supported formats. It integrates with various providers (Cloudinary, Imgix, IPX – built-in, or static generation).\n\n**Internal Working:** The module replaces `\u003Cimg>` tags with `\u003CNuxtImg>` or `\u003CNuxtPicture>`. At build time or runtime, it generates optimized images (using IPX, a Nitro-based image optimizer) and serves them with proper caching headers. For static sites, it can pre-generate images. For external providers, it delegates to their APIs.\n\n**Request Flow:** 1) Browser requests page → 2) HTML contains `\u003Cimg src=\"\u002F_ipx\u002Fw_200\u002Fimage.jpg\">` → 3) Nitro server (or provider) processes image on the fly (resize, format) → 4) Returns optimized image → 5) Browser caches it.\n\n**Lifecycle:** Images can be optimized at build time (static) or on-demand (SSR).\n\n**Syntax & Code Example:**\nInstallation:\n```bash\nnpm install @nuxt\u002Fimage\n```\n`nuxt.config.ts`:\n```ts\nexport default defineNuxtConfig({\n  modules: ['@nuxt\u002Fimage'],\n  image: {\n    domains: ['example.com'], \u002F\u002F external domains allowed\n    screens: { xs: 320, sm: 640, md: 768, lg: 1024, xl: 1280 },\n    ipx: { maxAge: 60 * 60 * 24 * 30 } \u002F\u002F cache IPX responses\n  }\n})\n```\nUsage in component:\n```vue\n\u003Ctemplate>\n  \u003C!-- Simple optimized image -->\n  \u003CNuxtImg src=\"\u002Fimages\u002Fhero.jpg\" width=\"800\" height=\"400\" format=\"webp\" quality=\"80\" \u002F>\n  \n  \u003C!-- Responsive picture with art direction -->\n  \u003CNuxtPicture\n    :src=\"imageUrl\"\n    :sizes=\"{ xs: 320, sm: 640, md: 1024 }\"\n    format=\"webp\"\n    densities=\"1x, 2x\"\n  \u002F>\n  \n  \u003C!-- Lazy loading -->\n  \u003CNuxtImg src=\"\u002Fimages\u002Fcarousel1.jpg\" loading=\"lazy\" \u002F>\n\u003C\u002Ftemplate>\n```\n\n**Practical Example:** A product gallery with thumbnails that, when clicked, show a high-resolution image. Use `NuxtImg` for thumbnails (small size, lazy loading) and `NuxtPicture` for the main image with responsive sizes.\n\n**Common Mistakes:** Not configuring `domains` for external images (results in 404). Using `NuxtImg` without `width` and `height` (causes layout shift). Over-optimizing (too many sizes generated) increases build time.\n\n**Edge Cases:** For dynamic image URLs (e.g., from CMS), ensure they are absolute URLs and domain is whitelisted. Static generation: use `image: { staticFilename: '[publicPath]\u002F[name]-[width][hash][ext]' }`. For provider like Cloudinary, set `image.cloudinary` config.\n\n**Interview Follow-ups:** \"How does @nuxt\u002Fimage handle different screen resolutions?\" \"What is the difference between NuxtImg and NuxtPicture?\"\n\n**Best Practices:** Always provide `width` and `height` to prevent CLS. Use `format=\"webp\"` (or `auto` to serve WebP when supported). Use `lazyLoading` for offscreen images. Preload critical images with `preload` prop.\n\n**Performance Considerations:** `@nuxt\u002Fimage` drastically improves LCP (Largest Contentful Paint) by serving appropriately sized images. On-demand optimization adds CPU overhead; consider pre-generating images for static sites.\n\n**SEO Considerations:** Proper `alt` attributes are still required. Optimized images improve page speed, a ranking factor. Use `NuxtPicture` with `fallback` for older browsers.\n\n**Production Recommendations:** Use a CDN in front of IPX or use a provider (Cloudinary) for edge optimization. Set appropriate cache headers. For high-traffic sites, pre-generate images at build time.\n\n**Latest Nuxt Patterns:** `@nuxt\u002Fimage` v1.0+ supports Nuxt 3. It integrates with Nuxt's Nitro server via IPX. You can also use `@nuxt\u002Fimage-edge` for edge optimization.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F NuxtImg accepts all img attributes\n\u003CNuxtImg src=\"\u002Fimage.jpg\" :width=\"200\" :height=\"100\" alt=\"Description\" \u002F>\n```\n\n**Interview Tip:** Emphasize that image optimization is often overlooked but critical for Core Web Vitals. `@nuxt\u002Fimage` is the standard solution in Nuxt ecosystem.\n\n**Common Follow-up:** \"How do you generate responsive images for a static site?\"\n\n**Real-world Example:** An e-commerce site with 10,000 product images. Using `@nuxt\u002Fimage` with IPX, they serve WebP images sized to the user's viewport. The homepage hero image uses `preload` and `fetchpriority=\"high\"`. Product gallery images use `lazyLoading` and `sizes` to deliver only needed resolutions. This improved LCP from 3.5s to 1.2s and increased conversions by 15%.",[453,454,455,432,456],"image","optimization","nuxt-image","webp","Emphasize that image optimization is often overlooked but critical for Core Web Vitals. `@nuxt\u002Fimage` is the standard solution in Nuxt ecosystem.","How do you generate responsive images for a static site?","An e-commerce site with 10,000 product images. Using `@nuxt\u002Fimage` with IPX, they serve WebP images sized to the user's viewport. The homepage hero image uses `preload` and `fetchpriority=\"high\"`. Product gallery images use `lazyLoading` and `sizes` to deliver only needed resolutions. This improved LCP from 3.5s to 1.2s and increased conversions by 15%.",{"id":169,"category":193,"question":461,"answer":462,"level":323,"tags":463,"interviewTip":465,"commonFollowUp":466,"realWorldExample":467},"What are the different data fetching strategies in Nuxt (server-only, client-only, SWR, polling) and when to use each?","**Concept Explanation:** Nuxt provides multiple data fetching strategies: server-only (fetch during SSR, not on client), client-only (fetch after hydration), SWR (stale-while-revalidate – serve cached data, revalidate in background), and polling (periodic refetch). You control these via options in `useFetch` \u002F `useAsyncData` (`server`, `lazy`, `immediate`, `watch`, and `refresh`).\n\n**Internal Working:** `server: true` (default) means fetch runs on server and client (client uses cached payload). `server: false` skips server fetch, runs only on client. `lazy: true` doesn't block navigation, returns `pending=true` initially. `refresh` can be called manually for polling. SWR-like behavior can be achieved with `useFetch` + `refresh` on interval or using route rules with `swr`.\n\n**Request Flow (Server-only):** 1) SSR runs fetch, data included in HTML → 2) Client reuses data, no second fetch. **Client-only:** 1) SSR skips fetch → 2) Client hydrates, then fetch runs → 3) Data appears after load. **SWR:** 1) Cache hit returns stale data immediately → 2) Background revalidation updates cache → 3) Component re-renders with fresh data.\n\n**Lifecycle:** Server-only data is ready on initial load; client-only data shows after hydration (may cause layout shift).\n\n**Syntax & Code Example:**\n```vue\n\u003Cscript setup>\n\u002F\u002F Server-only (default) – best for SEO\nconst { data: seoContent } = await useFetch('\u002Fapi\u002Fseo')\n\n\u002F\u002F Client-only – for user-specific data\nconst { data: userPrefs } = await useFetch('\u002Fapi\u002Fpreferences', { server: false })\n\n\u002F\u002F Lazy (non-blocking)\nconst { data: comments, pending } = await useFetch('\u002Fapi\u002Fcomments', { lazy: true })\n\n\u002F\u002F Polling – refresh every 30 seconds\nconst { data: liveData, refresh } = await useFetch('\u002Fapi\u002Flive-stats', {\n  server: false, \u002F\u002F or true, but polling on client\n})\nconst interval = setInterval(() => refresh(), 30000)\nonUnmounted(() => clearInterval(interval))\n\n\u002F\u002F SWR via useAsyncData with key (cached)\nconst { data: products } = await useAsyncData('products', () => $fetch('\u002Fapi\u002Fproducts'), {\n  \u002F\u002F SWR-like: use cache if exists, but not built-in; implement with useCookie\n})\n\u003C\u002Fscript>\n```\n\n**Practical Example:** A dashboard: user profile data (server-only for SEO), real-time stock ticker (client-only polling every 5 seconds), comments section (lazy load after page render).\n\n**Common Mistakes:** Using `server: false` for SEO-critical data (crawlers won't see it). Polling without cleanup (memory leak). Not handling `pending` state for lazy data (causes UI jump).\n\n**Edge Cases:** `server: false` data will not be included in HTML, but if you also use `lazy: false` (default), the fetch will run immediately after hydration, potentially delaying interactivity. Use `lazy: true` to defer.\n\n**Interview Follow-ups:** \"How do you implement optimistic UI with useFetch?\" \"What's the difference between useFetch with server: false and using $fetch in onMounted?\"\n\n**Best Practices:** Default to `server: true` for public content. Use `server: false` for private user data (reduces server load). Use `lazy` + skeleton loaders for non-critical content. For real-time data, use `refresh` on interval or WebSockets.\n\n**Performance Considerations:** Server-only reduces client requests but increases server load. Client-only shifts load to client, better for low-traffic internal tools. Polling impacts network and battery; use longer intervals.\n\n**SEO Considerations:** Server-only ensures crawlers see content. Client-only data is invisible to crawlers unless you pre-render or use dynamic rendering.\n\n**Production Recommendations:** For pages with both critical and non-critical data, use multiple `useFetch` calls with different `server` settings. For real-time features, consider WebSockets or Server-Sent Events instead of polling.\n\n**Latest Nuxt Patterns:** `useFetch` with `watch` can implement reactive refetching. Use `refreshNuxtData` to manually invalidate cache across components.\n\n**TypeScript Example:**\n```ts\nconst { data, pending, refresh } = await useFetch\u003CStockData>('\u002Fapi\u002Fstocks', {\n  server: false,\n  lazy: true\n})\n```\n\n**Interview Tip:** Emphasize that choosing the right strategy is a trade-off between SEO, server load, and user experience. Interviewers often ask for scenarios.\n\n**Common Follow-up:** \"How do you cache data across pages?\" (Use `useState` with key or Pinia)\n\n**Real-world Example:** A weather app: The main city weather is server-only (SEO for city name). Hourly forecast is lazy-loaded after page render. Severe weather alerts are polled every minute. User's saved locations are client-only (requires login). This strategy balances SEO, performance, and real-time needs.",[198,27,70,464,444],"polling","Emphasize that choosing the right strategy is a trade-off between SEO, server load, and user experience. Interviewers often ask for scenarios.","How do you cache data across pages?","A weather app: The main city weather is server-only (SEO for city name). Hourly forecast is lazy-loaded after page render. Severe weather alerts are polled every minute. User's saved locations are client-only (requires login). This strategy balances SEO, performance, and real-time needs.",{"id":181,"category":469,"question":470,"answer":471,"level":323,"tags":472,"interviewTip":476,"commonFollowUp":477,"realWorldExample":478},"Hydration","What is hydration in Nuxt and what are common hydration mismatch errors? How do you debug and fix them?","**Concept Explanation:** Hydration is the process where Vue takes over the static HTML sent by the server and makes it interactive, attaching event listeners and setting up reactivity. A hydration mismatch occurs when the client-side rendered virtual DOM does not match the server-rendered HTML. This causes Vue to discard the server HTML and re-render, hurting performance and potentially causing UI flicker.\n\n**Internal Working:** During SSR, Vue renders the component tree to HTML. On the client, Vue creates a new VDOM and compares it to the existing DOM. If they differ at any point, Vue throws a warning (in development) and replaces the mismatched part with client-rendered content. This process is expensive.\n\n**Common Causes of Mismatch:** Using browser-only APIs (`window`, `localStorage`, `Date.now()`) during SSR; rendering different content based on `process.client` without a fallback; random IDs (e.g., `Math.random()`, `uuid`); using `v-if` with client-only data; third-party components that generate different HTML on server\u002Fclient.\n\n**Debugging:** Look for `[Vue warn] Hydration node mismatch` in browser console. The warning often includes the surrounding HTML. Use `vue-devtools` to inspect the component tree. Temporarily disable SSR for that component using `\u003CClientOnly>`.\n\n**Solution Examples:**\n```vue\n\u003Cscript setup>\n\u002F\u002F Bad: using Date.now() during SSR\nconst timestamp = Date.now()\n\n\u002F\u002F Good: defer to client\nconst timestamp = process.client ? Date.now() : null\n\u003C\u002Fscript>\n\u003Ctemplate>\n  \u003Cdiv>{{ timestamp ?? 'Loading...' }}\u003C\u002Fdiv>\n\u003C\u002Ftemplate>\n\n\u002F\u002F Using ClientOnly component\n\u003Ctemplate>\n  \u003CClientOnly>\n    \u003CComponentThatUsesWindow \u002F>\n    \u003Ctemplate #fallback>\n      \u003Cdiv>Loading...\u003C\u002Fdiv>\n    \u003C\u002Ftemplate>\n  \u003C\u002FClientOnly>\n\u003C\u002Ftemplate>\n```\n\n**Practical Example:** A component that displays the current user's local time. On server, it has no timezone; on client, it shows the time. This causes mismatch. Solution: use `ClientOnly` or render only on client with `process.client` check.\n\n**Common Mistakes:** Using `Math.random()` for keys; using `v-if` with `v-for` where order may differ; using `useRoute().query` without default values (query may be missing on server if not passed).\n\n**Edge Cases:** Third-party libraries that manipulate the DOM directly (e.g., some carousels) can cause mismatches. Use `client-only` plugin for those. Also, `useAsyncData` with `server: false` will not run on server, but the component still renders without data, causing mismatch if the data is needed for the template.\n\n**Interview Follow-ups:** \"What happens after a hydration mismatch?\" \"How do you force a component to only render on client?\"\n\n**Best Practices:** Avoid browser-specific APIs in `setup` or templates. Use `onMounted` for client-only initialization. Use `ClientOnly` wrapper as last resort. Provide fallback content during SSR. Use `v-if` with `process.client` only for non-critical parts.\n\n**Performance Considerations:** Hydration mismatches cause Vue to throw away server-rendered HTML and re-render from scratch, negating SSR benefits. Always fix them.\n\n**SEO Considerations:** Mismatches do not affect SEO directly (since server HTML is still sent), but the flicker may affect user experience.\n\n**Production Recommendations:** Enable hydration mismatch warnings in development only. In production, Vue suppresses them but still re-renders. Use `@vue\u002Fserver-renderer` with `shouldPreventMismatch`? Not needed. Use `Nuxt` built-in hydration checks.\n\n**Latest Nuxt Patterns:** Nuxt 3 has improved hydration error messages. You can also use `ssr: false` on specific pages or components to bypass SSR entirely.\n\n**TypeScript Example:** Not applicable.\n\n**Interview Tip:** Emphasize that hydration mismatches are a common pain point in SSR frameworks. Demonstrating systematic debugging shows experience.\n\n**Common Follow-up:** \"How do you conditionally render a component on client only without layout shift?\"\n\n**Real-world Example:** A component displays a chart using `chart.js` which requires `window`. The developer wrapped it in `\u003CClientOnly>\u003CChart \u002F>\u003C\u002FClientOnly>` with a skeleton fallback. This eliminated hydration mismatch and provided a smooth loading experience. Without it, the server rendered an empty div, client rendered a canvas, causing mismatch and chart reinitialization.",[473,27,474,475,354],"hydration","mismatch","debugging","Emphasize that hydration mismatches are a common pain point in SSR frameworks. Demonstrating systematic debugging shows experience.","How do you conditionally render a component on client only without layout shift?","A component displays a chart using `chart.js` which requires `window`. The developer wrapped it in `\u003CClientOnly>\u003CChart \u002F>\u003C\u002FClientOnly>` with a skeleton fallback. This eliminated hydration mismatch and provided a smooth loading experience. Without it, the server rendered an empty div, client rendered a canvas, causing mismatch and chart reinitialization.",[480,491,501,512,523,535,544,556,566,579,590,601,612,623,631,644,654,665,675],{"id":6,"category":481,"question":482,"answer":483,"level":364,"tags":484,"interviewTip":488,"commonFollowUp":489,"realWorldExample":490},"Nitro Internals","How does Nitro's build pipeline work and how does it achieve universal deployment across different runtimes?","**Concept Explanation:** Nitro's build pipeline transforms your server code (API routes, middleware, server plugins) into a platform-agnostic bundle that can run on Node.js, Deno, Bun, Cloudflare Workers, Vercel Edge, and more. It achieves this by using a layer of abstractions: `h3` for HTTP, `unstorage` for storage, and runtime presets that shim platform-specific APIs. The build process uses Rollup to create a single output with platform-specific entry points.\n\n**Internal Working:** The pipeline has several phases: 1) Scan `server\u002F` directory and generate virtual modules for routes. 2) Resolve dependencies and create a dependency graph. 3) Apply platform-specific transformations (e.g., replace `fs` with in-memory for Workers). 4) Bundle using Rollup with custom plugins for each preset. 5) Generate an output directory (`.output\u002F`) containing server entry, public assets, and nitro.json configuration. The entry point uses a dynamic import to load the appropriate runtime adapter.\n\n**Request Flow (Build to Runtime):** Build: source code → Rollup bundling → platform adapter → output. Runtime: Adapter (e.g., `vercel-edge`) receives request → calls Nitro's internal handler → routes to API\u002FSSR.\n\n**Lifecycle:** Build-time: Nitro analyzes all server routes, including dynamic ones, and precomputes routing table. Runtime: The handler is a simple function that takes a request and returns a response, matching the signature of the target platform (e.g., `(request) => Response` for Workers).\n\n**Syntax & Code Example (Nitro config with custom preset):**\n```ts\n\u002F\u002F nuxt.config.ts\nexport default defineNuxtConfig({\n  nitro: {\n    preset: 'cloudflare',\n    output: { dir: 'dist' },\n    rollupConfig: {\n      plugins: [\u002F* custom rollup plugins *\u002F]\n    },\n    minify: true,\n    sourceMap: false\n  }\n})\n```\nView the generated output:\n```bash\n.output\u002F\n  server\u002F\n    chunks\u002F        # bundled server code\n    index.mjs      # main entry\n    package.json   # deployment metadata\n  public\u002F          # static assets\n  nitro.json       # route rules, preset info\n```\n\n**Practical Example:** Deploy the same codebase to Vercel (Edge) and Cloudflare Workers by changing only the preset. Nitro automatically handles differences like how headers are set (`event.node.res` vs `event.context.response`).\n\n**Common Mistakes:** Using Node.js-specific modules (`fs`, `path`) without checking if they exist in the target preset – will cause runtime errors. Assuming that environment variables are read the same way across platforms (Nitro abstracts via `useRuntimeConfig`). Overriding `rollupConfig` incorrectly can break the build.\n\n**Edge Cases:** Some presets (e.g., `vercel-edge`) have strict size limits (1MB for serverless functions). Nitro applies aggressive tree-shaking, but you may need to split routes into separate functions using `nitro.entry` or use the `node-server` preset instead. Also, `unstorage` drivers may not all work on edge (e.g., `redis` requires network access).\n\n**Interview Follow-ups:** \"How does Nitro handle WebSocket in serverless environments?\" \"What is the purpose of `preset: 'node'` vs `preset: 'node-server'`?\"\n\n**Best Practices:** Always test the built output with `nuxi preview` before deploying. Use environment-agnostic APIs (`useStorage`, `defineEventHandler`). For database connections, use lazy initialization to avoid cold start overhead.\n\n**Performance Considerations:** Nitro's bundle size is minimized by tree-shaking unused code. For serverless, smaller bundle = faster cold starts. Use `nitro.minify: true` in production. The `nitro.compressPublicAssets` option gzips assets.\n\n**SEO Considerations:** Not directly relevant.\n\n**Production Recommendations:** Choose the preset that matches your hosting platform precisely (e.g., `vercel` for Node.js, `vercel-edge` for edge). Use `nitro.static: true` for fully static sites. Monitor bundle sizes with `nitro.analyze: true`.\n\n**Latest Nuxt Patterns:** Nitro 2 supports `openapi` generation from your API routes, and `devProxy` for local development. The `preset` can also be a function returning a custom configuration.\n\n**TypeScript Example (defining custom preset):**\n```ts\nimport { defineNitroConfig } from 'nitropack'\nexport default defineNitroConfig({\n  preset: 'custom',\n  hooks: {\n    'rollup:before': (nitro, rollupConfig) => {\n      \u002F\u002F modify rollup config\n    }\n  }\n})\n```\n\n**Interview Tip:** Emphasize that understanding Nitro's abstraction layer is key to advanced Nuxt deployment. It allows you to write server code once and run anywhere – a huge advantage over traditional Node.js backends.\n\n**Common Follow-up:** \"How do you add a custom runtime adapter for a new platform?\"\n\n**Real-world Example:** A fintech startup needed to deploy their Nuxt app to a private cloud that runs AWS Lambda with a custom Node.js runtime. They created a custom Nitro preset by extending the `node-server` preset and modifying the entry point to match their Lambda wrapper. This allowed them to use the same codebase as their Vercel preview environment.\n\n",[38,270,485,325,486,487],"pipeline","adapter","rollup","Emphasize that understanding Nitro's abstraction layer is key to advanced Nuxt deployment. It allows you to write server code once and run anywhere – a huge advantage over traditional Node.js backends.","How do you add a custom runtime adapter for a new platform?","A fintech startup needed to deploy their Nuxt app to a private cloud that runs AWS Lambda with a custom Node.js runtime. They created a custom Nitro preset by extending the `node-server` preset and modifying the entry point to match their Lambda wrapper. This allowed them to use the same codebase as their Vercel preview environment.",{"id":20,"category":492,"question":493,"answer":494,"level":364,"tags":495,"interviewTip":498,"commonFollowUp":499,"realWorldExample":500},"Hydration & Payload","How does Nuxt's payload system work and how can you optimize payload extraction for performance?","**Concept Explanation:** Payload extraction is the mechanism Nuxt uses to serialize server-side data (from `useAsyncData`, `useFetch`, `useState`, and Pinia stores) and embed it into the HTML response. On the client, this payload is used to hydrate the app without re-fetching data. The payload is stored in `window.__NUXT__` (or a separate JavaScript file when using `payloadExtraction`). Optimizing payload size is critical for SSR performance.\n\n**Internal Working:** During SSR, Nuxt collects all data from composables with a unique key. After rendering, it serializes the data into a JavaScript object. By default, this object is embedded as a `\u003Cscript>` tag in the HTML. With `payloadExtraction: true` (default in Nuxt 3), Nuxt writes the payload to a separate `_payload.js` file (or `_payload.json`) and includes a `\u003Clink rel=\"modulepreload\">` to load it asynchronously, reducing HTML size. The client then fetches this payload and rehydrates.\n\n**Request Flow (with payload extraction):** 1) Server renders HTML and generates `_payload.js` file (in memory or disk). 2) HTML includes `\u003Cscript src=\"\u002F_payload.js\">` (or link). 3) Client downloads HTML first, then payload, then hydrates. Without extraction: payload is inline in HTML, increasing HTML size but reducing one request.\n\n**Lifecycle:** Payload is generated per request on server, then cached (if using route rules) or re-generated.\n\n**Syntax & Code Example (configuring payload extraction):**\n```ts\n\u002F\u002F nuxt.config.ts\nexport default defineNuxtConfig({\n  experimental: {\n    payloadExtraction: true  \u002F\u002F default in Nuxt 3, can be false\n  },\n  hooks: {\n    'render:html': (html, { event }) => {\n      \u002F\u002F modify html or payload\n    }\n  }\n})\n```\nOptimizing payload size:\n```vue\n\u003Cscript setup>\n\u002F\u002F Only pick needed fields\nconst { data } = await useFetch('\u002Fapi\u002Fusers', {\n  pick: ['id', 'name']  \u002F\u002F reduces payload size\n})\n\n\u002F\u002F Use transform to modify data before serialization\nconst { data } = await useAsyncData('products', () => $fetch('\u002Fapi\u002Fproducts'), {\n  transform: (products) => products.map(p => ({ id: p.id, name: p.name }))\n})\n\n\u002F\u002F Avoid storing large non-serializable data\nconst state = useState('bigData', () => null)\n\u002F\u002F Don't store functions, DOM elements, etc.\n\u003C\u002Fscript>\n```\n\n**Practical Example:** An e-commerce product page fetches 100 reviews with full text. Using `pick: ['rating', 'comment']` reduces payload from 500KB to 50KB. Also, using `transform` to strip HTML tags reduces further.\n\n**Common Mistakes:** Storing the same data multiple times with different keys (e.g., same user object in two `useAsyncData` calls). Not using `pick` or `transform`, leading to bloated payloads. Forgetting that `useState` values are also serialized – avoid storing large derived data.\n\n**Edge Cases:** `payloadExtraction: true` adds an extra network request, which may be slower on very high-latency connections. For very small payloads (\u003C1KB), inline may be better. You can conditionally disable extraction per route? Not directly, but you can use `useHead` to preload the payload.\n\n**Interview Follow-ups:** \"How does Nuxt handle circular references in payload?\" \"What is the difference between payload and state hydration?\"\n\n**Best Practices:** Always use `pick` or `transform` on API responses. Prefer `useAsyncData` with custom key to deduplicate identical data. Use `shallowRef` with `useState` if the data doesn't need deep reactivity. Avoid storing `ref` or `computed` inside state.\n\n**Performance Considerations:** Large payloads increase Time to First Byte (TTFB) and Time to Interactive (TTI). Keep payload under 100KB for good performance. Use `compression` middleware to gzip the payload.\n\n**SEO Considerations:** Payload extraction does not affect SEO directly, but faster page load improves Core Web Vitals, which are ranking factors.\n\n**Production Recommendations:** Enable `payloadExtraction: true` for most apps. Monitor payload size with `nuxi analyze`. For very large payloads (>500KB), consider lazy-loading data on the client using `server: false`.\n\n**Latest Nuxt Patterns:** Nuxt 3.5+ supports `payloadExtraction: 'manifest'` where payloads are hashed and cached infinitely. Also, `experimental.renderJsonPayloads` for JSON instead of JavaScript payloads.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F typed transform\nconst { data } = await useFetch\u003CApiUser, Pick\u003CApiUser, 'id' | 'name'>>('\u002Fapi\u002Fuser', {\n  transform: (user) => ({ id: user.id, name: user.name }) as const\n})\n```\n\n**Interview Tip:** Emphasize that payload size is often the biggest hidden performance issue in Nuxt apps. Many developers don't realize that `useState` also contributes to payload.\n\n**Common Follow-up:** \"How do you conditionally include data in payload only for certain routes?\"\n\n**Real-world Example:** A travel booking site had a homepage payload of 2MB because they fetched 5000 destination suggestions. They changed to lazy-loading suggestions on user input, reducing homepage payload to 80KB. This improved LCP from 3.2s to 1.1s and increased conversion by 12%.",[496,473,432,197,208,497],"payload","serialization","Emphasize that payload size is often the biggest hidden performance issue in Nuxt apps. Many developers don't realize that `useState` also contributes to payload.","How do you conditionally include data in payload only for certain routes?","A travel booking site had a homepage payload of 2MB because they fetched 5000 destination suggestions. They changed to lazy-loading suggestions on user input, reducing homepage payload to 80KB. This improved LCP from 3.2s to 1.1s and increased conversion by 12%.",{"id":32,"category":502,"question":503,"answer":504,"level":364,"tags":505,"interviewTip":509,"commonFollowUp":510,"realWorldExample":511},"Islands Architecture","What is islands architecture in Nuxt and how does it enable partial hydration?","**Concept Explanation:** Islands architecture is a pattern where most of the page is static HTML (generated on server) with small, isolated 'islands' of interactivity that load JavaScript only for those components. Nuxt implements this via the `@nuxtjs\u002Fisland` module (experimental) or by using `NuxtIsland` component. This reduces JavaScript bundle size and improves performance because only interactive components are hydrated, not the entire page.\n\n**Internal Working:** Islands are rendered on the server to HTML. Their JavaScript chunks are loaded separately and hydrated independently. The parent page does not need to load the island's JS until the island is scrolled into view or becomes interactive. Nuxt uses `vue-request` under the hood to manage island hydration. Each island is a separate Vue app instance (micro-frontend style).\n\n**Request Flow:** 1) Server renders page with islands as HTML placeholders (with `data-island` attributes). 2) Client loads minimal core JS. 3) When an island enters viewport (or based on `lazy` prop), client fetches island's JS chunk and hydrates it. 4) The island becomes interactive while the rest of the page remains static.\n\n**Lifecycle:** Islands are not reactive to page state changes unless explicitly connected via events or props.\n\n**Syntax & Code Example:**\nInstallation:\n```bash\nnpm install @nuxtjs\u002Fisland\n```\n`nuxt.config.ts`:\n```ts\nexport default defineNuxtConfig({\n  modules: ['@nuxtjs\u002Fisland'],\n  island: {\n    prefix: 'Island', \u002F\u002F optional prefix for auto-imports\n    clientOnly: true \u002F\u002F default\n  }\n})\n```\nDefine an island component (`components\u002FIsland\u002FComments.vue`):\n```vue\n\u003Ctemplate>\n  \u003Cdiv>\n    \u003Cbutton @click=\"loadComments\">Load Comments\u003C\u002Fbutton>\n    \u003Cdiv v-if=\"comments\">{{ comments }}\u003C\u002Fdiv>\n  \u003C\u002Fdiv>\n\u003C\u002Ftemplate>\n\u003Cscript setup>\nconst comments = ref(null)\nconst loadComments = async () => {\n  comments.value = await $fetch('\u002Fapi\u002Fcomments')\n}\n\u003C\u002Fscript>\n```\nUse in a page:\n```vue\n\u003Ctemplate>\n  \u003Cdiv>\n    \u003Ch1>Article\u003C\u002Fh1>\n    \u003Cp>Static content...\u003C\u002Fp>\n    \u003CNuxtIsland name=\"Comments\" :props=\"{ articleId: 1 }\" lazy \u002F>\n  \u003C\u002Fdiv>\n\u003C\u002Ftemplate>\n```\n\n**Practical Example:** A blog article page: the article content is static HTML, the comment section is an island that loads only when user scrolls to it, and the 'like' button is another island that loads immediately but independently.\n\n**Common Mistakes:** Putting too much logic in islands that need to communicate with each other (they are isolated). Using islands for components that are above the fold (increases waterfall). Forgetting to handle loading states (island may appear blank until hydrated).\n\n**Edge Cases:** Islands can also be rendered on the client only, but that defeats the purpose. Islands can accept props, but props are serialized and sent in the HTML (increases payload). Islands can emit events to parent via `defineEmits`, but the parent must have JS loaded.\n\n**Interview Follow-ups:** \"How does island architecture differ from traditional partial hydration?\" \"What are the limitations of islands in Nuxt currently?\"\n\n**Best Practices:** Use islands for third-party widgets (comments, social feeds, maps) and for above-the-fold interactive components only if necessary. For below-the-fold, use `lazy` prop. Keep islands small and focused.\n\n**Performance Considerations:** Islands dramatically reduce initial JavaScript bundle size – only core framework + island loader (\u003C10KB). Each island loads its own chunk, which can be cached. However, too many islands increase request count.\n\n**SEO Considerations:** Islands render fully on server, so crawlers see content even without JS. This is a huge SEO win compared to client-only components.\n\n**Production Recommendations:** Islands are still experimental in Nuxt; use with caution. For stable alternative, use `\u003CClientOnly>` with lazy loading. Monitor island chunk sizes.\n\n**Latest Nuxt Patterns:** Nuxt 3.9+ has built-in experimental island components via `experimental.componentIslands`. The `@nuxtjs\u002Fisland` module is the current recommended way.\n\n**TypeScript Example:**\n```vue\n\u003C!-- Island with typed props -->\n\u003Cscript setup lang=\"ts\">\nconst props = defineProps\u003C{ articleId: number }>()\nconst { data } = await useFetch(`\u002Fapi\u002Fcomments\u002F${props.articleId}`)\n\u003C\u002Fscript>\n```\n\n**Interview Tip:** Emphasize that islands architecture is the future of SSR frameworks – it gives the best of both worlds: static HTML with SEO and interactive components without the 'hydration tax' of full-page hydration.\n\n**Common Follow-up:** \"How do you share state between islands?\" (Use `useCookie` or broadcast channel, not Vue reactive state)\n\n**Real-world Example:** A news website converted their article page to islands: the article text (static), the 'related stories' carousel (island, lazy), social share buttons (island, eager), and comments (island, lazy with viewport trigger). JavaScript bundle dropped from 450KB to 45KB, and Time to Interactive improved from 4.2s to 1.8s.",[506,507,432,508],"islands","partial-hydration","experimental","Emphasize that islands architecture is the future of SSR frameworks – it gives the best of both worlds: static HTML with SEO and interactive components without the 'hydration tax' of full-page hydration.","How do you share state between islands?","A news website converted their article page to islands: the article text (static), the 'related stories' carousel (island, lazy), social share buttons (island, eager), and comments (island, lazy with viewport trigger). JavaScript bundle dropped from 450KB to 45KB, and Time to Interactive improved from 4.2s to 1.8s.",{"id":45,"category":513,"question":514,"answer":515,"level":364,"tags":516,"interviewTip":520,"commonFollowUp":521,"realWorldExample":522},"Streaming SSR","How does streaming SSR work in Nuxt and what are its performance implications?","**Concept Explanation:** Streaming SSR allows the server to send HTML to the client in chunks as soon as they are rendered, rather than waiting for the entire page to finish rendering. This improves perceived performance – the browser can start downloading assets and rendering early parts of the page (e.g., the header) before the rest is ready. Nuxt 3 supports streaming SSR by default when using `ssr: true` and deploying to a compatible environment (Node.js, Deno, but not all serverless platforms).\n\n**Internal Working:** Nitro uses `h3`'s streaming capability. Vue's `renderToNodeStream` (or `renderToWebStream`) produces a readable stream. As each component renders, the HTML is pushed to the stream. Nuxt also streams the payload and `\u003Chead>` early. The client starts receiving HTML immediately and can begin downloading CSS\u002FJS before the full page is done.\n\n**Request Flow:** 1) Browser requests page → 2) Server starts rendering top-level component (e.g., layout header) → 3) HTML chunk sent immediately → 4) Browser starts parsing and may request CSS\u002FJS for visible parts → 5) Server continues rendering async components (e.g., suspended `useAsyncData`) → 6) Remaining HTML sent progressively → 7) Browser completes parsing and hydrates.\n\n**Lifecycle:** Streaming is transparent – it happens automatically. However, components using `useAsyncData` with `suspense: true` (default) will block streaming until resolved unless you use `lazy: true`.\n\n**Syntax & Code Example (enabling streaming – default):**\n```ts\n\u002F\u002F nuxt.config.ts – streaming is default, no config needed\nexport default defineNuxtConfig({\n  ssr: true,\n  nitro: { preset: 'node-server' } \u002F\u002F Node.js supports streaming\n})\n```\nTo disable streaming (not recommended):\n```ts\n\u002F\u002F server\u002Fapi\u002Frenderer.ts (custom renderer)\nimport { renderToString } from 'vue\u002Fserver-renderer'\n\u002F\u002F Use renderToString instead of renderToStream\n```\n\nTo use `lazy` to unblock streaming:\n```vue\n\u003Cscript setup>\n\u002F\u002F This will not block streaming because lazy: true\nconst { data: comments } = await useFetch('\u002Fapi\u002Fcomments', { lazy: true })\n\u002F\u002F But you need to handle pending state in template\n\u003C\u002Fscript>\n\u003Ctemplate>\n  \u003Cdiv v-if=\"comments\">{{ comments }}\u003C\u002Fdiv>\n  \u003Cdiv v-else>Loading comments...\u003C\u002Fdiv>\n\u003C\u002Ftemplate>\n```\n\n**Practical Example:** An e-commerce product page: header and product title stream immediately, while product reviews (slow API) appear later. The user sees the page quickly and can start interacting with the header.\n\n**Common Mistakes:** Using `lazy: false` (default) for slow async data – this blocks streaming. Not handling `pending` state, causing layout shifts when data arrives. Deploying to a serverless platform that doesn't support streaming (e.g., some Lambda versions) – Nuxt falls back to non-streaming but may cause timeouts.\n\n**Edge Cases:** Streaming may not work with CDN caching (since CDN caches the full response). Use `swr` or `static` mode for cached pages. Also, some reverse proxies buffer responses, defeating streaming benefits. Set `X-Accel-Buffering: no` for Nginx.\n\n**Interview Follow-ups:** \"How does streaming affect SEO?\" \"Can you stream only part of the page?\"\n\n**Best Practices:** Profile your slow async data and mark them with `lazy: true`. Provide meaningful loading skeletons. Use `Suspense` with `#fallback` slot for components that stream asynchronously.\n\n**Performance Considerations:** Streaming improves Time to First Byte (TTFB) because the header is sent immediately. It also improves Largest Contentful Paint (LCP) if the LCP element is early in the stream. However, streaming adds CPU overhead; for very simple pages, it may be unnecessary.\n\n**SEO Considerations:** Search engine crawlers receive the full HTML eventually; streaming does not affect completeness. However, if your page relies on lazy-loaded content that never loads because crawler doesn't execute JS, you may lose SEO – ensure critical content is not lazy.\n\n**Production Recommendations:** Ensure your hosting platform supports response streaming. For Vercel (Node.js runtime), streaming works; for Vercel Edge, it also works. For Netlify Functions, streaming may be limited. Test with `curl -N` to see chunks.\n\n**Latest Nuxt Patterns:** Nuxt 3 supports `experimental.renderEventComponent` for streaming custom components. Also, `useAsyncData` with `suspense: false` to force non-blocking.\n\n**TypeScript Example:** Not applicable.\n\n**Interview Tip:** Emphasize that streaming SSR is a powerful but often misunderstood feature. Many developers don't realize that `useAsyncData` blocks streaming by default, hurting performance.\n\n**Common Follow-up:** \"How do you implement a loading skeleton for streaming content?\"\n\n**Real-world Example:** A travel search results page queries multiple APIs (flights, hotels, activities). By marking the flight and hotel data as `lazy: true`, the page header and search form stream immediately. The user sees a loading spinner for flights and hotels, but can already modify the search. This reduced perceived wait time from 3 seconds to 0.8 seconds.",[517,27,432,518,519],"streaming","lazy","suspense","Emphasize that streaming SSR is a powerful but often misunderstood feature. Many developers don't realize that `useAsyncData` blocks streaming by default, hurting performance.","How do you implement a loading skeleton for streaming content?","A travel search results page queries multiple APIs (flights, hotels, activities). By marking the flight and hotel data as `lazy: true`, the page header and search form stream immediately. The user sees a loading spinner for flights and hotels, but can already modify the search. This reduced perceived wait time from 3 seconds to 0.8 seconds.",{"id":55,"category":524,"question":525,"answer":526,"level":364,"tags":527,"interviewTip":532,"commonFollowUp":533,"realWorldExample":534},"Advanced Caching","How can you implement a multi-tier caching strategy in Nuxt using Nitro storage and route rules?","**Concept Explanation:** Multi-tier caching uses different caching layers (memory, Redis, CDN) with different TTLs to optimize performance and freshness. In Nuxt, you can combine Nitro's built-in cache with `defineCachedEventHandler` (in-memory or Redis), route rules `swr` for CDN-like caching, and manual storage caching for database queries. This reduces load on origin servers and databases.\n\n**Internal Working:** Nitro's `defineCachedEventHandler` wraps an event handler and stores the response in a cache store (configured via `nitro.storage`). You can have multiple storage mounts (e.g., `memory` for hot cache, `redis` for shared cache). Route rules with `swr` add `Cache-Control` headers for CDN and also enable Nitro's SWR (serve stale while revalidating). You can also implement manual caching for database queries using `useStorage()`.\n\n**Request Flow (multi-tier):** 1) Request hits CDN → if cached, serve; else forward to Nitro. 2) Nitro checks its SWR cache (Redis). 3) If miss, handler runs → checks manual cache (e.g., database query cache). 4) Response cached at all levels.\n\n**Lifecycle:** Cache entries expire based on TTL. SWR allows serving stale data while refreshing.\n\n**Syntax & Code Example (multi-tier config):**\n`nuxt.config.ts`:\n```ts\nexport default defineNuxtConfig({\n  nitro: {\n    storage: {\n      cache: {\n        driver: 'redis',\n        url: process.env.REDIS_URL\n      },\n      memoryCache: {\n        driver: 'memory',\n        maxEntries: 1000\n      }\n    },\n    routeRules: {\n      '\u002Fapi\u002Fproducts\u002F**': { swr: 3600, headers: { 'CDN-Cache-Control': 'max-age=86400' } }\n    }\n  }\n})\n```\n`server\u002Fapi\u002Fexpensive.ts` (manual multi-tier):\n```ts\nexport default defineEventHandler(async (event) => {\n  \u002F\u002F Tier 1: Check memory cache\n  const memoryCache = useStorage('memoryCache')\n  let data = await memoryCache.getItem('expensive-data')\n  if (data) return data\n\n  \u002F\u002F Tier 2: Check Redis shared cache\n  const redisCache = useStorage('cache')\n  data = await redisCache.getItem('expensive-data')\n  if (data) {\n    \u002F\u002F Populate memory cache\n    await memoryCache.setItem('expensive-data', data, { ttl: 60 })\n    return data\n  }\n\n  \u002F\u002F Tier 3: Compute fresh\n  data = await expensiveComputation()\n  await redisCache.setItem('expensive-data', data, { ttl: 300 })\n  await memoryCache.setItem('expensive-data', data, { ttl: 60 })\n  return data\n})\n```\n\n**Practical Example:** An API that aggregates data from multiple slow services. Redis caches the result for 5 minutes, memory cache for 1 minute, CDN caches for 1 day with stale-while-revalidate.\n\n**Common Mistakes:** Over-caching with too many layers increasing complexity. Not setting appropriate TTLs – too short defeats purpose, too long causes stale data. Using memory cache in serverless (doesn't persist across invocations).\n\n**Edge Cases:** Cache invalidation – when data updates, you need to purge all layers. Use `event.context.waitUntil` to purge caches asynchronously. Also, beware of cache stampede: many requests recompute simultaneously. Use `swr` or `stale-while-revalidate` to mitigate.\n\n**Interview Follow-ups:** \"How do you invalidate a Redis cache from an admin API?\" \"What is the difference between memory and Redis cache for serverless?\"\n\n**Best Practices:** Use memory cache for per-instance hot data (short TTL). Use Redis for shared cache across instances (medium TTL). Use CDN\u002FSWR for edge caching (long TTL). Implement cache versioning to flush old data.\n\n**Performance Considerations:** Redis adds network latency but reduces database load. Measure cache hit rates. Use `defineCachedEventHandler` for automatic caching with SWR.\n\n**SEO Considerations:** Not directly relevant.\n\n**Production Recommendations:** Start with `defineCachedEventHandler` and Redis. Add memory cache only if needed for high-throughput endpoints. Monitor Redis memory usage.\n\n**Latest Nuxt Patterns:** Nitro 2 supports `defineCachedEventHandler` with `swr: true` and `group` for batch invalidation. Also, `useStorage` can use `driver: 'redis'` with clustering.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F typed cache retrieval\nconst cached = await useStorage\u003CMyDataType>('cache').getItem('key')\n```\n\n**Interview Tip:** Emphasize that caching is not just about performance but also about cost reduction (fewer database calls, less compute). Multi-tier caching is an advanced pattern that scales.\n\n**Common Follow-up:** \"How do you handle cache warming on deploy?\"\n\n**Real-world Example:** A stock price API used by a dashboard. The data changes every 5 minutes. They implemented: CDN cache 1 minute (serves stale but fast), Redis cache 2 minutes (shared across serverless functions), memory cache 30 seconds (hot). This reduced origin calls by 99% and kept data fresh within 5 seconds of actual change.",[442,528,529,530,531,444],"redis","memory","cdn","multi-tier","Emphasize that caching is not just about performance but also about cost reduction (fewer database calls, less compute). Multi-tier caching is an advanced pattern that scales.","How do you handle cache warming on deploy?","A stock price API used by a dashboard. The data changes every 5 minutes. They implemented: CDN cache 1 minute (serves stale but fast), Redis cache 2 minutes (shared across serverless functions), memory cache 30 seconds (hot). This reduced origin calls by 99% and kept data fresh within 5 seconds of actual change.",{"id":66,"category":536,"question":537,"answer":538,"level":364,"tags":539,"interviewTip":541,"commonFollowUp":542,"realWorldExample":543},"Rendering Internals","How do route rules work under the hood in Nitro and how can you create custom route rules?","**Concept Explanation:** Route rules in Nitro define per-route behavior like caching, redirects, CORS, and rendering mode (SSR\u002FCSR\u002Fstatic). Under the hood, Nitro generates a route matcher during build time using `unjs\u002Fradix3` (a radix tree router). Each rule is compiled into a set of conditions and actions that are applied in the request handling pipeline. Custom route rules can be added programmatically via Nitro hooks.\n\n**Internal Working:** At build time, Nitro reads `routeRules` from config and builds a radix tree for fast matching. For each route, it creates an internal record with properties like `cache`, `redirect`, `headers`, `cors`, `ssr` (which controls whether to use the Vue SSR renderer or SPA fallback). At request time, Nitro matches the URL against the tree, applies the rules (e.g., sets headers, handles redirect), and then invokes the appropriate handler (static file, API, or SSR renderer).\n\n**Request Flow:** 1) Request URL `\u002Fproducts\u002F123` → 2) Nitro matches against route rules tree → 3) If `redirect` exists, returns 3xx response → 4) Else if `static: true`, serves pre-generated HTML from `dist\u002F` (if exists) → 5) Else if `ssr: false`, serves SPA fallback (empty HTML) → 6) Else proceeds to SSR renderer.\n\n**Lifecycle:** Route rules are static (defined at build time). However, you can use `useNitro` to dynamically add rules in a Nitro plugin (but must be before server start).\n\n**Syntax & Code Example (built-in):**\n```ts\n\u002F\u002F nuxt.config.ts\nexport default defineNuxtConfig({\n  routeRules: {\n    '\u002Fapi\u002F**': { cors: true, headers: { 'X-API-Version': '1' } },\n    '\u002Fold\u002F*': { redirect: '\u002Fnew\u002F:path*' },\n    '\u002Fblog\u002F**': { swr: 3600 },\n    '\u002Fdashboard\u002F**': { ssr: false }\n  }\n})\n```\n\n**Creating custom route rules programmatically (Nitro plugin):**\n`server\u002Fplugins\u002FrouteRules.ts`:\n```ts\nexport default defineNitroPlugin((nitroApp) => {\n  nitroApp.hooks.hook('render:html', (html, { event }) => {\n    \u002F\u002F Not for route rules\n  })\n  \u002F\u002F Use internal router (not publicly documented, but you can add middleware)\n  const router = useRuntimeConfig().nitro?.router\n  \u002F\u002F Alternative: use global middleware to conditionally apply logic\n})\n```\nBetter approach: use Nitro middleware to simulate custom route rules:\n`server\u002Fmiddleware\u002Fcustom.ts`:\n```ts\nexport default defineEventHandler((event) => {\n  const url = event.path\n  if (url.startsWith('\u002Fspecial')) {\n    event.context.customRule = true\n    setResponseHeader(event, 'X-Custom', 'value')\n  }\n})\n```\n\n**Practical Example:** Create a custom rule that throttles API requests per IP using Nitro middleware and `useStorage`. This is not built-in but can be added manually.\n\n**Common Mistakes:** Assuming route rules are applied in order of definition (they are not; radix tree matches most specific first). Using overlapping patterns that cause unexpected matches (e.g., `\u002Fapi\u002F**` and `\u002Fapi\u002Fpublic\u002F**` – both match, but `\u002Fapi\u002Fpublic\u002F**` is more specific). Not understanding that `ssr: false` returns an empty HTML shell, not the page content.\n\n**Edge Cases:** Dynamic route rules are not supported; you cannot change them at runtime. However, you can use `event.context` to apply conditional logic. For redirects, use `redirect` rule for permanent redirects (301) or `navigateTo` in middleware for temporary.\n\n**Interview Follow-ups:** \"How does Nitro handle conflicting route rules?\" \"Can you disable route rules for certain environments?\"\n\n**Best Practices:** Use `redirect` for permanent URL changes (SEO). Use `swr` for content that can be stale. Use `cors` for API routes. Avoid using `ssr: false` for critical SEO pages.\n\n**Performance Considerations:** Route rules matching is O(path length) using radix tree, very fast. Redirects and CORS headers are applied before any heavy processing.\n\n**SEO Considerations:** `redirect` rules return proper HTTP 301\u002F302 status codes, good for SEO. `swr` adds `Cache-Control` headers that crawlers respect.\n\n**Production Recommendations:** Test route rules thoroughly with `nuxi build` and preview. Use `curl -I` to check headers and redirects.\n\n**Latest Nuxt Patterns:** Nuxt 3.8+ supports `isr: true` (Incremental Static Regeneration) as a route rule. Also, `swr` can be a number (TTL in seconds) or `true` (default 60s).\n\n**TypeScript Example:**\n```ts\n\u002F\u002F Extend Nitro route rules types\ndeclare module 'nitropack' {\n  interface NitroRouteRules {\n    myCustom?: boolean\n  }\n}\n```\n\n**Interview Tip:** Emphasize that understanding route rules internals allows you to create highly optimized edge-cached applications with zero server-side logic for most requests.\n\n**Common Follow-up:** \"How do you implement IP-based rate limiting using route rules?\"\n\n**Real-world Example:** An e-commerce site had 100K product pages. They used `routeRules: { '\u002Fproducts\u002F**': { static: true } }` to pre-render all pages at build time, and `swr: 86400` for the homepage to revalidate daily. This reduced server costs by 90% and made the site extremely fast.",[441,38,105,540,442],"radix-tree","Emphasize that understanding route rules internals allows you to create highly optimized edge-cached applications with zero server-side logic for most requests.","How do you implement IP-based rate limiting using route rules?","An e-commerce site had 100K product pages. They used `routeRules: { '\u002Fproducts\u002F**': { static: true } }` to pre-render all pages at build time, and `swr: 86400` for the homepage to revalidate daily. This reduced server costs by 90% and made the site extremely fast.",{"id":77,"category":545,"question":546,"answer":547,"level":364,"tags":548,"interviewTip":553,"commonFollowUp":554,"realWorldExample":555},"Server Lifecycle","How does Nuxt manage request isolation and server context to prevent cross-request state leaks?","**Concept Explanation:** In SSR, multiple requests are handled concurrently by the same Node.js process. Global state (e.g., a module-level variable) would be shared across requests, leading to data leakage. Nuxt prevents this by using request-scoped contexts. Each request gets its own isolated context where per-request data like `useState`, `useAsyncData` payload, and request headers are stored. This is achieved using `AsyncLocalStorage` (Node.js) or similar mechanisms in other runtimes.\n\n**Internal Working:** Nuxt (via Nitro) creates an `AsyncLocalStorage` instance that holds the current request context. When a request arrives, Nitro initializes a new context, runs all Nuxt hooks and rendering inside that context, and then destroys it. Composables like `useState` and `useAsyncData` read\u002Fwrite from this context. The context includes the `event` object (request\u002Fresponse), a map for state, and a map for payload data. After the response is sent, the context is garbage-collected.\n\n**Request Flow:** 1) Request arrives → 2) Nitro creates a new async context → 3) Sets `event` context → 4) Nuxt SSR renderer runs inside this context → 5) Composables store data in context-local maps → 6) Response sent → 7) Context released.\n\n**Lifecycle:** Context is created per request and disposed after response. There is no shared state across requests unless explicitly using external storage (Redis, database).\n\n**Syntax & Code Example (how to use request context safely):**\n```ts\n\u002F\u002F composables\u002FuseRequestScopedState.ts\nexport const useRequestScopedState = (key: string, init: () => any) => {\n  \u002F\u002F Uses useState which is already request-scoped\n  return useState(key, init)\n}\n\n\u002F\u002F Bad: global variable (leaks)\nlet globalCounter = 0\nexport const useBadCounter = () => {\n  globalCounter++ \u002F\u002F will leak across requests!\n  return globalCounter\n}\n\n\u002F\u002F Good: use useState\nconst counter = useState('counter', () => 0)\ncounter.value++\n```\n\nTo access raw request context in a Nitro plugin:\n```ts\n\u002F\u002F server\u002Fplugins\u002Fcontext.ts\nexport default defineNitroPlugin((nitroApp) => {\n  nitroApp.hooks.hook('request', (event) => {\n    event.context.myCustomData = { startTime: Date.now() }\n  })\n})\n```\n\n**Practical Example:** A request counter for debugging – storing request count in a global variable would show increasing numbers across users, which is wrong. Using `useState` scopes it per request.\n\n**Common Mistakes:** Using module-level variables to cache data without understanding that they persist across requests (unless using a proper caching solution with TTL). Assuming that a plugin runs once per request (some plugins run once per process). Not cleaning up event listeners or timers in request scope.\n\n**Edge Cases:** In serverless environments, each request may run in a separate cold start, so global state is less of an issue but still not guaranteed. `AsyncLocalStorage` may not be available in all edge runtimes (e.g., Cloudflare Workers have their own context system via `event.waitUntil`).\n\n**Interview Follow-ups:** \"How does Nuxt's request isolation compare to Next.js?\" \"Can you manually create a new request context?\"\n\n**Best Practices:** Always use Nuxt composables (`useState`, `useCookie`, `useFetch`) for data that should be request-scoped. Avoid global variables. Use `event.context` for passing data between Nitro middleware and handlers.\n\n**Performance Considerations:** `AsyncLocalStorage` has minimal overhead (microseconds). Creating many per-request objects can increase memory pressure; clean up large references (e.g., uploaded files) after use.\n\n**SEO Considerations:** Not relevant.\n\n**Production Recommendations:** Monitor memory usage; if you see memory growth, suspect cross-request leaks. Use `process.memoryUsage()` in middleware to debug.\n\n**Latest Nuxt Patterns:** Nuxt 3 uses `unjs\u002Fnitro`'s context system. You can also use `useEvent` to get the current request event in composables (experimental).\n\n**TypeScript Example:**\n```ts\n\u002F\u002F Extend event context type\ndeclare module 'h3' {\n  interface H3EventContext {\n    user?: { id: number }\n  }\n}\n```\n\n**Interview Tip:** Emphasize that request isolation is critical for SSR correctness. This is a common source of bugs for developers coming from traditional backend frameworks where globals are per-thread but Node.js is single-threaded with async concurrency.\n\n**Common Follow-up:** \"How do you implement per-request caching of database queries?\"\n\n**Real-world Example:** A SaaS app had a bug where user A occasionally saw user B's data. The cause was a global `currentUser` variable set in a middleware that was being overwritten by concurrent requests. After refactoring to use `useState` and `event.context`, the issue was resolved.",[549,550,551,552],"request-context","isolation","async-local-storage","state-leaks","Emphasize that request isolation is critical for SSR correctness. This is a common source of bugs for developers coming from traditional backend frameworks where globals are per-thread but Node.js is single-threaded with async concurrency.","How do you implement per-request caching of database queries?","A SaaS app had a bug where user A occasionally saw user B's data. The cause was a global `currentUser` variable set in a middleware that was being overwritten by concurrent requests. After refactoring to use `useState` and `event.context`, the issue was resolved.",{"id":89,"category":426,"question":557,"answer":558,"level":364,"tags":559,"interviewTip":563,"commonFollowUp":564,"realWorldExample":565},"How do you debug and fix memory leaks in a production Nuxt SSR application?","**Concept Explanation:** Memory leaks in Nuxt SSR occur when the server process retains memory across requests that should be garbage-collected. Common causes: global variables, event listeners not removed, cached data growing indefinitely, closures referencing large objects, and improper use of `useState` or Pinia with cross-request contamination. Debugging requires heap snapshots, monitoring memory usage, and analyzing retention paths.\n\n**Internal Working:** Node.js uses garbage collection (GC) to free unused memory. Leaks happen when references to objects are kept unintentionally. In Nuxt, each request creates a new context; if that context is not released (e.g., due to unresolved promises, global event listeners), memory accumulates. Over time, the process may crash with `JavaScript heap out of memory`.\n\n**Detection:** Monitor memory usage: `process.memoryUsage().heapUsed`. A steady upward trend over requests indicates a leak. Use `--inspect` flag and Chrome DevTools to take heap snapshots. Compare snapshots before and after many requests to see retained objects.\n\n**Debugging Steps:**\n1. Enable GC logging: `node --trace-gc server\u002Findex.mjs`\n2. Use `clinic` or `0x` for flamegraphs.\n3. Add `process.memoryUsage()` logging in middleware.\n4. Take heap snapshots using `node --inspect` and Chrome Memory tab.\n5. Look for large arrays or objects that persist.\n\n**Common Leak Patterns in Nuxt:**\n```ts\n\u002F\u002F Bad: global cache without eviction\nconst globalCache = new Map()\nexport default defineEventHandler(() => {\n  globalCache.set(Date.now(), largeData) \u002F\u002F grows forever\n})\n\n\u002F\u002F Bad: adding event listeners without removal\n\u002F\u002F In a plugin or middleware\nwindow.addEventListener('resize', () => {}) \u002F\u002F On server? Doesn't exist, but client-side leaks.\n\u002F\u002F For server: event listeners on process\nprocess.on('SIGINT', () => {}) \u002F\u002F Only once, but if added per request, leaks.\n\n\u002F\u002F Bad: storing request data in a global array\nconst requests = []\ndefineEventHandler((event) => {\n  requests.push(event) \u002F\u002F event objects retain request data\n})\n\n\u002F\u002F Good: use LRU cache or TTL\nconst cache = useStorage('cache') \u002F\u002F Nitro storage with TTL\n```\n\n**Practical Example:** A middleware that logs every request URL to an array for analytics. After 1 million requests, the array consumes 500MB memory. Fix: write to external service or use a bounded queue.\n\n**Common Mistakes:** Assuming `useState` is automatically garbage-collected after request (it is, but if you store it in a global variable, it leaks). Using `setInterval` in a plugin without cleanup. Caching user sessions in memory (use Redis instead).\n\n**Edge Cases:** Third-party modules may leak memory. Use `require.cache` to debug module leaks. In serverless, memory leaks cause cold starts only, but long-running functions still suffer.\n\n**Interview Follow-ups:** \"How do you profile heap memory in production without stopping the server?\" \"What tools do you use for memory leak detection?\"\n\n**Best Practices:** Avoid global mutable state. Use `useStorage` with TTL for caching. Use `WeakMap` or `WeakRef` when appropriate. Clean up event listeners in `onUnmounted` (client) or `afterResponse` hook (server).\n\n**Performance Considerations:** Memory leaks degrade performance over time, causing GC pauses and eventual OOM crashes. Fixing leaks improves request latency and stability.\n\n**SEO Considerations:** Not relevant.\n\n**Production Recommendations:** Set up memory monitoring (e.g., Datadog, New Relic). Use `@nuxt\u002Ftelemetry` to track memory usage. Schedule periodic process restarts (e.g., daily) as a fallback.\n\n**Latest Nuxt Patterns:** Nuxt 3's `useState` is automatically cleaned up per request. For long-running processes, use `nitro.storage` with `driver: 'redis'` to offload memory.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F Using LRU cache from 'lru-cache'\nimport LRU from 'lru-cache'\nconst cache = new LRU({ max: 500 })\nexport default defineEventHandler(() => {\n  const data = cache.get('key')\n  if (!data) {\n    const fresh = compute()\n    cache.set('key', fresh)\n    return fresh\n  }\n  return data\n})\n```\n\n**Interview Tip:** Emphasize that memory leaks are subtle but can bring down production apps. Knowing how to use heap snapshots is a valuable skill that sets senior engineers apart.\n\n**Common Follow-up:** \"Can you have memory leaks in serverless environments?\"\n\n**Real-world Example:** A Nuxt app serving 10k requests per minute on a 2GB memory instance started crashing every 2 days. Heap snapshots revealed that a `useAsyncData` key was dynamically generated (`key: ${Date.now()}`), creating a new entry every request. The payload store grew unbounded. Fix: use a static key or implement a cleanup strategy. After fix, memory stabilized and crashes stopped.",[560,432,475,561,562],"memory-leaks","heap","gc","Emphasize that memory leaks are subtle but can bring down production apps. Knowing how to use heap snapshots is a valuable skill that sets senior engineers apart.","Can you have memory leaks in serverless environments?","A Nuxt app serving 10k requests per minute on a 2GB memory instance started crashing every 2 days. Heap snapshots revealed that a `useAsyncData` key was dynamically generated (`key: ${Date.now()}`), creating a new entry every request. The payload store grew unbounded. Fix: use a static key or implement a cleanup strategy. After fix, memory stabilized and crashes stopped.",{"id":99,"category":567,"question":568,"answer":569,"level":364,"tags":570,"interviewTip":576,"commonFollowUp":577,"realWorldExample":578},"Deployment","What are the advanced deployment strategies for Nuxt 3 at scale (blue-green, canary, edge, multi-region)?","**Concept Explanation:** Advanced deployment strategies go beyond basic `nuxt build && nuxt start`. Blue-green deployment uses two identical environments (blue=live, green=staging) to switch traffic with zero downtime. Canary deployment rolls out new versions to a small percentage of users. Edge deployment runs Nuxt on CDN nodes (Cloudflare Workers, Vercel Edge) for low latency. Multi-region deploys to multiple geographic regions for high availability and reduced latency.\n\n**Internal Working:** Nuxt's Nitro output is a standalone server or serverless function. For blue-green, you run two instances behind a load balancer. For canary, you use weighted routing (e.g., 10% traffic to new version). For edge, you deploy using Nitro's edge presets (`vercel-edge`, `cloudflare`). For multi-region, you deploy the same Nitro output to multiple regions and use global load balancing (e.g., AWS Global Accelerator, Cloudflare's network).\n\n**Request Flow (multi-region edge):** User in Asia → DNS resolves to nearest edge location → Cloudflare Worker or Vercel Edge runs Nuxt → SSR (or cached) response from that region.\n\n**Syntax & Code Example (blue-green with PM2):**\n```bash\n# Deploy to green (port 3001)\nPORT=3001 NITRO_PORT=3001 node .output\u002Fserver\u002Findex.mjs &\n# Switch load balancer from blue (3000) to green\n```\n**Canary with Vercel:** Use Vercel's deployment aliases and `vercel --target=preview` then gradually promote.\n**Edge deployment configuration:**\n```ts\n\u002F\u002F nuxt.config.ts\nexport default defineNuxtConfig({\n  nitro: {\n    preset: 'vercel-edge',\n    edge: true,\n    serveStatic: false \u002F\u002F static assets via CDN\n  }\n})\n```\n**Multi-region with Cloudflare:**\n```ts\n\u002F\u002F wrangler.toml\nname = \"my-nuxt-app\"\nworkers_dev = true\nregions = [\"weur\", \"eeur\", \"apac\", \"oc\", \"nam\"]\n```\n\n**Practical Example:** A global e-commerce site deploys to Vercel Edge with regions: `iad1` (US), `cpt1` (EU), `hnd1` (Asia). Users in Asia get \u003C50ms latency. Blue-green ensures zero downtime on Black Friday.\n\n**Common Mistakes:** Not handling database migration compatibility across versions (blue-green requires backward-compatible schema). Edge runtimes have limitations (no `fs`, limited CPU time). Multi-region may cause session affinity issues if using in-memory sessions (use Redis).\n\n**Edge Cases:** Stateful WebSocket connections cannot be blue-green without draining. Serverless cold starts in edge are usually minimal (\u003C5ms). Canary with SSR may serve different HTML versions to users, causing client cache issues.\n\n**Interview Follow-ups:** \"How do you handle database migrations in blue-green?\" \"What is the downside of edge deployment?\"\n\n**Best Practices:** Use stateless design for easy scaling. Use external session store (Redis) for multi-region. Implement health checks for blue-green. Use feature flags for canary, not just traffic splitting.\n\n**Performance Considerations:** Edge deployment drastically reduces latency for dynamic content (from 200ms to 20ms). Multi-region reduces latency globally. Blue-green adds no performance overhead.\n\n**SEO Considerations:** Edge and multi-region improve Core Web Vitals due to lower latency. Blue-green prevents downtime, preserving SEO rankings.\n\n**Production Recommendations:** Start with single-region edge. Add multi-region if you have global users. Use blue-green for critical apps. Canary is advanced; use feature flags with LaunchDarkly instead.\n\n**Latest Nuxt Patterns:** Nuxt 3 supports `nitro. preset: 'cloudflare-pages'` and `vercel-edge`. Also, `openapi` generation helps with blue-green by validating API contracts.\n\n**TypeScript Example:** Not applicable.\n\n**Interview Tip:** Emphasize that deployment strategy is not one-size-fits-all. Edge is great for dynamic content, but for heavy compute, a traditional Node.js server may be better.\n\n**Common Follow-up:** \"How do you implement zero-downtime migrations with Prisma and Nuxt?\"\n\n**Real-world Example:** A fintech app with global users deployed to 5 AWS regions using Nitro's `aws-lambda` preset and CloudFront latency-based routing. Blue-green allowed them to upgrade the backend without downtime. Edge wasn't feasible due to Node.js native dependencies, so they used `node-server` preset and regional EC2 clusters.",[325,571,572,573,574,575],"blue-green","canary","edge","multi-region","scaling","Emphasize that deployment strategy is not one-size-fits-all. Edge is great for dynamic content, but for heavy compute, a traditional Node.js server may be better.","How do you implement zero-downtime migrations with Prisma and Nuxt?","A fintech app with global users deployed to 5 AWS regions using Nitro's `aws-lambda` preset and CloudFront latency-based routing. Blue-green allowed them to upgrade the backend without downtime. Edge wasn't feasible due to Node.js native dependencies, so they used `node-server` preset and regional EC2 clusters.",{"id":112,"category":580,"question":581,"answer":582,"level":364,"tags":583,"interviewTip":587,"commonFollowUp":588,"realWorldExample":589},"Nitro Rendering Pipeline","How does Nitro's rendering pipeline integrate with Vue SSR? Explain the step-by-step flow from request to HTML response.","**Concept Explanation:** Nitro's rendering pipeline is the bridge between the incoming HTTP request and the Vue SSR renderer. It consists of several layers: Nitro server (h3) receives the request, applies route rules and global middleware, then invokes the Vue renderer (via Nuxt's server plugin). The renderer creates a Vue app instance, executes async data fetching, and streams\u002Freturns HTML. Nitro then sends the response, applying any cache headers from route rules.\n\n**Internal Working:** The pipeline is orchestrated by Nitro's `defineEventHandler` for the default renderer route (usually `\u002F**`). This handler:\n1. Normalizes the request URL and extracts route parameters.\n2. Runs Nitro middleware (global, before rendering).\n3. Calls the Nuxt renderer (imported from `#build`).\n4. The Nuxt renderer creates a new Vue app, runs `setup()` of the matched page, waits for `useAsyncData` promises, and renders to HTML stream\u002Fstring.\n5. The result is wrapped in a full HTML document (including `\u003C!DOCTYPE>`, `\u003Chead>`, etc.).\n6. Nitro applies response headers, cookies, and cache control from route rules.\n7. Returns the response.\n\n**Request Flow (detailed):**\n1. HTTP request → Nitro server (`server\u002Findex.mjs` entry).\n2. Nitro matches route against `routeRules` (radix tree). If redirect, returns 3xx.\n3. Nitro applies global server middleware (from `server\u002Fmiddleware\u002F`).\n4. Route handler resolved: for non-API routes, it's the default SSR handler.\n5. SSR handler calls `renderToString` or `renderToStream` from Nuxt core.\n6. Nuxt creates a Vue app instance (isolated per request).\n7. Vue router resolves the page component.\n8. Page `setup()` runs, including `useAsyncData` and `useFetch` calls (these are tracked).\n9. Nuxt waits for all tracked promises (unless `lazy: true`).\n10. Vue renders the component tree to a stream or string.\n11. Nuxt injects the serialized payload (`window.__NUXT__` or separate `_payload.js`).\n12. Nitro finalizes response: sets `Content-Type`, cache headers, etc.\n13. Response sent.\n\n**Lifecycle:** On server start, Nitro loads all routes and middleware once. Per request, a fresh Vue app is created and discarded after response.\n\n**Syntax & Code Example (custom renderer hook):**\n```ts\n\u002F\u002F server\u002Fplugins\u002Frenderer.ts – hook into render process\nexport default defineNitroPlugin((nitroApp) => {\n  nitroApp.hooks.hook('render:html', (html, { event }) => {\n    \u002F\u002F Modify HTML before sending\n    html.head.push('\u003Cmeta name=\"custom\" content=\"value\">')\n  })\n  nitroApp.hooks.hook('render:response', (response, { event }) => {\n    \u002F\u002F Modify response headers\n    response.headers['X-Custom'] = 'value'\n  })\n})\n```\n\n**Practical Example:** Inject a CSP nonce into the HTML head and also into inline scripts. Use `render:html` hook to read the nonce from event context and add to each script tag.\n\n**Common Mistakes:** Assuming `render:html` runs only once per request (it does, but only for the main HTML, not for sub-resources). Modifying the HTML stream after it has started streaming can break the stream; use `render:html` for head modifications only.\n\n**Edge Cases:** When using `payloadExtraction: true`, the payload is not in the initial HTML but loaded separately. The `render:html` hook still runs, but the payload script tag is omitted. You can manually add it if needed.\n\n**Interview Follow-ups:** \"How does Nitro handle concurrent SSR requests?\" \"What is the difference between `render:html` and `render:response` hooks?\"\n\n**Best Practices:** Use `render:html` for injecting global meta tags or preload links. Use `render:response` for setting cache headers or cookies. Avoid heavy computation in these hooks as they block rendering.\n\n**Performance Considerations:** The render pipeline is highly optimized. The biggest bottleneck is usually `useAsyncData` calls. Use `lazy: true` to unblock streaming.\n\n**SEO Considerations:** The full HTML is generated before sending, so crawlers see everything.\n\n**Production Recommendations:** Monitor the time spent in `render:html` hooks; keep them fast. For large sites, consider using CDN caching to bypass the render pipeline entirely.\n\n**Latest Nuxt Patterns:** Nuxt 3.5+ supports `experimental.renderJsonPayloads` which changes how payload is serialized. The pipeline adapts accordingly.\n\n**TypeScript Example:**\n```ts\nexport default defineNitroPlugin((nitroApp) => {\n  nitroApp.hooks.hook('render:html', (html, { event }) => {\n    const nonce = event.context.nonce\n    html.head.forEach(line => {\n      \u002F\u002F modify script tags with nonce\n    })\n  })\n})\n```\n\n**Interview Tip:** Emphasize that understanding this pipeline allows you to hook into critical points for advanced optimizations like edge-side includes or custom CDN purging.\n\n**Common Follow-up:** \"How would you implement a custom 404 page using the render pipeline?\"\n\n**Real-world Example:** A travel website needed to add a `X-Request-ID` header to every response for tracing. They implemented a Nitro plugin that hooks into `render:response` and adds the header from `event.context.requestId`. This avoided modifying every API endpoint and SSR page individually.",[38,584,585,586,356],"render-pipeline","vue-ssr","hooks","Emphasize that understanding this pipeline allows you to hook into critical points for advanced optimizations like edge-side includes or custom CDN purging.","How would you implement a custom 404 page using the render pipeline?","A travel website needed to add a `X-Request-ID` header to every response for tracing. They implemented a Nitro plugin that hooks into `render:response` and adds the header from `event.context.requestId`. This avoided modifying every API endpoint and SSR page individually.",{"id":122,"category":591,"question":592,"answer":593,"level":364,"tags":594,"interviewTip":598,"commonFollowUp":599,"realWorldExample":600},"Edge Rendering","What are the limitations and advanced techniques for running Nuxt on edge runtimes (Cloudflare Workers, Vercel Edge)?","**Concept Explanation:** Edge runtimes are lightweight JavaScript environments running on CDN nodes, with constraints: no `fs` or `net` modules, limited CPU time (e.g., 10ms on Cloudflare Workers), limited memory (128-256MB), and no child processes. Nuxt can run on edge via Nitro presets (`cloudflare`, `vercel-edge`), but you must adapt: use `useStorage` with edge-compatible drivers, avoid large synchronous computations, and leverage edge-specific APIs (e.g., `Cache API`, `KV`).\n\n**Internal Working:** Nitro generates a single JavaScript file that includes all server code, statically linked. The edge runtime executes this file per request (or reuses context across requests). Nitro's `event` object is mapped to the platform's request\u002Fresponse. Storage drivers like `cloudflare-kv` or `vercel-kv` are provided. Nitro also supports `cf` properties (Cloudflare) and `waitUntil` for background tasks.\n\n**Request Flow (Edge):** 1) User request hits edge node. 2) Edge runtime invokes Nitro handler. 3) Handler runs SSR\u002FAPI logic. 4) Response returned from edge. No origin server involved.\n\n**Lifecycle:** Edge workers can be long-lived (reused across requests) but may be evicted at any time. State must be stored externally (KV, database).\n\n**Syntax & Code Example (Cloudflare Workers):**\n`nuxt.config.ts`:\n```ts\nexport default defineNuxtConfig({\n  nitro: {\n    preset: 'cloudflare',\n    cloudflare: {\n      pages: true, \u002F\u002F deploy to Cloudflare Pages\n      bindings: {\n        MY_KV: true \u002F\u002F define KV namespace\n      }\n    }\n  }\n})\n```\nUsing Cloudflare KV:\n```ts\n\u002F\u002F server\u002Fapi\u002Fkv.ts\nexport default defineEventHandler(async (event) => {\n  const kv = event.context.cloudflare?.env?.MY_KV\n  if (!kv) return { error: 'KV not bound' }\n  const value = await kv.get('key')\n  return { value }\n})\n```\n\n**Practical Example:** Deploy a global blog to Cloudflare Workers. Use KV to store blog posts and edge caching to serve them with \u003C20ms latency worldwide.\n\n**Common Mistakes:** Using Node.js modules (`fs`, `path`, `crypto`) – will fail. Performing heavy computations (e.g., image processing) – may exceed CPU limits. Forgetting that `console.log` may be async and not flushed. Using `setTimeout` or `setInterval` without `event.waitUntil` to keep the worker alive.\n\n**Edge Cases:** Cold starts on edge are usually \u003C5ms, but if your bundle is large (>1MB), it may be slower. Some edge runtimes have different Web API implementations (e.g., `Headers` object differences). Websockets are not universally supported.\n\n**Interview Follow-ups:** \"How do you handle database connections from the edge?\" \"What is the maximum bundle size for Vercel Edge?\"\n\n**Best Practices:** Keep the nitro bundle small (\u003C1MB). Use edge-compatible storage (KV, D1, PostgreSQL via HTTP). Leverage `waitUntil` for analytics or logging that shouldn't block response. Cache aggressively using `Cache-Control` or the platform's cache API.\n\n**Performance Considerations:** Edge rendering is extremely fast for dynamic content, but CPU time is limited. For complex SSR (e.g., heavy Vue components), you may need to move to Node.js server. Use `lazy` components to reduce initial render work.\n\n**SEO Considerations:** Edge responses have very low latency, which improves Core Web Vitals and crawl budget.\n\n**Production Recommendations:** Use `cloudflare` preset for global distribution. For Vercel, prefer `vercel-edge` over `vercel` for lower latency. Test with `wrangler` locally before deploying.\n\n**Latest Nuxt Patterns:** Nitro 2 supports `preset: 'cloudflare-pages'` for integrated Pages + Workers. Also supports `cloudflare-modules` for Workers.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F server\u002Fapi\u002Fcf.ts – accessing Cloudflare context\nexport default defineEventHandler((event) => {\n  const cf = event.context.cloudflare?.cf\n  const country = cf?.country\n  return { country }\n})\n```\n\n**Interview Tip:** Emphasize that edge is not a silver bullet – it's best for dynamic content that is mostly read-heavy and can be cached. For write-heavy or compute-heavy operations, use traditional Node.js.\n\n**Common Follow-up:** \"How do you implement authentication on the edge?\" (Use JWT with KV, or external auth service)\n\n**Real-world Example:** A weather app deployed to Cloudflare Workers. The app fetches weather data from an external API, caches responses in KV for 10 minutes, and serves from edge. The SSR renders the page with cached data, and client-side JS handles interactive maps. Edge response time: 15ms globally, compared to 200ms from a single-region server.",[573,595,596,597,432],"cloudflare","vercel-edge","serverless","Emphasize that edge is not a silver bullet – it's best for dynamic content that is mostly read-heavy and can be cached. For write-heavy or compute-heavy operations, use traditional Node.js.","How do you implement authentication on the edge?","A weather app deployed to Cloudflare Workers. The app fetches weather data from an external API, caches responses in KV for 10 minutes, and serves from edge. The SSR renders the page with cached data, and client-side JS handles interactive maps. Edge response time: 15ms globally, compared to 200ms from a single-region server.",{"id":132,"category":602,"question":603,"answer":604,"level":364,"tags":605,"interviewTip":609,"commonFollowUp":610,"realWorldExample":611},"Composable Architecture","How can you design advanced composable patterns in Nuxt, including factories, dependency injection, and lifecycle-aware composables?","**Concept Explanation:** Advanced composable patterns go beyond simple reactive functions. You can create composable factories (functions that return composables), dependency injection (using `provide`\u002F`inject` within Nuxt's context), and lifecycle-aware composables that hook into Nuxt's lifecycle (via `onNuxtReady`, `useNuxtApp` hooks). These patterns enable code reuse, testability, and separation of concerns.\n\n**Internal Working:** Nuxt's auto-import system scans `composables\u002F` and makes them available. You can use `provide`\u002F`inject` within composables because they run in the same component context. Lifecycle hooks like `onNuxtReady` (client-only) or `useNuxtApp().hook('page:finish')` allow composables to react to navigation events. Composables can also be async and use `useAsyncData`.\n\n**Syntax & Code Examples:**\n**Composable factory:**\n```ts\n\u002F\u002F composables\u002Ffactory\u002FcreateApiClient.ts\nexport const createApiClient = (baseURL: string) => {\n  return () => {\n    const config = useRuntimeConfig()\n    const client = $fetch.create({ baseURL: baseURL || config.public.apiBase })\n    return {\n      get: \u003CT>(url: string) => client\u003CT>(url),\n      post: \u003CT>(url: string, body: any) => client\u003CT>(url, { method: 'POST', body })\n    }\n  }\n}\n\u002F\u002F Usage in component: const api = createApiClient('\u002Fapi')()\n```\n\n**Dependency injection composable:**\n```ts\n\u002F\u002F composables\u002FuseFeatureFlag.ts\nconst featureFlagsSymbol = Symbol('featureFlags')\n\nexport const provideFeatureFlags = (flags: Record\u003Cstring, boolean>) => {\n  provide(featureFlagsSymbol, flags)\n}\n\nexport const useFeatureFlag = (name: string) => {\n  const flags = inject(featureFlagsSymbol, {})\n  return computed(() => flags[name] ?? false)\n}\n```\n\n**Lifecycle-aware composable:**\n```ts\n\u002F\u002F composables\u002FusePageAnalytics.ts\nexport const usePageAnalytics = (pageName?: string) => {\n  const route = useRoute()\n  let lastPage = ''\n\n  onMounted(() => {\n    \u002F\u002F Send page view on mount\n    sendAnalytics(route.path)\n  })\n\n  \u002F\u002F Listen to route changes (client-side navigation)\n  watch(() => route.path, (newPath, oldPath) => {\n    if (oldPath) sendAnalytics(newPath)\n  })\n\n  useNuxtApp().hook('page:finish', () => {\n    \u002F\u002F Alternative: Nuxt's page transition hook\n    console.log('Page transition finished')\n  })\n\n  const sendAnalytics = (path: string) => {\n    if (process.client) {\n      \u002F\u002F Send to analytics service\n    }\n  }\n}\n```\n\n**Practical Example:** A `useDataTable` composable that accepts columns, data, pagination, sorting, and filtering options, returning computed and methods for UI. Used across multiple admin pages.\n\n**Common Mistakes:** Providing values in a composable that is called multiple times (causes multiple providers). Forgetting that `inject` works only within the component tree; if composable is called outside (e.g., in a plugin without a Vue instance), it fails.\n\n**Edge Cases:** Async composables that use `useAsyncData` cannot be called conditionally (must be at top level). Composables that use `onMounted` will not run on server (fine). Circular dependencies between composables cause auto-import issues; use explicit imports or restructure.\n\n**Interview Follow-ups:** \"How do you test composables that use Nuxt composables?\" \"Can you create a composable that overrides default `useFetch` behavior?\"\n\n**Best Practices:** Name factories with `create*` prefix. Use `Symbol` for injection keys to avoid collisions. Keep composables pure when possible (no side effects unless documented). Use `readonly` for exposed refs to prevent external mutation.\n\n**Performance Considerations:** Composables are lightweight; however, creating many reactive dependencies can impact performance. Use `shallowRef` for large objects.\n\n**SEO Considerations:** Not relevant.\n\n**Production Recommendations:** Group related composables in subdirectories (e.g., `composables\u002Fanalytics\u002F`, `composables\u002Fui\u002F`). Use TypeScript for better intellisense.\n\n**Latest Nuxt Patterns:** Nuxt 3 supports composables that return `AsyncData` objects. You can also use `composables\u002F` with `.client.ts` suffix for client-only composables.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F Generic factory with type safety\nexport const createStateFactory = \u003CT>(initial: T) => {\n  return (key: string) => {\n    return useState\u003CT>(key, () => initial)\n  }\n}\n```\n\n**Interview Tip:** Emphasize that advanced composable patterns separate business logic from UI components, making your Nuxt app more maintainable and testable. This is a mark of senior-level architecture.\n\n**Common Follow-up:** \"How do you share composables across different Nuxt apps?\" (Use layers or npm packages)\n\n**Real-world Example:** A large SaaS platform had 20+ pages with complex forms. They created a `useForm` composable that handled validation, submission, loading states, and error handling. Each page only needed to define fields and submit handler. The composable was reused across all forms, reducing code duplication by 70% and ensuring consistent behavior.",[174,606,607,608,356],"patterns","factory","dependency-injection","Emphasize that advanced composable patterns separate business logic from UI components, making your Nuxt app more maintainable and testable. This is a mark of senior-level architecture.","How do you share composables across different Nuxt apps?","A large SaaS platform had 20+ pages with complex forms. They created a `useForm` composable that handled validation, submission, loading states, and error handling. Each page only needed to define fields and submit handler. The composable was reused across all forms, reducing code duplication by 70% and ensuring consistent behavior.",{"id":145,"category":613,"question":614,"answer":615,"level":364,"tags":616,"interviewTip":620,"commonFollowUp":621,"realWorldExample":622},"Plugin Internals","How do you create advanced Nuxt modules (plugins) with hooks, templates, and programmatic generation?","**Concept Explanation:** Nuxt modules are the most powerful way to extend Nuxt. They can add hooks, generate virtual files (templates), modify the Nuxt configuration, add server routes, and integrate with the build process. Advanced modules leverage the `nuxt` kit to manipulate the Nuxt instance at various lifecycle stages (setup, build, ready, close).\n\n**Internal Working:** A module is a function that receives `nuxt` (Nuxt instance) and `options`. It can use `addPlugin`, `addTemplate`, `addImports`, `addServerHandler`, `addComponent`, etc. Templates are `.ejs` or `.ts` files that are compiled into the `.nuxt` directory. Hooks allow reacting to events like `build:done`, `pages:extend`, or `nitro:config`. The module system runs during `nuxt build` and `nuxt dev`.\n\n**Lifecycle:** 1) Nuxt loads config. 2) Modules are executed in order. 3) Each module can register hooks. 4) Nuxt proceeds to build. 5) Hooks fire at appropriate times.\n\n**Syntax & Code Example (basic module):**\n`modules\u002Fmy-module\u002Findex.ts`:\n```ts\nimport { defineNuxtModule, addPlugin, addTemplate, addImports } from '@nuxt\u002Fkit'\n\nexport default defineNuxtModule({\n  meta: {\n    name: 'my-module',\n    configKey: 'myModule'\n  },\n  defaults: { enabled: true },\n  setup(options, nuxt) {\n    \u002F\u002F Add a plugin\n    addPlugin({ src: resolve('.\u002Fruntime\u002Fplugin.client.ts'), mode: 'client' })\n    \n    \u002F\u002F Generate a virtual file from template\n    const template = addTemplate({\n      filename: 'my-config.mjs',\n      getContents: () => `export default ${JSON.stringify(options)}`\n    })\n    \n    \u002F\u002F Add auto-imports\n    addImports([{ name: 'useMyFeature', from: template.dst }])\n    \n    \u002F\u002F Add server route\n    addServerHandler({\n      route: '\u002Fapi\u002Fmy-endpoint',\n      handler: resolve('.\u002Fruntime\u002Fapi\u002Fmy-endpoint.ts')\n    })\n    \n    \u002F\u002F Hook into Nuxt lifecycle\n    nuxt.hook('pages:extend', (pages) => {\n      pages.push({ name: 'custom', path: '\u002Fcustom', file: resolve('.\u002Fruntime\u002Fpages\u002Fcustom.vue') })\n    })\n    \n    \u002F\u002F Modify Nitro config\n    nuxt.hook('nitro:config', (nitroConfig) => {\n      nitroConfig.storage = nitroConfig.storage || {}\n      nitroConfig.storage.myCache = { driver: 'memory' }\n    })\n  }\n})\n```\n\n**Practical Example:** Create a module that auto-generates API routes for each model in a database, similar to Strapi. The module scans a `models\u002F` directory and creates CRUD endpoints.\n\n**Common Mistakes:** Not using `@nuxt\u002Fkit` functions (e.g., using `fs` directly to write to `.nuxt` may conflict). Forgetting to resolve paths with `resolve` (relative to module). Not handling HMR for templates (templates are not hot-reloaded; require restart).\n\n**Edge Cases:** Modules can depend on other modules; use `nuxt.options.modules` to check. Modules can also be published to npm. Template contents can be functions that receive build-time data.\n\n**Interview Follow-ups:** \"How do you test a Nuxt module?\" \"What is the difference between `addPlugin` and `addImports`?\"\n\n**Best Practices:** Use `defineNuxtModule` for type safety. Provide sensible defaults. Document module options. Use `resolve` for all file paths. Keep runtime code separate from build-time code.\n\n**Performance Considerations:** Modules run at build time, not runtime, so they don't affect request performance. However, generating many virtual files can slow down build.\n\n**SEO Considerations:** Not relevant.\n\n**Production Recommendations:** Use `nuxtModule`'s `install` hook for per-install prompts. Publish to npm with `module` condition for ESM.\n\n**Latest Nuxt Patterns:** Nuxt 3 modules can use `addImportsSources` for advanced auto-imports. Also, `addTypeTemplate` for generating TypeScript definitions.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F With typed options\nexport interface ModuleOptions {\n  apiPrefix?: string\n}\nexport default defineNuxtModule\u003CModuleOptions>({\n  setup(options, nuxt) {\n    \u002F\u002F options.apiPrefix is typed\n  }\n})\n```\n\n**Interview Tip:** Emphasize that building a custom module is the ultimate way to encapsulate complex logic and share it across multiple Nuxt projects. Many official features (like `@nuxt\u002Fimage`) are implemented as modules.\n\n**Common Follow-up:** \"How do you add a Nitro plugin from a Nuxt module?\"\n\n**Real-world Example:** A company with 10 different Nuxt apps needed consistent authentication and theming. They built an internal `@company\u002Fnuxt-auth` module that added login pages, protected route middleware, and a `useAuth` composable. Each app just added the module to `modules` and configured a few options. This reduced setup time from days to minutes.",[617,243,586,618,619],"modules","templates","nuxt-kit","Emphasize that building a custom module is the ultimate way to encapsulate complex logic and share it across multiple Nuxt projects. Many official features (like `@nuxt\u002Fimage`) are implemented as modules.","How do you add a Nitro plugin from a Nuxt module?","A company with 10 different Nuxt apps needed consistent authentication and theming. They built an internal `@company\u002Fnuxt-auth` module that added login pages, protected route middleware, and a `useAuth` composable. Each app just added the module to `modules` and configured a few options. This reduced setup time from days to minutes.",{"id":157,"category":624,"question":625,"answer":626,"level":364,"tags":627,"interviewTip":628,"commonFollowUp":629,"realWorldExample":630},"Hydration Mismatch","What are the advanced techniques to debug and fix hydration mismatches in complex Nuxt applications?","**Concept Explanation:** Hydration mismatches occur when the client-side virtual DOM doesn't match the server-rendered HTML. While basic mismatches are easy to fix (e.g., `process.client` checks), advanced mismatches can be caused by third-party libraries, dynamic imports, time-based content, or reactive data that differs between server and client. Debugging requires deep inspection of the generated HTML, understanding Vue's hydration algorithm, and sometimes patching libraries.\n\n**Internal Working:** Vue's hydration process compares the existing DOM (server HTML) with the new VDOM. It expects the structure and content to be identical. If a mismatch is found, Vue discards the server-rendered DOM for that node and its children and replaces it with client-rendered content. This can cause layout shifts, loss of event listeners, and performance degradation.\n\n**Debugging Techniques:**\n1. **Enable detailed warnings:** In development, Vue logs mismatches to console with the expected and actual DOM.\n2. **Use `vue-devtools`** to inspect the component tree and see which component caused the mismatch.\n3. **Compare HTML snapshots:** Run `curl` on the SSR endpoint and save the HTML, then compare with client-generated HTML using `diff`.\n4. **Use `ssr: false` incrementally:** Temporarily disable SSR for suspicious components to isolate the mismatch.\n5. **Log server vs client state:** Add `console.log` with `process.server` and `process.client` to compare data.\n6. **Use `v-once` or `v-memo`** to prevent reactivity on static parts that might differ.\n\n**Advanced Fixes:**\n```vue\n\u003Ctemplate>\n  \u003Cdiv>\n    \u003C!-- Fix 1: Use ClientOnly wrapper for problematic third-party component -->\n    \u003CClientOnly>\n      \u003CHeavyChart \u002F>\n      \u003Ctemplate #fallback>\n        \u003Cdiv class=\"skeleton\">Loading chart...\u003C\u002Fdiv>\n      \u003C\u002Ftemplate>\n    \u003C\u002FClientOnly>\n\n    \u003C!-- Fix 2: Use `v-if` with `process.client` and provide a stable server placeholder -->\n    \u003Cdiv v-if=\"process.client\">{{ clientTime }}\u003C\u002Fdiv>\n    \u003Cdiv v-else>--:--\u003C\u002Fdiv>\n\n    \u003C!-- Fix 3: Use `:key` to force remount on client if mismatch is inevitable -->\n    \u003CClientOnly :key=\"Math.random()\">\n      \u003CWidget \u002F>\n    \u003C\u002FClientOnly>\n\n    \u003C!-- Fix 4: Defer hydration using `useDefer` composable -->\n    \u003Cdiv v-if=\"defer(2)\">\n      \u003CComponentThatUsesLocalStorage \u002F>\n    \u003C\u002Fdiv>\n  \u003C\u002Fdiv>\n\u003C\u002Ftemplate>\n\u003Cscript setup>\n\u002F\u002F Custom defer composable\nconst useDefer = (maxFrame = 30) => {\n  const frame = ref(0)\n  if (process.client) {\n    const update = () => {\n      requestAnimationFrame(() => {\n        frame.value++\n        if (frame.value \u003C maxFrame) update()\n      })\n    }\n    update()\n  }\n  return (n) => frame.value >= n\n}\nconst defer = useDefer()\n\u003C\u002Fscript>\n```\n\n**Practical Example:** A component that displays a random quote using `Math.random()`. On server, it picks one quote; on client, another. The mismatch causes the quote to jump after hydration. Fix: Use `ClientOnly` or seed the random generator with a stable seed.\n\n**Common Mistakes:** Overusing `ClientOnly` – it defeats SSR for that component. Not providing fallback skeletons causes layout shift. Ignoring mismatches because they don't break visibly – they still hurt performance.\n\n**Edge Cases:** Third-party libraries that modify the DOM directly (e.g., some carousels, maps) will almost always cause mismatches. Wrap them in `\u003CClientOnly>`. Also, components that use `useRoute().query` without default values – query is empty on server if not in URL.\n\n**Interview Follow-ups:** \"How do you fix a mismatch caused by a third-party library that you cannot modify?\" \"What is the performance impact of a hydration mismatch?\"\n\n**Best Practices:** Design your components to be deterministic (same output for same props). Avoid `Math.random()`, `Date.now()`, `new Date()` in templates or setup. Use `useAsyncData` with `key` to ensure same data on server\u002Fclient. Test your app with `javascript: false` (disable JS) to see what crawlers see.\n\n**Performance Considerations:** Hydration mismatches cause Vue to discard server-rendered DOM, leading to a full client render. This can increase TTI by 2-5x.\n\n**SEO Considerations:** Mismatches do not affect the initial HTML sent to crawlers, so SEO is safe. However, the client-side flicker may affect user experience.\n\n**Production Recommendations:** Use `@nuxtjs\u002Fgoogle-fonts` which avoids hydration mismatches by generating fonts properly. Set `ssr: false` for pages with unavoidable mismatches. Use `normalize` props on UI libraries.\n\n**Latest Nuxt Patterns:** Nuxt 3's `useDefer` pattern is experimental. Also, `experimental.clientFallback` component allows client-only fallback with lazy hydration.\n\n**TypeScript Example:** Not applicable.\n\n**Interview Tip:** Emphasize that hydration mismatches are not just warnings – they are performance issues. A senior developer should systematically track and fix them, not ignore them.\n\n**Common Follow-up:** \"How do you test for hydration mismatches in CI?\"\n\n**Real-world Example:** A large e-commerce site had a product carousel that used `Math.random()` for unique IDs. This caused hydration mismatches on every product page, leading to a 300ms increase in TTI. They replaced the random ID with a deterministic one based on product ID + index, eliminating mismatches and improving performance.",[473,474,475,354,432],"Emphasize that hydration mismatches are not just warnings – they are performance issues. A senior developer should systematically track and fix them, not ignore them.","How do you test for hydration mismatches in CI?","A large e-commerce site had a product carousel that used `Math.random()` for unique IDs. This caused hydration mismatches on every product page, leading to a 300ms increase in TTI. They replaced the random ID with a deterministic one based on product ID + index, eliminating mismatches and improving performance.",{"id":169,"category":632,"question":633,"answer":634,"level":364,"tags":635,"interviewTip":641,"commonFollowUp":642,"realWorldExample":643},"Advanced SEO","How do you implement advanced SEO strategies in Nuxt at scale, including dynamic sitemaps, hreflang, structured data, and crawl optimization?","**Concept Explanation:** Advanced SEO goes beyond basic meta tags. It includes: dynamic sitemap generation (for thousands of pages), hreflang tags for multilingual sites, structured data (JSON-LD) for rich snippets, crawl budget optimization (controlling which pages are crawled), and canonical URLs for duplicate content. Nuxt provides tools like `@nuxtjs\u002Fsitemap`, `@nuxtjs\u002Frobots`, and `useHead` for JSON-LD. At scale, you need server-generated sitemaps and efficient crawling strategies.\n\n**Internal Working:** Sitemap modules can generate static XML files at build time, but for large sites (10k+ pages), you need dynamic sitemaps generated on-the-fly via Nitro routes. Hreflang tags are added to `\u003Chead>` using `useHead` with computed values. Structured data can be injected via `useHead` with `script` tags (JSON-LD). Crawl optimization uses `robots.txt`, `X-Robots-Tag`, and `link` headers for pagination.\n\n**Syntax & Code Examples:**\n**Dynamic sitemap (server route):**\n`server\u002Fapi\u002Fsitemap.xml.get.ts`:\n```ts\nexport default defineEventHandler(async (event) => {\n  const baseUrl = 'https:\u002F\u002Fexample.com'\n  const products = await getProductsFromDB() \u002F\u002F thousands of products\n  const urls = products.map(p => `\n    \u003Curl>\n      \u003Cloc>${baseUrl}\u002Fproduct\u002F${p.id}\u003C\u002Floc>\n      \u003Clastmod>${p.updatedAt}\u003C\u002Flastmod>\n      \u003Cpriority>0.8\u003C\u002Fpriority>\n    \u003C\u002Furl>\n  `).join('')\n  const xml = `\u003C?xml version=\"1.0\" encoding=\"UTF-8\"?>\n    \u003Curlset xmlns=\"http:\u002F\u002Fwww.sitemaps.org\u002Fschemas\u002Fsitemap\u002F0.9\">\n      ${urls}\n    \u003C\u002Furlset>`\n  setHeader(event, 'Content-Type', 'application\u002Fxml')\n  return xml\n})\n```\n\n**Hreflang with useHead:**\n```vue\n\u003Cscript setup>\nconst route = useRoute()\nconst { data: page } = await useFetch(`\u002Fapi\u002Fpage\u002F${route.params.slug}`)\n\nconst hreflangLinks = computed(() => {\n  if (!page.value) return []\n  return page.value.localizations.map(loc => ({\n    rel: 'alternate',\n    href: `https:\u002F\u002Fexample.com\u002F${loc.lang}${loc.path}`,\n    hreflang: loc.lang\n  }))\n})\nuseHead({\n  link: () => hreflangLinks.value\n})\n\u003C\u002Fscript>\n```\n\n**Structured data (JSON-LD):**\n```vue\n\u003Cscript setup>\nconst product = await $fetch('\u002Fapi\u002Fproduct\u002F1')\nconst jsonLd = {\n  '@context': 'https:\u002F\u002Fschema.org',\n  '@type': 'Product',\n  name: product.name,\n  image: product.image,\n  offers: {\n    '@type': 'Offer',\n    price: product.price,\n    priceCurrency: 'USD'\n  }\n}\nuseHead({\n  script: [\n    {\n      type: 'application\u002Fld+json',\n      children: JSON.stringify(jsonLd)\n    }\n  ]\n})\n\u003C\u002Fscript>\n```\n\n**Practical Example:** A global e-commerce site with 500k products, 10 languages. Dynamic sitemap splits into multiple sitemaps (products_sitemap.xml, categories_sitemap.xml) and a sitemap index. Hreflang tags ensure users are directed to correct language version. Structured data enables rich product snippets in search results.\n\n**Common Mistakes:** Generating sitemap at build time for dynamic content (stale data). Not using `lastmod` causing crawlers to re-crawl unchanged pages. Overloading `robots.txt` with `Disallow` rules that block important pages. Forgetting to set canonical URLs for duplicate content (e.g., pagination, sort parameters).\n\n**Edge Cases:** For sites with >50k pages, use multiple sitemap files and a sitemap index. For JavaScript-rendered content, use `nuxt generate` for critical pages. Hreflang conflicts (same page with multiple hreflang) can cause Google to ignore them.\n\n**Interview Follow-ups:** \"How do you handle pagination SEO with `prev`\u002F`next` links?\" \"What is crawl budget and how do you optimize it?\"\n\n**Best Practices:** Use `@nuxtjs\u002Fsitemap` module for static sitemaps; for dynamic, implement Nitro routes as above. Use `useServerSeoMeta` for server-only meta (to avoid client-side flashes). Validate structured data with Google's Rich Results Test.\n\n**Performance Considerations:** Dynamic sitemaps can be heavy; cache them with `defineCachedEventHandler`. Use `sitemap` route rule with `swr: 86400`.\n\n**SEO Considerations:** Proper sitemaps and hreflang directly improve indexing. Structured data increases CTR. Crawl budget optimization prevents Google from wasting time on low-value pages (e.g., filters, sort pages).\n\n**Production Recommendations:** Submit sitemap URLs to Google Search Console. Monitor crawl stats in Search Console. Use `X-Robots-Tag: noindex` for low-value pages. Implement `rel=canonical` for all pages.\n\n**Latest Nuxt Patterns:** Nuxt 3 + `@nuxtjs\u002Fsitemap` v5 supports hybrid sitemaps (static + dynamic). Also, `nuxt-seo-kit` provides an all-in-one solution.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F types for JSON-LD\ninterface ProductJsonLd {\n  '@context': 'https:\u002F\u002Fschema.org'\n  '@type': 'Product'\n  name: string\n  \u002F\u002F ...\n}\n```\n\n**Interview Tip:** Emphasize that advanced SEO is not just about adding tags; it's about infrastructure (sitemap generation, handling scale) and strategy (crawl budget, canonicalization).\n\n**Common Follow-up:** \"How do you implement dynamic canonical URLs for user-generated content?\"\n\n**Real-world Example:** A job board with 1 million job listings. They implemented a dynamic sitemap that splits into 100 sitemap files (10k jobs each), regenerated daily via a cron job (using `nuxi generate` and uploading to CDN). Hreflang tags for 20 countries. Structured data for job postings. As a result, their indexed pages increased by 300% and organic traffic doubled.",[26,636,637,638,639,640],"sitemap","hreflang","structured-data","crawl-budget","canonical","Emphasize that advanced SEO is not just about adding tags; it's about infrastructure (sitemap generation, handling scale) and strategy (crawl budget, canonicalization).","How do you implement dynamic canonical URLs for user-generated content?","A job board with 1 million job listings. They implemented a dynamic sitemap that splits into 100 sitemap files (10k jobs each), regenerated daily via a cron job (using `nuxi generate` and uploading to CDN). Hreflang tags for 20 countries. Structured data for job postings. As a result, their indexed pages increased by 300% and organic traffic doubled.",{"id":181,"category":645,"question":646,"answer":647,"level":364,"tags":648,"interviewTip":651,"commonFollowUp":652,"realWorldExample":653},"Scaling","How do you scale a Nuxt application to handle millions of requests per day?","**Concept Explanation:** Scaling Nuxt involves horizontal scaling (multiple server instances), load balancing, caching (CDN, Redis), database optimization, and efficient SSR. At high traffic, SSR can become a bottleneck. Strategies include: using static generation for most pages, deploying to serverless for auto-scaling, using edge rendering for low latency, implementing robust caching, and offloading long-running tasks to queues.\n\n**Internal Working:** Nuxt (via Nitro) is stateless by default – each request is independent. This allows horizontal scaling: deploy multiple instances behind a load balancer. For serverless (AWS Lambda, Vercel Functions), each request may spin up a new instance, automatically scaling to traffic. For Node.js servers, use `cluster` or process managers (PM2) with `-i max`.\n\n**Scaling Strategies:**\n1. **Static-first:** Use `routeRules: { '\u002Fproducts\u002F**': { static: true } }` to pre-render all product pages. Only dynamic pages (cart, checkout) hit the server.\n2. **CDN + SWR:** Use `swr: 3600` on dynamic pages so CDN caches responses; revalidate in background.\n3. **Database connection pooling:** Use `pg` pool or Prisma with connection limit to avoid exhausting DB connections.\n4. **Queue background jobs:** For emails, PDF generation, use BullMQ with Redis.\n5. **Rate limiting:** Protect against abuse using Nitro middleware.\n\n**Syntax & Code Example (scaling with PM2 cluster):**\n```bash\n# Start 8 instances\npm2 start .output\u002Fserver\u002Findex.mjs -i 8 --name nuxt-app\n```\n\n**Serverless auto-scaling (Vercel):** No config needed; each request is isolated.\n**Redis for session store:**\n```ts\n\u002F\u002F server\u002Fapi\u002FuseSession.ts\nimport { createClient } from 'redis'\nconst redis = createClient({ url: process.env.REDIS_URL })\nexport default defineEventHandler(async (event) => {\n  const sessionId = getCookie(event, 'sessionId')\n  const session = await redis.get(`session:${sessionId}`)\n  \u002F\u002F ...\n})\n```\n\n**Practical Example:** A e-commerce site with 5M daily page views. 80% of pages (product listings) are static (pre-rendered daily). 15% (product detail) are SWR-cached for 1 hour. 5% (cart, checkout) are dynamic SSR with database calls. They deployed to 20 Node.js instances with load balancer and Redis for session sharing.\n\n**Common Mistakes:** Using in-memory session storage (breaks horizontal scaling). Not implementing connection pooling (exhausts DB). Over-caching user-specific data (showing wrong data). Not monitoring memory usage (leads to OOM crashes).\n\n**Edge Cases:** Serverless cold starts at high traffic – mitigated by provisioned concurrency (AWS) or edge workers. Database scaling: read replicas for queries, separate write master. File uploads: store in S3, not on server filesystem.\n\n**Interview Follow-ups:** \"How do you handle WebSocket connections at scale?\" \"What is the maximum throughput of a single Nuxt SSR instance?\"\n\n**Best Practices:** Use stateless design. Implement caching at all levels (browser, CDN, server, database). Use a process manager for Node.js deployments. Monitor metrics (requests per second, error rate, memory).\n\n**Performance Considerations:** A single Node.js instance can handle ~1000-3000 requests per second for simple pages, less for complex SSR. Scale horizontally as needed. Use `autoscaling` in Kubernetes or serverless.\n\n**SEO Considerations:** Scaling doesn't directly affect SEO, but downtime (from overload) will hurt rankings.\n\n**Production Recommendations:** Start with static + SWR for most pages. Use serverless for unpredictable traffic. For steady high traffic, use dedicated Node.js clusters with a CDN cache. Always use a reverse proxy (Nginx, Cloudflare) in front.\n\n**Latest Nuxt Patterns:** Nitro's `preset: 'vercel'` auto-scales. `preset: 'aws-lambda'` with `concurrency: 1000` for provisioned concurrency. `preset: 'deno'` for edge.\n\n**TypeScript Example:** Not applicable.\n\n**Interview Tip:** Emphasize that scaling is not just about throwing more servers; it's about architectural decisions (static vs dynamic, caching strategy) that reduce load on the origin server.\n\n**Common Follow-up:** \"How do you load test a Nuxt application?\" (Use k6 or Artillery)\n\n**Real-world Example:** A Black Friday sale event saw traffic spike from 10k to 2M requests per minute. The site had pre-generated all product pages as static HTML (`static: true`), used CDN caching for the homepage, and only the checkout page was dynamic. This reduced server load to \u003C1% of total traffic. The checkout page used Redis session store across 100 auto-scaling serverless instances, handling the spike without downtime.",[575,432,649,597,442,650],"load-balancing","database","Emphasize that scaling is not just about throwing more servers; it's about architectural decisions (static vs dynamic, caching strategy) that reduce load on the origin server.","How do you load test a Nuxt application?","A Black Friday sale event saw traffic spike from 10k to 2M requests per minute. The site had pre-generated all product pages as static HTML (`static: true`), used CDN caching for the homepage, and only the checkout page was dynamic. This reduced server load to \u003C1% of total traffic. The checkout page used Redis session store across 100 auto-scaling serverless instances, handling the spike without downtime.",{"id":192,"category":655,"question":656,"answer":657,"level":364,"tags":658,"interviewTip":662,"commonFollowUp":663,"realWorldExample":664},"SSR Optimization","How do you optimize SSR performance in Nuxt beyond basic caching, including critical CSS, resource hints, and payload pruning?","**Concept Explanation:** SSR optimization aims to reduce Time to First Byte (TTFB), First Contentful Paint (FCP), and Largest Contentful Paint (LCP). Advanced techniques include: inlining critical CSS, preload\u002Fpreconnect hints, deferring non-critical scripts, payload pruning (reducing serialized data), and using `serverPrefetch` for component-level data loading. These optimizations require deep understanding of the browser's parsing and rendering pipeline.\n\n**Internal Working:** During SSR, Nuxt generates HTML and CSS (either extracted or inline). Critical CSS (styles needed for above-the-fold content) can be inlined to avoid extra round trips. Resource hints (`\u003Clink rel=preload>`, `preconnect`) can be added via `useHead`. Payload pruning removes unused fields from serialized data. `serverPrefetch` (Vue 2) is replaced by `useAsyncData` with `lazy: false` (default) – but you can control.\n\n**Syntax & Code Examples:**\n**Inlining critical CSS (manual using vite\u002Frollup):**\n```ts\n\u002F\u002F nuxt.config.ts\nimport criticalCSS from 'vite-plugin-critical-css'\nexport default defineNuxtConfig({\n  vite: {\n    plugins: [\n      criticalCSS({ inline: true })\n    ]\n  }\n})\n```\n\n**Resource hints:**\n```ts\n\u002F\u002F app.vue or plugin\nuseHead({\n  link: [\n    { rel: 'preconnect', href: 'https:\u002F\u002Ffonts.googleapis.com' },\n    { rel: 'preload', href: '\u002Ffonts\u002Fprimary.woff2', as: 'font', crossorigin: '' }\n  ]\n})\n```\n\n**Payload pruning with pick:**\n```ts\nconst { data } = await useFetch('\u002Fapi\u002Fusers', {\n  pick: ['id', 'name'] \u002F\u002F reduces payload by 70%\n})\n```\n\n**Defer non-critical scripts:**\n```ts\nuseHead({\n  script: [\n    { src: '\u002Fanalytics.js', defer: true, async: true }\n  ]\n})\n```\n\n**Lazy load below-the-fold components:**\n```vue\n\u003Ctemplate>\n  \u003CTheHeader \u002F>\n  \u003CLazyComments v-if=\"showComments\" \u002F> \u003C!-- lazy-loaded -->\n\u003C\u002Ftemplate>\n```\n\n**Practical Example:** A news article page: critical CSS inlined (article text, header), preload for hero image, defer for social sharing widgets, payload pruning to send only article text (not raw HTML). FCP improved from 1.8s to 0.9s.\n\n**Common Mistakes:** Inlining too much CSS (increases HTML size). Preloading too many resources (bandwidth waste). Forgetting to set `crossorigin` for font preloads. Over-pruning payload (removing data needed for interactive features).\n\n**Edge Cases:** Critical CSS generation can be tricky with dynamic classes (e.g., Tailwind's generated classes). Use `critters` webpack plugin or `vite-plugin-critical-css` with safe mode.\n\n**Interview Follow-ups:** \"How do you measure CSS coverage in Nuxt?\" \"What is the impact of `defer` vs `async` on LCP?\"\n\n**Best Practices:** Use `@nuxt\u002Fimage` for responsive images with `preload` attribute for LCP image. Inline CSS only for above-the-fold content (less than 14KB). Use `resourceHint` composable from `@nuxtjs\u002Foptimize` module.\n\n**Performance Considerations:** Each optimization adds complexity but can shave off hundreds of milliseconds. Use Lighthouse to measure improvements.\n\n**SEO Considerations:** Faster pages improve Core Web Vitals, a ranking factor.\n\n**Production Recommendations:** Automate critical CSS generation in build pipeline. Monitor LCP field data in Google Search Console. Use `nuxt build --analyze` to find large assets.\n\n**Latest Nuxt Patterns:** Nuxt 3 supports `experimental.inlineSSRStyles` for automatic critical CSS. Also, `vite: { css: { devSourcemap: true } }` for debugging.\n\n**TypeScript Example:** Not applicable.\n\n**Interview Tip:** Emphasize that SSR optimization is not just about server speed; it's about optimizing what the browser receives. Critical CSS and resource hints often yield bigger gains than server-side caching.\n\n**Common Follow-up:** \"How do you implement priority hints (`fetchpriority`) in Nuxt?\"\n\n**Real-world Example:** A SaaS dashboard had a LCP of 3.5s due to a large chart library loaded synchronously. They moved the chart below the fold and lazy-loaded it. They also inlined CSS for the header and preloaded the logo font. LCP improved to 1.2s, and the site passed Core Web Vitals.",[27,454,659,660,496,661],"critical-css","resource-hints","lcp","Emphasize that SSR optimization is not just about server speed; it's about optimizing what the browser receives. Critical CSS and resource hints often yield bigger gains than server-side caching.","How do you implement priority hints (`fetchpriority`) in Nuxt?","A SaaS dashboard had a LCP of 3.5s due to a large chart library loaded synchronously. They moved the chart below the fold and lazy-loaded it. They also inlined CSS for the header and preloaded the logo font. LCP improved to 1.2s, and the site passed Core Web Vitals.",{"id":204,"category":666,"question":667,"answer":668,"level":364,"tags":669,"interviewTip":672,"commonFollowUp":673,"realWorldExample":674},"Server Engine Internals","How does Nitro's event handler lifecycle work? Explain `defineEventHandler`, hooks, and context propagation.","**Concept Explanation:** Nitro's event handler lifecycle is built on `h3`, a minimal HTTP framework. Each request flows through: `defineEventHandler` (core handler), global middleware (in order), route-specific middleware, and finally the route handler. Hooks (`request`, `beforeResponse`, `afterResponse`) allow plugins to intercept. Context (`event.context`) is an object that persists throughout the request and can be used to pass data between middleware and handlers.\n\n**Internal Working:** When a request arrives, Nitro creates an `H3Event` object containing `req`, `res`, `context`, and helper methods. The event passes through a chain of middleware (added via `use` method). Each middleware can modify `event.context` or early-return a response. The matching route handler is executed last. After the handler returns, Nitro applies response hooks and sends the response.\n\n**Request Flow (with middleware):**\n1. Nitro receives request, creates event.\n2. Global middleware (added via `app.use`) runs in order.\n3. Route middleware (e.g., `server\u002Fmiddleware\u002F` files) runs.\n4. Route handler (`defineEventHandler`) runs.\n5. `beforeResponse` hooks run.\n6. Response sent.\n7. `afterResponse` hooks run (for cleanup).\n\n**Lifecycle:** All middleware and handlers are async; Nitro awaits each. Context is unique per request.\n\n**Syntax & Code Example:**\n```ts\n\u002F\u002F server\u002Fmiddleware\u002Flogger.ts\nexport default defineEventHandler((event) => {\n  event.context.startTime = Date.now()\n  \u002F\u002F No return means continue to next middleware\n})\n\n\u002F\u002F server\u002Fmiddleware\u002Fauth.ts\nexport default defineEventHandler((event) => {\n  const token = getCookie(event, 'token')\n  if (!token && event.path.startsWith('\u002Fapi\u002Fprotected')) {\n    throw createError({ statusCode: 401, message: 'Unauthorized' })\n  }\n  event.context.user = { id: 1 }\n})\n\n\u002F\u002F server\u002Fapi\u002Fprotected\u002Findex.get.ts\nexport default defineEventHandler((event) => {\n  const user = event.context.user\n  return { message: `Hello ${user.id}` }\n})\n```\n\n**Using hooks in a plugin:**\n```ts\n\u002F\u002F server\u002Fplugins\u002Fhooks.ts\nexport default defineNitroPlugin((nitroApp) => {\n  nitroApp.hooks.hook('request', (event) => {\n    console.log('Request started', event.path)\n  })\n  nitroApp.hooks.hook('afterResponse', (event, response) => {\n    const duration = Date.now() - event.context.startTime\n    console.log(`Request took ${duration}ms`)\n  })\n})\n```\n\n**Practical Example:** A custom rate-limiting middleware that reads IP from `event.context` (populated by a previous middleware), checks Redis, and returns 429 if exceeded. This is done via middleware before the route handler.\n\n**Common Mistakes:** Not `await`ing async middleware (Nitro will still wait, but errors may be caught incorrectly). Modifying `event.context` with non-serializable values (only needed for internal use). Forgetting that middleware order matters; use file naming to control order.\n\n**Edge Cases:** Middleware can return a response directly (e.g., `return 'hello'`), short-circuiting the pipeline. Throwing `createError` triggers error handler. In serverless, `afterResponse` may run after the response is already sent (useful for logging).\n\n**Interview Follow-ups:** \"How do you add a global error handler?\" \"What is the difference between middleware and hooks?\"\n\n**Best Practices:** Use middleware for cross-cutting concerns (auth, logging, rate limiting). Use hooks for observability (metrics, tracing). Keep middleware fast to avoid blocking.\n\n**Performance Considerations:** Each middleware adds a microsecond overhead. For high-throughput apps, limit to essential middleware.\n\n**SEO Considerations:** Not relevant.\n\n**Production Recommendations:** Use `event.context` to cache per-request computed values (e.g., database connection). Avoid memory leaks by cleaning up any resources in `afterResponse`.\n\n**Latest Nuxt Patterns:** Nitro 2 supports `event.context.waitUntil` for background tasks (similar to Cloudflare Workers). Also, `defineCachedEventHandler` internally uses this lifecycle.\n\n**TypeScript Example:**\n```ts\n\u002F\u002F Augment event context type\ndeclare module 'h3' {\n  interface H3EventContext {\n    user?: { id: number; role: string }\n    startTime?: number\n  }\n}\n```\n\n**Interview Tip:** Emphasize that understanding the Nitro event lifecycle allows you to build complex server features (multi-tenancy, tracing, feature flags) without bloating route handlers.\n\n**Common Follow-up:** \"How do you conditionally apply middleware based on route pattern?\" (Use `event.path` check inside middleware)\n\n**Real-world Example:** An API gateway built with Nitro had 20 microservices behind it. They used global middleware to authenticate (JWT), another to log requests, and a route-specific middleware to transform responses. The `event.context` carried user info, request ID, and timing data through the pipeline, enabling distributed tracing.",[38,670,356,231,586,671],"event-handler","context","Emphasize that understanding the Nitro event lifecycle allows you to build complex server features (multi-tenancy, tracing, feature flags) without bloating route handlers.","How do you conditionally apply middleware based on route pattern?","An API gateway built with Nitro had 20 microservices behind it. They used global middleware to authenticate (JWT), another to log requests, and a route-specific middleware to transform responses. The `event.context` carried user info, request ID, and timing data through the pipeline, enabling distributed tracing.",{"id":214,"category":676,"question":677,"answer":678,"level":364,"tags":679,"interviewTip":685,"commonFollowUp":686,"realWorldExample":687},"Performance Profiling","How do you profile a production Nuxt application for CPU, memory, and request latency using OpenTelemetry and flamegraphs?","**Concept Explanation:** Performance profiling in production involves collecting metrics (CPU usage, memory allocation, request latency) and tracing requests through the system. OpenTelemetry (OTel) provides vendor-agnostic instrumentation. Flamegraphs visualize where time is spent in the code. For Nuxt, you can instrument Nitro server, Vue SSR, and database calls. This helps identify bottlenecks.\n\n**Internal Working:** OpenTelemetry uses auto-instrumentation for Node.js, HTTP, and database drivers. You add the OTel SDK to your Nuxt server. Spans are created for each request, sub-spans for database queries, external API calls, and rendering phases. These spans are exported to a collector (Jaeger, Datadog, New Relic). Flamegraphs are generated from trace data.\n\n**Setup Example (OpenTelemetry with Jaeger):**\n```ts\n\u002F\u002F server\u002Fplugins\u002Fotel.ts\nimport { NodeSDK } from '@opentelemetry\u002Fsdk-node'\nimport { JaegerExporter } from '@opentelemetry\u002Fexporter-jaeger'\nimport { getNodeAutoInstrumentations } from '@opentelemetry\u002Fauto-instrumentations-node'\n\nconst sdk = new NodeSDK({\n  traceExporter: new JaegerExporter({ endpoint: 'http:\u002F\u002Fjaeger:14268\u002Fapi\u002Ftraces' }),\n  instrumentations: [getNodeAutoInstrumentations()]\n})\nsdk.start()\n```\n\n**Manual instrumentation in Nitro handler:**\n```ts\nimport { trace } from '@opentelemetry\u002Fapi'\nconst tracer = trace.getTracer('nuxt-app')\n\nexport default defineEventHandler(async (event) => {\n  return tracer.startActiveSpan('api:products', async (span) => {\n    try {\n      const data = await $fetch('\u002Fexternal-api')\n      return data\n    } finally {\n      span.end()\n    }\n  })\n})\n```\n\n**CPU profiling (flamegraph) using `0x`:**\n```bash\nnpx 0x .output\u002Fserver\u002Findex.mjs\n# Open generated flamegraph.html\n```\n\n**Memory profiling (heap snapshot) in production without stopping:**\n```ts\n\u002F\u002F server\u002Fapi\u002Fdebug\u002Fheap.ts (protected endpoint)\nimport v8 from 'v8'\nexport default defineEventHandler(() => {\n  const snapshot = v8.getHeapSnapshot()\n  setHeader(event, 'Content-Type', 'application\u002Foctet-stream')\n  return snapshot\n})\n```\n\n**Practical Example:** A Nuxt app was slow on product pages. Using OTel traces, they discovered that a `useAsyncData` call to a slow external API was taking 2 seconds. They added a Redis cache, reducing to 50ms.\n\n**Common Mistakes:** Over-instrumenting (too many spans causing performance overhead). Forgetting to flush spans before process exit. Not sampling in high-traffic (use probability sampler).\n\n**Edge Cases:** In serverless, tracing may not work across invocations. Use cloud provider's native tracing (e.g., AWS X-Ray).\n\n**Interview Follow-ups:** \"How do you profile the Vue SSR rendering phase specifically?\" \"What is the overhead of OpenTelemetry?\"\n\n**Best Practices:** Sample 1-5% of requests in production. Use async context to correlate spans across microservices. Store traces for 7-14 days.\n\n**Performance Considerations:** Instrumentation adds 5-10% CPU overhead. Use sampling to reduce. Flamegraph generation on production should be done on a staging environment with simulated traffic.\n\n**SEO Considerations:** Not relevant.\n\n**Production Recommendations:** Use managed services (Datadog APM, New Relic) for ease. For open-source, use Jaeger + Prometheus. Set up alerts on high latency.\n\n**Latest Nuxt Patterns:** Nuxt 3 has experimental `nitro.instrumentation` option for built-in OTel. Also, `nuxt-otel` module simplifies setup.\n\n**TypeScript Example:** Not applicable.\n\n**Interview Tip:** Emphasize that profiling is not a one-time activity; it should be part of your CI\u002FCD to catch regressions. Use flamegraphs to identify unexpected hot paths.\n\n**Common Follow-up:** \"How do you profile memory leaks over time?\"\n\n**Real-world Example:** A travel booking site noticed increased latency during peak hours. OTel traces revealed that a `useState` call was storing a large object (500KB) per request, causing GC pressure. Flamegraphs showed 30% of CPU time in GC. They refactored to use a computed property instead of storing the full object. Latency dropped by 60%.",[680,681,682,432,683,684],"profiling","opentelemetry","flamegraph","monitoring","tracing","Emphasize that profiling is not a one-time activity; it should be part of your CI\u002FCD to catch regressions. Use flamegraphs to identify unexpected hot paths.","How do you profile memory leaks over time?","A travel booking site noticed increased latency during peak hours. OTel traces revealed that a `useState` call was storing a large object (500KB) per request, causing GC pressure. Flamegraphs showed 30% of CPU time in GC. They refactored to use a computed property instead of storing the full object. Latency dropped by 60%.",1779734543422]