### Target Host Example Source: https://nuxt.com/docs/3.x/getting-started/testing An example demonstrating how to use the `host` option in `setup` to run end-to-end tests against a separately running server, which can improve test execution speed. ```APIDOC ##### Target `host` end-to-end example A common use-case for end-to-end testing is running the tests against a deployed application running in the same environment typically used for Production. For local development or automated deploy pipelines, testing against a separate local server can be more efficient and is typically faster than allowing the test framework to rebuild between tests. To utilize a separate target host for end-to-end tests, simply provide the `host` property of the `setup` function with the desired URL. ```typescript import { createPage, setup } from '@nuxt/test-utils/e2e' import { describe, expect, it } from 'vitest' describe('login page', async () => { await setup({ host: 'http://localhost:8787', }) it('displays the email and password fields', async () => { const page = await createPage('/login') expect(await page.getByTestId('email').isVisible()).toBe(true) expect(await page.getByTestId('password').isVisible()).toBe(true) }) }) ``` ``` -------------------------------- ### Example Usage of installModule Source: https://nuxt.com/docs/3.x/api/kit/modules Provides a concrete example of using the installModule function within a Nuxt module setup. It shows how to pass module configuration options. ```javascript import { defineNuxtModule, installModule } from '@nuxt/kit' export default defineNuxtModule({ async setup (options, nuxt) { // will install @nuxtjs/fontaine with Roboto font and Impact fallback await installModule('@nuxtjs/fontaine', { // module configuration fonts: [ { family: 'Roboto', fallbacks: ['Impact'], fallbackName: 'fallback-a', }, ], }) }, }) ``` -------------------------------- ### Example Module Definition with Configurable Options Source: https://nuxt.com/docs/3.x/api/kit An example demonstrating how to define a Nuxt module with a `configKey` for user configuration and a `setup` function. ```javascript import { defineNuxtModule } from '@nuxt/kit' export default defineNuxtModule({ meta: { name: 'my-module', configKey: 'myModule', }, defaults: { // Module options enabled: true, }, setup (options) { if (options.enabled) { console.log('My Nuxt module is enabled!') } }, }) ``` -------------------------------- ### Basic useFetch Example Source: https://nuxt.com/docs/3.x/getting-started/data-fetching Use `useFetch` to make SSR-safe network calls within the setup function. It automatically handles data fetching and provides the result. ```vue ``` -------------------------------- ### Mock Nuxt Component with Setup Function Source: https://nuxt.com/docs/3.x/getting-started/testing Demonstrates how to mock a Nuxt component using `mockComponent`. This example shows mocking 'MyComponent' with a setup function that returns a simple div displaying a counter. ```typescript import { mockComponent } from '@nuxt/test-utils/runtime' mockComponent('MyComponent', { props: { value: String, }, setup (props) { // ... }, }) // relative path or alias also works mockComponent('~/components/my-component.vue', () => { // or a factory function return defineComponent({ setup (props) { // ... }, }) }) // or you can use SFC for redirecting to a mock component mockComponent('MyComponent', () => import('./MockComponent.vue')) // your tests here ``` -------------------------------- ### Handle Async Setup with Lifecycle Hooks Source: https://nuxt.com/docs/3.x/guide/modules/best-practices Use lifecycle hooks like `onInstall` and `onUpgrade` for one-time setup tasks instead of the main `setup` function. This prevents unnecessary work on every build and improves developer experience. Nuxt warns if module setup exceeds 1 second. ```javascript import { addServerHandler, defineNuxtModule } from 'nuxt/kit' import semver from 'semver' export default defineNuxtModule({ meta: { name: 'my-database-module', version: '1.0.0', }, async onInstall (nuxt) { // One-time setup: create database schema, generate config files, etc. await generateDatabaseConfig(nuxt.options.rootDir) }, async onUpgrade (nuxt, options, previousVersion) { // Handle version-specific migrations if (semver.lt(previousVersion, '1.0.0')) { await migrateLegacyData() } }, setup (options, nuxt) { // Regular setup logic that runs on every build addServerHandler({ /* ... */ }) }, }) ``` -------------------------------- ### Setup Options Source: https://nuxt.com/docs/3.x/getting-started/testing Details the available options for the `setup` function, including configuration for Nuxt, timings, and feature flags for the test environment. ```APIDOC #### Nuxt Config * `rootDir`: Path to a directory with a Nuxt app to be put under test. * Type: `string` * Default: `'.'` * `configFile`: Name of the configuration file. * Type: `string` * Default: `'nuxt.config'` #### Timings * `setupTimeout`: The amount of time (in milliseconds) to allow for `setupTest` to complete its work (which could include building or generating files for a Nuxt application, depending on the options that are passed). * Type: `number` * Default: `120000` or `240000` on windows * `teardownTimeout`: The amount of time (in milliseconds) to allow tearing down the test environment, such as closing the browser. * Type: `number` * Default: `30000` #### Features * `build`: Whether to run a separate build step. * Type: `boolean` * Default: `true` (`false` if `browser` or `server` is disabled, or if a `host` is provided) * `server`: Whether to launch a server to respond to requests in the test suite. * Type: `boolean` * Default: `true` (`false` if a `host` is provided) * `port`: If provided, set the launched test server port to the value. * Type: `number | undefined` * Default: `undefined` * `host`: If provided, a URL to use as the test target instead of building and running a new server. Useful for running "real" end-to-end tests against a deployed version of your application, or against an already running local server (which may provide a significant reduction in test execution timings). See the target host end-to-end example below. * Type: `string` * Default: `undefined` * `browser`: Under the hood, Nuxt test utils uses `playwright` to carry out browser testing. If this option is set, a browser will be launched and can be controlled in the subsequent test suite. * Type: `boolean` * Default: `false` * `browserOptions` * Type: `object` with the following properties * `type`: The type of browser to launch - either `chromium`, `firefox` or `webkit` * `launch`: `object` of options that will be passed to playwright when launching the browser. See full API reference. * `runner`: Specify the runner for the test suite. Currently, Vitest is recommended. * Type: `'vitest' | 'jest' | 'cucumber'` * Default: `'vitest'` ``` -------------------------------- ### Setup End-to-End Tests with setup Source: https://nuxt.com/docs/3.x/getting-started/testing Initialize end-to-end testing environment using the `setup` function from `@nuxt/test-utils/e2e`. Configure options like `setupTimeout` to control the test environment's behavior. ```javascript import { $fetch, setup } from '@nuxt/test-utils/e2e' await setup ({ setupTimeout : 10000, }) // ... ``` -------------------------------- ### navigateTo Usage Examples Source: https://nuxt.com/docs/3.x/api/utils/navigate-to Examples demonstrating how to use the navigateTo function with different parameters and options. ```APIDOC ## navigateTo ### Description Navigates to a different route. This function can be used on both the server and client side. ### Parameters #### `to` **Type** : `RouteLocationRaw` | `undefined` | `null` **Default** : `'/'` `to` can be a plain string or a route object to redirect to. When passed as `undefined` or `null`, it will default to `'/'`. #### `options` (optional) **Type** : `NavigateToOptions` An object accepting the following properties: * `replace` * **Type** : `boolean` * **Default** : `false` * By default, `navigateTo` pushes the given route into the Vue Router's instance on the client side. This behavior can be changed by setting `replace` to `true`, to indicate that given route should be replaced. * `redirectCode` * **Type** : `number` * **Default** : `302` * `navigateTo` redirects to the given path and sets the redirect code to `302 Found` by default when the redirection takes place on the server side. This default behavior can be modified by providing different `redirectCode`. Commonly, `301 Moved Permanently` can be used for permanent redirections. * `external` * **Type** : `boolean` * **Default** : `false` * Allows navigating to an external URL when set to `true`. Otherwise, `navigateTo` will throw an error, as external navigation is not allowed by default. * `open` * **Type** : `OpenOptions` * Allows navigating to the URL using the open() method of the window. This option is only applicable on the client side and will be ignored on the server side. An object accepting the following properties: * `target` * **Type** : `string` * **Default** : `'_blank'` * A string, without whitespace, specifying the name of the browsing context the resource is being loaded into. * `windowFeatures` * **Type** : `OpenWindowFeatures` * An object accepting the following properties: Property| Type| Description ---|---|--- `popup`| `boolean`| Requests a minimal popup window instead of a new tab, with UI features decided by the browser. `width` or `innerWidth`| `number`| Specifies the content area's width (minimum 100 pixels), including scrollbars. `height` or `innerHeight`| `number`| Specifies the content area's height (minimum 100 pixels), including scrollbars. `left` or `screenX`| `number`| Sets the horizontal position of the new window relative to the left edge of the screen. `top` or `screenY`| `number`| Sets the vertical position of the new window relative to the top edge of the screen. `noopener`| `boolean`| Prevents the new window from accessing the originating window via `window.opener`. `noreferrer`| `boolean`| Prevents the Referer header from being sent and implicitly enables `noopener`. Refer to the documentation for more detailed information on the **windowFeatures** properties. ### Examples ```typescript // Passing the URL directly will redirect to the '/blog' page await navigateTo('/blog') // Using the route object, will redirect to the route with the name 'blog' await navigateTo({ name: 'blog' }) // Redirects to the 'product' route while passing a parameter (id = 1) using the route object. await navigateTo({ name: 'product', params: { id: 1 } }) // Navigate to an external URL await navigateTo('https://example.com', { external: true }) // Open a URL in a new tab with specific window features await navigateTo('/about', { open: { target: '_blank', windowFeatures: { width: 800, height: 600, popup: true } } }) ``` ``` -------------------------------- ### Controlling Loading Indicator Source: https://nuxt.com/docs/3.x/api/composables/use-loading-indicator Examples of how to manually control the loading indicator's state using the `start` and `set` methods. ```APIDOC ## Controlling Loading Indicator ### Example ```vue ``` ``` -------------------------------- ### Example Plugin Logic Source: https://nuxt.com/docs/3.x/api/kit/plugins This example plugin demonstrates setting a 'dark' color mode preference on app mount if it's not already set. ```typescript export default defineNuxtPlugin((nuxtApp) => { const colorMode = useColorMode() nuxtApp.hook('app:mounted', () => { if (colorMode.preference !== 'dark') { colorMode.preference = 'dark' } }) }) ``` -------------------------------- ### Install Stylus Preprocessor Source: https://nuxt.com/docs/3.x/getting-started/styling Install Stylus as a development dependency to use it with Nuxt.js. ```bash npm install -D stylus ``` -------------------------------- ### Basic useFetch Example Source: https://nuxt.com/docs/3.x/api/composables/use-fetch Fetch data from an API endpoint and destructure the returned refs and functions. Access data, status, and error using `.value` within ` ``` -------------------------------- ### installModule Source: https://nuxt.com/docs/3.x/api/kit Installs a specified Nuxt module programmatically. This is helpful when your module depends on other modules. Module options can be passed as an object to `inlineOptions` and will be forwarded to the module's `setup` function. Note: This function is deprecated and will be removed in a future version. ```APIDOC ## `installModule` ### Description Install specified Nuxt module programmatically. This is helpful when your module depends on other modules. You can pass the module options as an object to `inlineOptions` and they will be passed to the module's `setup` function. **Deprecated:** Use the `moduleDependencies` option in `defineNuxtModule` instead. The `installModule` function will be removed (or may become non-blocking) in a future version. ### Type ```typescript async function installModule (moduleToInstall: string | NuxtModule, inlineOptions?: any, nuxt?: Nuxt) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Property| Type| Required| Description ---|---|---|--- `moduleToInstall`| `string | NuxtModule`| `true`| The module to install. Can be either a string with the module name or a module object itself. `inlineOptions`| `any`| `false`| An object with the module options to be passed to the module's `setup` function. `nuxt`| `Nuxt`| `false`| Nuxt instance. If not provided, it will be retrieved from the context via `useNuxt()` call. ### Request Example ```javascript import { defineNuxtModule, installModule } from '@nuxt/kit' export default defineNuxtModule({ async setup (options, nuxt) { // will install @nuxtjs/fontaine with Roboto font and Impact fallback await installModule('@nuxtjs/fontaine', { // module configuration fonts: [ { family: 'Roboto', fallbacks: ['Impact'], fallbackName: 'fallback-a', }, ], }) }, }) ``` ### Response #### Success Response (200) None explicitly documented. #### Response Example None explicitly documented. ``` -------------------------------- ### Install Pinia Module Source: https://nuxt.com/docs/3.x/migration/configuration Install the Pinia module and its Nuxt integration using Yarn. ```bash yarn add pinia @pinia/nuxt ``` -------------------------------- ### Install Nuxt Module with Options Source: https://nuxt.com/docs/3.x/api/kit/modules Demonstrates how to install a Nuxt module programmatically with inline options. This is useful when your module depends on other modules. ```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', }, ], }) }, }) ``` -------------------------------- ### Basic Usage Example Source: https://nuxt.com/docs/3.x/api/composables/use-lazy-fetch An example demonstrating how to use useLazyFetch in a Vue component to fetch data and handle pending states. ```APIDOC ``` -------------------------------- ### Install Less Preprocessor Source: https://nuxt.com/docs/3.x/getting-started/styling Install Less as a development dependency to use it with Nuxt.js. ```bash npm install -D less ``` -------------------------------- ### Handling Pending State Example Source: https://nuxt.com/docs/3.x/api/composables/use-lazy-fetch An example illustrating how to manage the pending state when using useLazyFetch, ensuring the UI updates correctly. ```APIDOC ``` -------------------------------- ### Install Nuxt Content Module Source: https://nuxt.com/docs/3.x/directory-structure/content Install the @nuxt/content module and add it to your nuxt.config.ts. This command handles both installation and configuration. ```bash npx nuxt module add content ``` -------------------------------- ### Install Nuxt Bridge and nuxi (deno) Source: https://nuxt.com/docs/3.x/bridge/overview Install Nuxt Bridge and nuxi as development dependencies using deno. ```bash deno add -D npm:@nuxt/bridge npm:nuxi ``` -------------------------------- ### Install Nuxt Bridge and nuxi (bun) Source: https://nuxt.com/docs/3.x/bridge/overview Install Nuxt Bridge and nuxi as development dependencies using bun. ```bash bun add -D @nuxt/bridge nuxi ``` -------------------------------- ### Install Nuxi CLI Source: https://nuxt.com/docs/3.x/bridge/nitro Install `nuxi` as a development dependency using npm, yarn, pnpm, bun, or deno. ```bash npm install -D nuxi ``` ```bash yarn add --dev nuxi ``` ```bash pnpm add -D nuxi ``` ```bash bun add -D nuxi ``` ```bash deno add -D npm:nuxi ``` -------------------------------- ### Example API Endpoint (Server Route) Source: https://nuxt.com/docs/3.x/examples/advanced/use-custom-fetch-composable This is an example of a server route that could be used with the custom fetch composable. It simulates fetching a list of users. ```javascript export default defineEventHandler(async (event) => { // Simulate fetching data from a database or external API const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' } ] return users }) ``` -------------------------------- ### Install Sass Preprocessor Source: https://nuxt.com/docs/3.x/getting-started/styling Install Sass as a development dependency to use it with Nuxt.js. ```bash npm install -D sass ``` -------------------------------- ### Example: Middleware Authorization Source: https://nuxt.com/docs/3.x/api/composables/use-request-header Example demonstrating how to use `useRequestHeader` in a route middleware to check for an authorization header. ```APIDOC ## Example: Middleware Authorization ### Description This example shows how to use `useRequestHeader` to protect a route by checking for the presence of an `authorization` header. ### File: `middleware/authorized-only.ts` ```typescript export default defineNuxtRouteMiddleware((to, from) => { if (!useRequestHeader('authorization')) { return navigateTo('/not-authorized') } }) ``` ``` -------------------------------- ### Install vue-gtag-next with bun Source: https://nuxt.com/docs/3.x/directory-structure/plugins Install the vue-gtag-next dependency using bun for integrating Google Analytics. ```bash bun add -D vue-gtag-next ``` -------------------------------- ### Create a Custom Fetch Composable Source: https://nuxt.com/docs/3.x/examples/advanced/use-custom-fetch-composable Define a composable function to encapsulate fetch logic. This example shows basic setup for making a GET request. ```javascript import { ref } from 'vue' export function useFetchData(url: string) { const data = ref(null) const error = ref(null) const loading = ref(false) const fetchData = async () => { loading.value = true error.value = null try { const response = await fetch(url) if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`) } data.value = await response.json() } catch (e: any) { error.value = e } finally { loading.value = false } } return { data, error, loading, fetchData } } ``` -------------------------------- ### Define a Custom Fetch Composable Source: https://nuxt.com/docs/3.x/examples/advanced/use-custom-fetch-composable Create a composable function to encapsulate fetch logic. This example shows a basic setup for making GET requests. ```javascript import { useFetch } from '#app' export const useCustomFetch = (url, options = {}) => { const config = useRuntimeConfig() const defaults = { baseURL: config.public.apiBaseUrl } const mergedOptions = { ...defaults, ...options } return useFetch(url, mergedOptions) } ``` -------------------------------- ### Define Custom Fetch Composable Source: https://nuxt.com/docs/3.x/examples/advanced/use-custom-fetch-composable Create a composable function to encapsulate fetch logic. This example shows a basic setup for making GET requests. ```javascript import { useFetch } from '#app' export const useCustomFetch = (url, options = {}) => { const config = useRuntimeConfig() return useFetch(() => `${config.public.apiBase}${url}`, { ...options, headers: { ...(options.headers || {}), 'x-api-key': config.apiKey } }) } ``` -------------------------------- ### Creating a Custom Fetch Composable Source: https://nuxt.com/docs/3.x/examples/advanced/use-custom-fetch-composable Define a composable function to encapsulate fetch logic. This example shows a basic setup for making GET requests. ```javascript import { useFetch } from '#app' export const useCustomFetch = (url, options = {}) => { const config = useRuntimeConfig() const defaultOptions = { baseURL: config.public.apiBase, headers: { 'Accept': 'application/json' } } return useFetch(url, { ...defaultOptions, ...options }) } ``` -------------------------------- ### Basic useLazyFetch Example Source: https://nuxt.com/docs/3.x/api/composables/use-lazy-fetch Demonstrates how to use useLazyFetch to fetch posts and display them. It includes handling the 'pending' state for loading feedback. ```vue ``` -------------------------------- ### Define Custom Fetch Composable Source: https://nuxt.com/docs/3.x/examples/advanced/use-custom-fetch-composable Create a composable function to encapsulate fetch logic. This example shows a basic setup for making GET requests and handling responses. ```javascript import { useNuxtApp } from '#app' export const useCustomFetch = (url, options = {}) => { const { $api } = useNuxtApp() return $api.get(url, options) } ``` -------------------------------- ### Example Nitro Server Plugin Source: https://nuxt.com/docs/3.x/api/kit/nitro This example shows a Nitro server plugin that hooks into the `request`, `beforeResponse`, and `afterResponse` events to log activity. ```javascript export default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('request', (event) => { console.log('on request', event.path) }) nitroApp.hooks.hook('beforeResponse', (event, { body }) => { console.log('on response', event.path, { body }) }) nitroApp.hooks.hook('afterResponse', (event, { body }) => { console.log('on after response', event.path, { body }) }) }) ``` -------------------------------- ### Initialize Nuxt Layer with Starter Template Source: https://nuxt.com/docs/3.x/guide/going-further/layers Use this command to create a new Nuxt layer project based on the 'layer' template. Follow the README instructions for further setup. ```bash npm create nuxt -- --template layer nuxt-layer ``` -------------------------------- ### Setup Test Context Source: https://nuxt.com/docs/3.x/getting-started/testing Demonstrates how to set up the test context using the `setup` function from `@nuxt/test-utils/e2e` before running tests. This function initializes the Nuxt test environment. ```APIDOC ## Setup Test Context In each `describe` block where you are taking advantage of the `@nuxt/test-utils/e2e` helper methods, you will need to set up the test context before beginning. ```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', () => { // ... }) }) ``` Behind the scenes, `setup` performs a number of tasks in `beforeAll`, `beforeEach`, `afterEach` and `afterAll` to set up the Nuxt test environment correctly. Please use the options below for the `setup` method. ``` -------------------------------- ### Getting the Router Instance Source: https://nuxt.com/docs/3.x/api/composables/use-router The useRouter composable returns the router instance, which can be used in your script setup. ```APIDOC ## useRouter The useRouter composable returns the router instance. pages/index.vue ```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 with Deno. Replace `` with your desired project directory name. ```bash deno -A npm:create-nuxt@latest -t v3 ``` -------------------------------- ### Create a Custom Fetch Composable Source: https://nuxt.com/docs/3.x/examples/advanced/use-custom-fetch-composable Define a composable function to encapsulate fetch logic. This example shows basic setup with error handling. ```javascript import { ref } from 'vue' export function useFetchData(url: string) { const data = ref(null) const error = ref(null) const loading = ref(false) const fetchData = async () => { loading.value = true error.value = null try { const response = await fetch(url) if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`) } data.value = await response.json() } catch (e: any) { error.value = e.message console.error('Fetch error:', e) } finally { loading.value = false } } return { data, error, loading, fetchData } } ``` -------------------------------- ### Initialize a Fresh Nuxt Project Source: https://nuxt.com/docs/3.x/api/commands/init Use this command to initialize a new Nuxt project. You can specify the project directory and various options to customize the setup. ```bash npm create nuxt@latest [DIR] [--cwd=] [--logLevel=] [-t, --template] [-f, --force] [--offline] [--preferOffline] [--no-install] [--gitInit] [--shell] [--packageManager] [-M, --modules] [--no-modules] [--nightly] ``` -------------------------------- ### Nuxt Preview Command Usage Source: https://nuxt.com/docs/3.x/api/commands/preview This command starts a server to preview your Nuxt application after the build command. The `start` command is an alias for `preview`. When running your application in production, refer to the Deployment section. ```bash npx nuxt preview [ROOTDIR] [--cwd=] [--logLevel=] [--envName] [-e, --extends=] [-p, --port] [--dotenv] ``` -------------------------------- ### Server API Route to Get Cookie Source: https://nuxt.com/docs/3.x/api/utils/dollarfetch A server-side API route example demonstrating how to retrieve a specific cookie ('foo') from the incoming event. ```typescript export default defineEventHandler((event) => { const foo = getCookie(event, 'foo') // ... Do something with the cookie }) ``` -------------------------------- ### Get Router Instance with useRouter Source: https://nuxt.com/docs/3.x/api/composables/use-router Obtain the router instance using the useRouter composable. This instance is available for use in script setup blocks. ```vue ``` -------------------------------- ### Example .nuxtignore Configuration Source: https://nuxt.com/docs/3.x/directory-structure/nuxtignore Use glob patterns to ignore specific files or directories. Lines starting with '#' are comments. You can also use negation patterns with '!'. ```ignore # ignore layout foo.vue layouts/foo.vue # ignore layout files whose name ends with -ignore.vue layouts/*-ignore.vue # ignore page bar.vue pages/bar.vue # ignore page inside ignore folder pages/ignore/*.vue # ignore route middleware files under foo folder except foo/bar.js middleware/foo/*.js !middleware/foo/bar.js ``` -------------------------------- ### Create Nuxt Project with Bun Source: https://nuxt.com/docs/3.x/getting-started/installation Use this command to create a new Nuxt starter project with Bun. Replace `` with your desired project directory name. Note: This command may be subject to changes based on Bun's issue resolution. ```bash # you can use this when https://github.com/oven-sh/bun/issues/29087 is resolved # bun create nuxt@latest -t v3 bunx create-nuxt@latest init -t v3 ``` -------------------------------- ### installModule Source: https://nuxt.com/docs/3.x/api/kit/modules Installs a specified Nuxt module programmatically. This is useful for modules that depend on other modules. Options can be passed to the module's setup function via `inlineOptions`. ```APIDOC ## `installModule` ### Description Installs a specified Nuxt module programmatically. This is useful for modules that depend on other modules. Options can be passed to the module's setup function via `inlineOptions`. ### Type ```typescript async function installModule (moduleToInstall: string | NuxtModule, inlineOptions?: any, nuxt?: Nuxt) ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### 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. ### Request Example ```javascript import { defineNuxtModule, installModule } from '@nuxt/kit' export default defineNuxtModule({ async setup (options, nuxt) { // will install @nuxtjs/fontaine with Roboto font and Impact fallback await installModule('@nuxtjs/fontaine', { // module configuration fonts: [ { family: 'Roboto', fallbacks: ['Impact'], fallbackName: 'fallback-a', }, ], }) }, }) ``` ### Response #### Success Response (200) - **None**: This function does not return a value directly. It performs an action. #### Response Example - None ``` -------------------------------- ### Implement Module Lifecycle Hooks (`onInstall`, `onUpgrade`) Source: https://nuxt.com/docs/3.x/api/kit/modules Define `onInstall` and `onUpgrade` hooks to manage one-time setup tasks or version-specific migrations. Requires `meta.name` and `meta.version` to be set. ```javascript import { defineNuxtModule } from '@nuxt/kit' import semver from 'semver' export default defineNuxtModule({ meta: { name: 'my-awesome-module', version: '1.2.0', // Required for lifecycle hooks configKey: 'myAwesomeModule', }, defaults: { apiKey: '', enabled: true, }, onInstall (nuxt) { // This runs only when the module is first installed console.log('Setting up my-awesome-module for the first time!') // You might want to: // - Create initial configuration files // - Set up database schemas // - Display welcome messages // - Perform initial data migration }, onUpgrade (nuxt, options, previousVersion) { // This runs when the module is upgraded to a newer version console.log(`Upgrading my-awesome-module from ${previousVersion} to 1.2.0`) // You might want to: // - Migrate configuration files // - Update database schemas // - Clean up deprecated files // - Display upgrade notes if (semver.lt(previousVersion, '1.1.0')) { console.log('⚠️ Breaking changes in 1.1.0 - please check the migration guide') } }, setup (options, nuxt) { // Regular setup logic runs on every build if (options.enabled) { // Configure the module } }, }) ``` -------------------------------- ### Example Nuxt Module with Server Plugin Source: https://nuxt.com/docs/3.x/api/kit/nitro This example demonstrates how to add a server plugin from a Nuxt module. The plugin path is resolved using `createResolver`. ```javascript import { addServerPlugin, createResolver, defineNuxtModule } from '@nuxt/kit' export default defineNuxtModule({ setup () { const { resolve } = createResolver(import.meta.url) addServerPlugin(resolve('./runtime/plugin.ts')) }, }) ``` -------------------------------- ### Create a Custom Fetch Composable Source: https://nuxt.com/docs/3.x/examples/advanced/use-custom-fetch-composable Define a composable function to encapsulate your fetch logic. This example shows how to create a reusable function for making GET requests. ```javascript import { useFetch } from '#app' export const useCustomFetch = (url, options = {}) => { const config = useRuntimeConfig() return useFetch(url, { baseURL: config.public.apiBase, headers: { 'X-Custom-Header': 'nuxt-api' }, ...options }) } ``` -------------------------------- ### Nuxt Runtime Configuration Example Source: https://nuxt.com/docs/3.x/api/configuration/nuxt-config Demonstrates how to configure runtime configuration, including private API keys and public base URLs. Environment variables like NUXT_API_KEY and NUXT_PUBLIC_BASE_URL can override these values at runtime. ```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. } } } ``` -------------------------------- ### Creating a Custom Fetch Composable Source: https://nuxt.com/docs/3.x/examples/advanced/use-custom-fetch-composable Define a composable function to encapsulate fetch logic. This example shows how to create a basic composable for making GET requests. ```javascript import { ref } from 'vue' export function useCustomFetch(url: string, options: any = {}) { const data = ref(null) const error = ref(null) const loading = ref(false) const fetchData = async () => { loading.value = true error.value = null try { const response = await fetch(url, options) if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`) } data.value = await response.json() } catch (e) { error.value = e } finally { loading.value = false } } return { data, error, loading, fetchData } } ``` -------------------------------- ### Create Nuxt Project with pnpm Source: https://nuxt.com/docs/3.x/getting-started/installation Use this command to create a new Nuxt starter project with pnpm. Replace `` with your desired project directory name. ```bash pnpm create nuxt@latest -t v3 ``` -------------------------------- ### Creating a Custom Fetch Composable Source: https://nuxt.com/docs/3.x/examples/advanced/use-custom-fetch-composable Define a composable function that encapsulates fetch logic. This example shows how to set up a basic composable for making GET requests. ```javascript import { ref } from 'vue' export function useFetchComposable(url) { const data = ref(null) const error = ref(null) const loading = ref(true) const fetchData = async () => { loading.value = true error.value = null try { const response = await fetch(url) if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`) } data.value = await response.json() } catch (e) { error.value = e } finally { loading.value = false } } fetchData() return { data, error, loading, fetchData } } ``` -------------------------------- ### Create a Custom Fetch Composable Source: https://nuxt.com/docs/3.x/examples/advanced/use-custom-fetch-composable Define a composable function to abstract fetch requests. This example shows how to create a reusable function for making GET requests. ```javascript import { ref } from 'vue' export const useFetchCustom = (url) => { const data = ref(null) const error = ref(null) const fetchData = async () => { try { const response = await fetch(url) if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`) } data.value = await response.json() } catch (e) { error.value = e } } return { data, error, fetchData } } ``` -------------------------------- ### Middleware Directory Structure Example Source: https://nuxt.com/docs/3.x/directory-structure/middleware Illustrates the default directory structure for middleware files in a Nuxt 3 project. ```bash -| middleware/ ---| analytics.global.ts ---| setup.global.ts ---| auth.ts ``` -------------------------------- ### Create Nuxt Project with npm Source: https://nuxt.com/docs/3.x/getting-started/installation Use this command to create a new Nuxt starter project with npm. Replace `` with your desired project directory name. ```bash npm create nuxt@latest -- -t v3 ``` -------------------------------- ### Create a Custom Fetch Composable Source: https://nuxt.com/docs/3.x/examples/advanced/use-custom-fetch-composable Define a composable function to encapsulate your fetch logic. This example shows how to create a reusable `useFetch` composable for making GET requests. ```javascript import { ref } from 'vue' export function useFetch(url: string) { const data = ref(null) const error = ref(null) const loading = ref(false) const fetchData = async () => { loading.value = true error.value = null try { const response = await fetch(url) if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`) } data.value = await response.json() } catch (e: any) { error.value = e.message console.error('Fetch error:', e) } finally { loading.value = false } } return { data, error, loading, fetchData } } ``` -------------------------------- ### Create Nuxt Module with bun Source: https://nuxt.com/docs/3.x/guide/concepts/modules Use this command to initialize a new Nuxt module project with the official starter template using bun. ```bash bun create nuxt --template=module my-module ``` -------------------------------- ### defineNuxtModule Source: https://nuxt.com/docs/3.x/api/kit/modules Defines a Nuxt module, merging defaults, installing hooks, and providing a setup function for customization. It allows modules to be configurable via `nuxt.config` using a specified `configKey`. ```APIDOC ## `defineNuxtModule` ### Description Defines a Nuxt module, automatically merging defaults with user-provided options, installing any provided hooks, and calling an optional setup function for full control. ### Usage ```javascript import { defineNuxtModule } from '@nuxt/kit' export default defineNuxtModule({ meta: { name: 'my-module', configKey: 'myModule', }, defaults: { enabled: true, }, setup (options) { if (options.enabled) { console.log('My Nuxt module is enabled!') } }, }) ``` ### Parameters **definition** : A module definition object or a module function. The module definition object should contain the following properties: | Property | Type | Required | Description | |---|---|---|---| | `meta` | `ModuleMeta` | `false` | Metadata of the module. It defines the module name, version, config key and compatibility. | | `defaults` | `T | ((nuxt: Nuxt) => T)` | `false` | Default options for the module. If a function is provided, it will be called with the Nuxt instance as the first argument. | | `schema` | `T` | `false` | Schema for the module options. If provided, options will be applied to the schema. | | `hooks` | `Partial` | `false` | Hooks to be installed for the module. If provided, the module will install the hooks. | | `moduleDependencies` | `Record | ((nuxt: Nuxt) => Record)` | `false` | Dependencies on other modules with version constraints and configuration. Can be an object or a function that receives the Nuxt instance. See example. | | `onInstall` | `(nuxt: Nuxt) => Awaitable` | `false` | Lifecycle hook called when the module is first installed. Requires `meta.name` and `meta.version` to be defined. | | `onUpgrade` | `(nuxt: Nuxt, options: T, previousVersion: string) => Awaitable` | `false` | Lifecycle hook called when the module is upgraded to a newer version. Requires `meta.name` and `meta.version` to be defined. | | `setup` | `(this: void, resolvedOptions: T, nuxt: Nuxt) => Awaitable` | `false` | Setup function for the module. If provided, the module will call the setup function. | ### Examples #### Using `configKey` to Make Your Module Configurable When defining a Nuxt module, you can set a `configKey` to specify how users should configure the module in their `nuxt.config`. ```javascript import { defineNuxtModule } from '@nuxt/kit' export default defineNuxtModule({ meta: { name: 'my-module', configKey: 'myModule', }, defaults: { // Module options enabled: true, }, setup (options) { if (options.enabled) { console.log('My Nuxt module is enabled!') } }, }) ``` Users can provide options for this module under the corresponding key in `nuxt.config`. ```javascript export default defineNuxtConfig({ myModule: { enabled: false, }, }) ``` Users can also completely disable a module by setting the config key to `false`. This prevents the module's setup function from running while still generating types for module options. ```javascript export default defineNuxtConfig({ // Disable the module entirely myModule: false, }) ``` This is particularly useful when you want to disable modules inherited from Nuxt layers. ``` -------------------------------- ### Auto Imports Example in app.vue Source: https://nuxt.com/docs/3.x/examples/features/auto-imports This script setup uses auto-imports for `ref`, `sayHello`, `CustomInput`, and `UButton`. The `sayHello` composable and `CustomInput` component are expected to be auto-imported from their respective directories. ```vue ``` -------------------------------- ### Start Nuxt Development Server Source: https://nuxt.com/docs/3.x/api/commands Starts a development server with hot module replacement. Options can configure the working directory, log level, environment variables, port, host, and more. Environment variables like NUXT_PORT can also set the port and host. ```bash npx nuxt dev [ROOTDIR] [--cwd=] [--logLevel=] [--dotenv] [--envName] [-e, --extends=] [--clear] [--no-f, --no-fork] [-p, --port] [-h, --host] [--clipboard] [-o, --open] [--https] [--publicURL] [--qr] [--public] [--tunnel] [--sslCert] [--sslKey] ``` -------------------------------- ### Example v4 Folder Structure Source: https://nuxt.com/docs/3.x/getting-started/upgrade Illustrates the new default directory layout in Nuxt 4, with `app/` as the primary source directory. ```tree .output/ .nuxt/ app/ assets/ components/ composables/ layouts/ middleware/ pages/ plugins/ utils/ app.config.ts app.vue router.options.ts content/ layers/ modules/ node_modules/ public/ shared/ types/ utils/ server/ api/ middleware/ plugins/ routes/ utils/ nuxt.config.ts ``` -------------------------------- ### Accessing Route Parameters in Nuxt 3 Source: https://nuxt.com/docs/3.x/getting-started/routing Use the `useRoute()` composable within a ` ``` -------------------------------- ### Get Query Parameters in Nuxt Server API Source: https://nuxt.com/docs/3.x/directory-structure/server Use getQuery(event) to retrieve query parameters from the request URL. The example shows how to access 'foo' and 'baz' query parameters. ```typescript export default defineEventHandler((event) => { const query = getQuery(event) return { a: query.foo, b: query.baz } }) ```