### Nuxt.js Script Setup Example Source: https://nuxt.com/llms-full.txt A basic example of using ` ``` -------------------------------- ### Install Dependencies and Develop Source: https://nuxt.com/modules/hub Commands to install dependencies, prepare types, and start the development server for NuxtHub. ```bash # Install dependencies pnpm i # Generate type stubs pnpm dev:prepare # Develop with the playground pnpm dev # Build the playground pnpm dev:build # Run ESLint pnpm lint # Run Vitest pnpm test pnpm test:watch ``` -------------------------------- ### Testing Example Source: https://nuxt.com/llms-full.txt Provides a basic setup for testing Nuxt applications. ```vue ``` -------------------------------- ### Command Palette with Trailing Icon and Script Setup Source: https://ui.nuxt.com/components/command-palette This example shows the same Command Palette configuration as above, but explicitly includes the `ref` import for clarity in the script setup. ```vue ``` -------------------------------- ### Nuxt Plugin Object Syntax with Setup Source: https://nuxt.com/llms-full.txt An example of a Nuxt plugin defined using the object syntax, utilizing the `setup` property for the main plugin logic. This allows for more configuration options. ```typescript export default defineNuxtPlugin({ name: 'myPlugin', enforce: 'post', setup(nuxtApp) { // Plugin logic here } }) ``` -------------------------------- ### Create Project Directory and Navigate Source: https://v2.nuxt.com/docs/get-started/installation Manually set up your Nuxt project by creating a directory and navigating into it. ```bash mkdir cd ``` -------------------------------- ### Get Router Instance in Setup Source: https://nuxt.com/docs/3.x/api/composables/use-router Use useRouter in your script setup to get the router instance. This is typically done at the top of your component or composable. ```vue ``` -------------------------------- ### Basic Test Setup with Vitest Source: https://nuxt.com/docs/3.x/getting-started/testing Demonstrates the basic structure for setting up a test context using Vitest and `@nuxt/test-utils/e2e`'s `setup` function. ```typescript import { describe, test } from 'vitest' import { $fetch, setup } from '@nuxt/test-utils/e2e' describe('My test', async () => { await setup({ // test context options }) test('my test', () => { // ... }) }) ``` -------------------------------- ### Programmatically Installing a Nuxt Module (Deprecated) Source: https://nuxt.com/docs/3.x/api/kit/modules Demonstrates the deprecated `installModule` function for programmatically installing a Nuxt module with specific options. This example installs `@nuxtjs/fontaine` with custom font configurations. ```javascript import { defineNuxtModule, installModule } from '@nuxt/kit' export default defineNuxtModule({ async setup () { // will install @nuxtjs/fontaine with Roboto font and Impact fallback await installModule('@nuxtjs/fontaine', { // module configuration fonts: [ { family: 'Roboto', fallbacks: ['Impact'], fallbackName: 'fallback-a', }, ], }) }, }) ``` -------------------------------- ### Create Nuxt Project with Starter Template Source: https://nuxt.com/llms-full.txt Use this command to create a new Nuxt project with the default starter template. ```bash npm create nuxt@latest -- -t ui ``` -------------------------------- ### Basic Command Palette Setup Source: https://ui.nuxt.com/components/command-palette This snippet shows the basic setup for the Command Palette component. It assumes you have Nuxt UI installed and configured. ```vue ``` -------------------------------- ### Install the Pinia Nuxt module Source: https://nuxt.com/llms-full.txt Example of adding the Pinia module to a Nuxt project. This command installs the module, adds it to package.json, and updates nuxt.config.ts. ```bash npx nuxt module add pinia ``` -------------------------------- ### Runtime Configuration Example Source: https://nuxt.com/docs/3.x/api/nuxt-config Demonstrates how to configure runtime config, including private API keys and public base URLs. Environment variables can automatically override these values. ```javascript export default { runtimeConfig: { apiKey: '', // Default to an empty string, automatically set at runtime using process.env.NUXT_API_KEY public: { baseURL: '' // Exposed to the frontend as well. } } } ``` -------------------------------- ### Default Plugin Setup Definitions Source: https://nuxt.com/docs/3.x/api/nuxt-config Lists default definitions for the 'setup' function within `defineNuxtPlugin`. ```javascript [ "setup" ] ``` -------------------------------- ### Basic Test Setup with Nuxt Test Utils Source: https://nuxt.com/llms-full.txt Demonstrates the basic structure for setting up a test environment using `setup` from `@vue/test-utils`. This is typically used within a testing framework like Vitest. ```javascript describe('My test', async () => { await setup({ // test context options }) test('my test', () => { // ... }) }) ``` -------------------------------- ### GET /api/query Source: https://nuxt.com/llms-full.txt Handles GET requests to the /api/query endpoint and retrieves query parameters. The example demonstrates how to access and return query parameters like 'foo' and 'baz'. ```APIDOC ## GET /api/query ### Description Handles GET requests to the /api/query endpoint and retrieves query parameters. The example demonstrates how to access and return query parameters like 'foo' and 'baz'. ### Method GET ### Endpoint /api/query ### Parameters #### Query Parameters - **foo** (string) - Optional - The value for the 'foo' query parameter. - **baz** (string) - Optional - The value for the 'baz' query parameter. ### Response #### Success Response (200) - **a** (string) - The value of the 'foo' query parameter. - **b** (string) - The value of the 'baz' query parameter. ### Response Example ```json { "a": "bar", "b": "qux" } ``` ``` -------------------------------- ### Nuxt Project Structure Example Source: https://nuxt.com/llms-full.txt Illustrates a typical Nuxt.js project directory structure. ```bash -| app/ ---| node_modules/ ---| nuxt.config.js ---| package.json ---| src/ ------| assets/ ------| components/ ------| layouts/ ------| middleware/ ------| pages/ ------| plugins/ ------| public/ ------| store/ ------| server/ ------| app.config.ts ------| app.vue ------| error.vue ``` -------------------------------- ### Create Nuxt Project with deno Source: https://nuxt.com/docs/3.x/getting-started/installation Use this command to create a new Nuxt starter project locally with deno. ```bash deno -A npm:create-nuxt@latest -t v3 ``` -------------------------------- ### installModule Function Source: https://nuxt.com/docs/api/kit The `installModule` function is used to programmatically install Nuxt modules within your Nuxt application's setup. It allows for passing inline options to the module being installed. ```APIDOC ## installModule ### Description Installs a Nuxt module programmatically. ### Type Signature `async function installModule (moduleToInstall: string | NuxtModule, inlineOptions?: any, nuxt?: Nuxt)` ### Parameters #### Parameters - **moduleToInstall** (string | NuxtModule) - Required - The module to install. Can be either a string with the module name or a module object itself. - **inlineOptions** (any) - Optional - An object with the module options to be passed to the module's `setup` function. - **nuxt** (Nuxt) - Optional - Nuxt instance. If not provided, it will be retrieved from the context via `useNuxt()` call. ### Usage Example ```javascript import { defineNuxtModule, installModule } from '@nuxt/kit' export default defineNuxtModule({ async setup() { // will install @nuxtjs/fontaine with Roboto font and Impact fallback await installModule('@nuxtjs/fontaine', { // module configuration fonts: [ { family: 'Roboto', fallbacks: ['Impact'], fallbackName: 'fallback-a', }, ], }) }, }) ``` ``` -------------------------------- ### Page Routing Setup Source: https://nuxt.com/llms-full.txt Pages in the `app/pages/` directory define routes. Use `` in `app.vue` to render the content of the current route. This example shows the setup for the homepage and an about page. ```vue ``` ```vue ``` -------------------------------- ### Run Development Server Source: https://nuxt.com/docs/3.x/community/framework-contribution Start the development server to test changes in the playground application. ```bash pnpm dev ``` -------------------------------- ### Nuxt Configuration Example with Future Compatibility Source: https://nuxt.com/docs/3.x/api/nuxt-config Demonstrates how to enable Nuxt v4 features and flags while selectively re-enabling Nuxt v3 behavior for testing purposes. ```javascript export default defineNuxtConfig({ future: { compatibilityVersion: 4, }, // To re-enable _all_ Nuxt v3 behaviour, set the following options: srcDir: '.', dir: { app: 'app' }, experimental: { compileTemplate: true, templateUtils: true, relativeWatchPaths: true, resetAsyncDataToUndefined: true, defaults: { useAsyncData: { deep: true } } }, unhead: { renderSSRHeadOptions: { omitLineBreaks: false } } }) ``` -------------------------------- ### Build Templates Example Source: https://nuxt.com/llms-full.txt Example of configuring Nuxt build templates, recommending the use of `@nuxt/kit`'s `addTemplate`. ```javascript templates: [ { src: '~/modules/support/plugin.js', // `src` can be absolute or relative dst: 'support.js', // `dst` is relative to project `.nuxt` dir } ] ``` -------------------------------- ### Install Test Utilities and Dependencies Source: https://nuxt.com/docs/3.x/getting-started/testing Install @nuxt/test-utils along with Vitest, Vue Test Utils, Happy DOM, and Playwright Core for a complete testing setup. Choose your preferred test runner and environment based on your project needs. ```bash npm i --save-dev @nuxt/test-utils vitest @vue/test-utils happy-dom playwright-core ``` ```bash yarn add --dev @nuxt/test-utils vitest @vue/test-utils happy-dom playwright-core ``` -------------------------------- ### Pages Example Source: https://nuxt.com/llms-full.txt Demonstrates the file-based routing system in Nuxt.js. ```vue ``` -------------------------------- ### Using TypeScript in Nuxt.js Components Source: https://nuxt.com/docs/4.x/guide/concepts/typescript Example of a Nuxt.js component written in TypeScript, demonstrating script setup with type inference. ```typescript ``` -------------------------------- ### setup Options Source: https://nuxt.com/llms-full.txt Configuration options for the setup function in Nuxt Test Utils. ```APIDOC ## setup Options ### Nuxt Config - `rootDir` (string): Path to a directory with a Nuxt app to be put under test. Default: `'.'` - `configFile` (string): Name of the configuration file. Default: `'nuxt.config'` ### Timings - `setupTimeout` (number): The amount of time (in milliseconds) to allow for `setupTest` to complete its work. Default: `120000` or `240000` on windows. - `teardownTimeout` (number): The amount of time (in milliseconds) to allow tearing down the test environment. Default: `30000`. ### Features - `build` (boolean): Whether to run a separate build step. Default: `true` (`false` if `browser` or `server` is disabled, or if a `host` is provided). - `server` (boolean): Whether to launch a server to respond to requests in the test suite. Default: `true` (`false` if a `host` is provided). - `port` (number | undefined): If provided, set the launched test server port to the value. Default: `undefined`. - `host` (string): If provided, a URL to use as the test target instead of building and running a new server. Default: `undefined`. - `browser` (boolean): If this option is set, a browser will be launched and can be controlled in the subsequent test suite. Default: `false`. - `browserOptions` (object): Options for the browser. - `type` (string): The type of browser to launch - either `chromium`, `firefox` or `webkit`. - `launch` (object): Object of options that will be passed to playwright when launching the browser. - `runner` (string): Specify the runner for the test suite. Default: `'vitest'`. ``` -------------------------------- ### Server API to Get Cookie Source: https://nuxt.com/docs/3.x/api/utils/dollarfetch An example of a server API route that retrieves a cookie named 'foo' from the incoming event. ```typescript export default defineEventHandler((event) => { const foo = getCookie(event, 'foo') // ... Do something with the cookie }) ``` -------------------------------- ### Render Deployment Start Command Source: https://nuxt.com/llms-full.txt Update the start command for Render deployments to point to the server output. ```bash node .output/server/index.mjs ``` -------------------------------- ### Nuxt Module Hook Example Source: https://nuxt.com/docs/3.x/guide/going-further/hooks Defining a Nuxt module and registering a hook within its setup function. The 'close' hook is used here. ```typescript import { defineNuxtModule } from '@nuxt/kit' export default defineNuxtModule({ setup (options, nuxt) { nuxt.hook('close', async () => { }) }, }) ``` -------------------------------- ### Basic Module Setup with Logger Source: https://nuxt.com/llms-full.txt Demonstrates a simple Nuxt module setup using `defineNuxtModule` and the `useLogger` utility for logging information. ```typescript import { defineNuxtModule, useLogger } from '@nuxt/kit' export default defineNuxtModule({ setup (options, nuxt) { const logger = useLogger('my-module') logger.info('Hello from my module!') }, }) ``` -------------------------------- ### Basic useFetch Example Source: https://nuxt.com/docs/3.x/getting-started/data-fetching Fetch data from an API endpoint within the setup function. The fetched data is available in the 'count' variable. ```vue ``` -------------------------------- ### setup Function Source: https://nuxt.com/llms-full.txt Configures the test environment, allowing you to specify a target host for end-to-end tests. ```APIDOC ## setup(options) ### Description Configures the test environment for end-to-end testing. Allows specifying a target host for tests. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **host** (string) - Required - The URL of the target host for end-to-end tests. ### Request Example ```ts import { setup } from '@nuxt/test-utils/e2e' await setup({ host: 'http://localhost:8787', }) ``` ``` -------------------------------- ### Accessing Nuxt App Context Source: https://nuxt.com/docs/3.x/api/composables/use-nuxt-app Use `useNuxtApp` within your setup to get access to the Nuxt application's runtime context. ```javascript const nuxtApp = useNuxtApp() ``` -------------------------------- ### Module Setup with Logger and Options Source: https://nuxt.com/llms-full.txt Shows how to initialize a logger with a tag and custom options, and integrate it into a Nuxt module setup. ```typescript import { defineNuxtModule, useLogger } from '@nuxt/kit' export default defineNuxtModule({ setup (options, nuxt) { const logger = useLogger('my-module', { level: options.quiet ? 0 : 3 }) logger.info('Hello from my module!') }, }) ``` -------------------------------- ### Basic Usage of useRequestFetch Source: https://nuxt.com/docs/3.x/api/composables/use-request-fetch Demonstrates how to use useRequestFetch to fetch data from an API endpoint. This example shows a simple GET request. ```javascript import { useRequestFetch } from '#app' const { data } = await useRequestFetch('/api/users') console.log(data.value) ``` -------------------------------- ### Get Authorization Header Source: https://nuxt.com/docs/3.x/api/composables/use-request-header Retrieve the value of the 'authorization' request header. This example demonstrates a basic usage for accessing a specific header. ```javascript const authorization = useRequestHeader('authorization') ``` -------------------------------- ### Run Local Static Server Source: https://nuxt.com/blog/going-full-static After generating the static site, you can use `nuxt start` to run a local development server that serves the generated static application. This is useful for testing the production build locally. ```bash nuxt start ``` -------------------------------- ### Nuxt App Plugin Hook Example Source: https://nuxt.com/docs/3.x/guide/going-further/hooks Using a Nuxt plugin to hook into the 'page:start' event during the application's runtime. ```typescript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.hook('page:start', () => { /* your code goes here */ }) }) ``` -------------------------------- ### Update App Config Example Source: https://nuxt.com/docs/3.x/api/utils/update-app-config Demonstrates how to import and use the updateAppConfig utility along with useAppConfig to update the application's configuration. It shows the initial state of appConfig, the update operation, and the resulting state. ```javascript import { updateAppConfig, useAppConfig } from '#imports' const appConfig = useAppConfig() // { foo: 'bar' } const newAppConfig = { foo: 'baz' } updateAppConfig(newAppConfig) console.log(appConfig) // { foo: 'baz' } ``` -------------------------------- ### Run Nuxt Development Server with NPM Source: https://v2.nuxt.com/docs/get-started/installation Navigate to your project directory and start the Nuxt development server using NPM. ```bash cd npm run dev ``` -------------------------------- ### Basic Nuxt Agent Setup Source: https://nuxt.com/blog/introducing-nuxt-agent This snippet shows the basic configuration for Nuxt Agent in your Nuxt application. Ensure you have the necessary dependencies installed. ```javascript import { NuxtAgent } from "nuxt-agent"; export default defineNuxtPlugin((nuxtApp) => { const agent = new NuxtAgent({ // Configuration options }); nuxtApp.provide('agent', agent); }); ``` -------------------------------- ### Basic Module Dependencies Declaration Source: https://nuxt.com/llms-full.txt A simple example of declaring module dependencies. This ensures Nuxt installs and manages the specified modules correctly. ```typescript import { createResolver, defineNuxtModule } from '@nuxt/kit' const resolver = createResolver(import.meta.url) ``` -------------------------------- ### Nuxt Server Directory Structure Example Source: https://nuxt.com/docs/3.x/directory-structure/server This example shows the typical file structure within the server/ directory for API routes, custom routes, and middleware. ```bash -| server/ -| api/ -| hello.ts # /api/hello -| routes/ -| bonjour.ts # /bonjour -| middleware/ -| log.ts # log all requests ``` -------------------------------- ### Server Middleware Example Source: https://nuxt.com/llms-full.txt Illustrates how to create server middleware that runs on every request to perform actions like logging or authentication. ```APIDOC ## Middleware for All Requests ### Description Server middleware handlers execute on every incoming request before other routes are processed. They can be used for logging, authentication, or modifying request context. ### Method All (GET, POST, PUT, DELETE, etc.) ### Endpoint /* ### Example Usage - **Logging**: Logs the URL of each incoming request. - **Authentication**: Adds authentication context to the event object. ### Middleware Examples #### server/middleware/log.ts ```ts export default defineEventHandler((event) => { console.log('New request: ' + getRequestURL(event)) }) ``` #### server/middleware/auth.ts ```ts export default defineEventHandler((event) => { event.context.auth = { user: 123 } }) ``` ::note Middleware handlers should not return values or respond to the request directly; their purpose is to inspect, extend, or throw errors. :: ``` -------------------------------- ### Register Nuxt.js Plugin for VueGtag Source: https://nuxt.com/llms-full.txt Example of registering a Nuxt.js plugin to integrate VueGtag for analytics tracking. Ensure VueGtag and its dependencies are installed. ```javascript export default defineNuxtPlugin((nuxtApp) => { nuxtApp.vueApp.use(VueGtag, { property: { id: 'GA_MEASUREMENT_ID', }, }) trackRouter(useRouter()) }) ``` -------------------------------- ### Open Nuxt Starter on StackBlitz Source: https://nuxt.com/docs/4.x/getting-started/installation Use this online sandbox to play around with Nuxt in your browser without local setup. ```html Open on StackBlitz ``` -------------------------------- ### Accessing Router Instance Source: https://nuxt.com/docs/3.x/api/composables/use-router Import and use the `useRouter` composable to get the router instance. This is typically done in `setup` functions or script blocks. ```javascript import { useRouter } from '#imports' const router = useRouter() // You can now use router.push, router.replace, etc. ```