### Using Lifecycle Hooks for Module Installation and Upgrade
Source: https://nuxt.com/docs/4.x/api/kit/modules
Implement `onInstall` and `onUpgrade` hooks to manage one-time setup tasks, migrations, or cleanup operations when a module is installed or updated.
```APIDOC
## Using Lifecycle Hooks for Module Installation and Upgrade
### Description
You can define lifecycle hooks that run when your module is first installed or upgraded to a new version. These hooks are useful for performing one-time setup tasks, database migrations, or cleanup operations. For lifecycle hooks to work, you **must** provide both `meta.name` and `meta.version` in your module definition. The hooks use these values to track the module's installation state in the project's `.nuxtrc` file. Lifecycle hooks run before the main `setup` function, and if a hook throws an error, it's logged but doesn't stop the build process.
### Hooks
- **`onInstall`**: Runs only once when the module is first added to a project.
- **`onUpgrade`**: Runs each time the module version increases (using semver comparison) — but only once for each version bump.
### Method
`defineNuxtModule` with `onInstall` and `onUpgrade` properties.
### Endpoint
N/A (Module definition)
### Parameters
#### Module Definition Parameters
- **meta.name** (string) - Required. The name of the module.
- **meta.version** (string) - Required. The current version of the module (semver format).
- **onInstall** (function) - Callback function executed on module installation.
- **onUpgrade** (function) - Callback function executed on module upgrade.
### Request Example
```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
}
},
})
```
### Response
#### Success Response (N/A)
N/A
#### Response Example
```
Setting up my-awesome-module for the first time!
```
(or)
```
Upgrading my-awesome-module from 1.1.0 to 1.2.0
```
```
--------------------------------
### Handle Module Installation and Upgrade Lifecycle Hooks
Source: https://nuxt.com/docs/4.x/api/kit
Shows how to use onInstall and onUpgrade hooks to perform one-time setup tasks or migrations. Requires meta.name and meta.version to be defined.
```typescript
import { defineNuxtModule } from '@nuxt/kit'
import semver from 'semver'
export default defineNuxtModule({
meta: {
name: 'my-awesome-module',
version: '1.2.0',
configKey: 'myAwesomeModule',
},
defaults: {
apiKey: '',
enabled: true,
},
onInstall (nuxt) {
console.log('Setting up my-awesome-module for the first time!')
},
onUpgrade (nuxt, options, previousVersion) {
console.log(`Upgrading my-awesome-module from ${previousVersion} to 1.2.0`)
if (semver.lt(previousVersion, '1.1.0')) {
console.log('⚠️ Breaking changes in 1.1.0')
}
},
setup (options, nuxt) {
if (options.enabled) {}
},
})
```
--------------------------------
### Programmatically Install Nuxt Module
Source: https://nuxt.com/docs/4.x/api/kit
Illustrates how to programmatically install a Nuxt module within the `setup` function of another module using the `installModule` utility. This method is deprecated in favor of `moduleDependencies`.
```javascript
import { defineNuxtModule, installModule } from '@nuxt/kit'
export default defineNuxtModule({
async setup () {
await installModule('@nuxtjs/fontaine', {
fonts: [
{
family: 'Roboto',
fallbacks: ['Impact'],
fallbackName: 'fallback-a',
},
],
})
},
})
```
--------------------------------
### Programmatic Module Installation (`installModule`)
Source: https://nuxt.com/docs/4.x/api/kit
Explains how to programmatically install Nuxt modules within your module's setup function using `installModule`. This method is deprecated in favor of `moduleDependencies`.
```APIDOC
## `installModule` (Deprecated)
### Description
The `installModule` function allows you to programmatically install other Nuxt modules from within your module's `setup` function. This is useful for creating modules that depend on other modules. Note that this function is deprecated and `moduleDependencies` should be used instead.
### Method
`installModule`
### Endpoint
N/A (Internal Nuxt function)
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
N/A
#### Function Parameters
- **moduleToInstall** (string | NuxtModule) - Required - The name of the module to install or the module object itself.
- **inlineOptions** (any) - Optional - An object containing options to be passed to the installed module's `setup` function.
- **nuxt** (Nuxt) - Optional - The Nuxt instance. If not provided, it will be retrieved from the context.
### Request 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',
},
],
})
},
})
```
### Response
N/A (Asynchronous operation, returns a Promise)
#### Success Response (200)
N/A
#### Response Example
N/A
### Error Handling
- Throws an error if the module cannot be installed.
```
--------------------------------
### Define Nuxt Plugin - Object Syntax with Setup and Hooks
Source: https://nuxt.com/docs/4.x/api/utils/define-nuxt-plugin
This example showcases the object syntax for `defineNuxtPlugin`, including advanced configuration like `name`, `enforce`, `setup` for asynchronous operations, and `hooks` for lifecycle events.
```typescript
export default defineNuxtPlugin({
name: 'my-plugin',
enforce: 'pre',
async setup (nuxtApp) {
// Plugin setup logic
const data = await $fetch('/api/config')
return {
provide: {
config: data,
},
}
},
hooks: {
'app:created' () {
console.log('App created!')
},
},
})
```
--------------------------------
### Nuxt Module Lifecycle Hooks
Source: https://nuxt.com/docs/4.x/guide/modules/best-practices
Demonstrates the use of lifecycle hooks like `onInstall`, `onUpgrade`, and `setup` within a Nuxt module. This pattern is useful for performing one-time setup tasks, handling version-specific migrations, and regular setup logic that runs on every build.
```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({ /* ... */ })
},
})
```
--------------------------------
### Start Nuxt Development Server
Source: https://nuxt.com/docs/4.x/community/framework-contribution
Starts the Nuxt development server, allowing you to test your changes locally. This command typically rebuilds the project and launches a local instance.
```bash
pnpm dev
```
--------------------------------
### Install Nuxt Content Module
Source: https://nuxt.com/docs/4.x/directory-structure/content
Use the Nuxt CLI to automatically install and configure the @nuxt/content module in your project.
```bash
npx nuxt module add content
```
--------------------------------
### Configure Nuxt using .nuxtrc flat syntax
Source: https://nuxt.com/docs/4.x/directory-structure/nuxtrc
Example of defining SSR settings, devtools, and modules within a .nuxtrc file. Note that modules are added using array syntax and setups are managed internally by Nuxt.
```ini
# Disable SSR
ssr=false
# Configuration for `@nuxt/devtools`
devtools.enabled=true
# Add Nuxt modules
modules[]=@nuxt/image
modules[]=nuxt-security
# Module setups (automatically added by Nuxt)
setups.@nuxt/test-utils="3.23.0"
```
--------------------------------
### Install Dependencies
Source: https://nuxt.com/docs/4.x/bridge
Commands to install project dependencies using various package managers.
```bash
npm install
```
```bash
yarn install
```
```bash
pnpm install
```
```bash
bun install
```
```bash
deno install
```
--------------------------------
### Define Nuxt Plugin - Basic Provide Example
Source: https://nuxt.com/docs/4.x/api/utils/define-nuxt-plugin
A simple example of a Nuxt plugin using the function syntax to provide a global method `hello` to the Nuxt application instance.
```typescript
export default defineNuxtPlugin((nuxtApp) => {
// Add a global method
return {
provide: {
hello: (name: string) => `Hello ${name}!`,
},
}
})
```
--------------------------------
### Update Build and Start Scripts for Server Target
Source: https://nuxt.com/docs/4.x/bridge/nitro
For server-targeted applications (not static), ensure your 'build' script uses 'nuxi build' and your 'start' script uses 'nuxi preview' in your package.json.
```json
{
"scripts": {
"build": "nuxi build",
"start": "nuxi preview"
}
}
```
--------------------------------
### Nuxt App Configuration Setup
Source: https://nuxt.com/docs/4.x/getting-started/configuration
Provides an example of configuring app.config.ts to expose public variables determined at build time. These settings, like titles and themes, are bundled and can be accessed using the useAppConfig composable.
```typescript
export default defineNuxtConfig({
title: 'Hello Nuxt',
theme: {
dark: true,
colors: {
primary: '#ff0000',
},
},
})
```
```typescript
```
--------------------------------
### useFetch and $fetch Example
Source: https://nuxt.com/docs/4.x/getting-started/data-fetching
Demonstrates the basic usage of useFetch for server-side data fetching and $fetch for client-side form submissions.
```APIDOC
## GET /api/data & POST /api/submit
### Description
This example shows how to use `useFetch` to get data on the server and `useFetch` to submit form data using a POST request.
### Method
GET, POST
### Endpoint
/api/data, /api/submit
### Request Body (for POST /api/submit)
#### Request Body
- **body** (object) - Required - The form data to submit.
### Request Example (for POST /api/submit)
```json
{
"example": "My form data"
}
```
### Response (for GET /api/data)
#### Success Response (200)
- **data** (any) - The fetched data.
### Response Example (for GET /api/data)
```json
{
"example": "// Fetched data"
}
```
```
--------------------------------
### installModule Utility
Source: https://nuxt.com/docs/4.x/api/kit/modules
The installModule function allows for programmatic installation of Nuxt modules, including passing custom inline options to the module's setup function.
```APIDOC
## installModule
### Description
Installs a specified Nuxt module programmatically. Note that this is deprecated in favor of the moduleDependencies option in defineNuxtModule.
### Method
Async Function
### Parameters
#### Path Parameters
- **moduleToInstall** (string | NuxtModule) - Required - The module name or module object to install.
- **inlineOptions** (any) - Optional - Configuration options passed to the module's setup function.
- **nuxt** (Nuxt) - Optional - The Nuxt instance context.
### Request Example
await installModule('@nuxtjs/fontaine', { fonts: [{ family: 'Roboto', fallbacks: ['Impact'] }] });
### Response
#### Success Response (Promise)
- **void** - Returns a promise that resolves when the module is installed.
```
--------------------------------
### Set Environment Variables in Production
Source: https://nuxt.com/docs/4.x/directory-structure/env
Shows how to pass environment variables directly to the Node.js process when starting the production server.
```bash
DATABASE_HOST=mydatabaseconnectionstring node .output/server/index.mjs
```
--------------------------------
### SFC Style Block with Stylus
Source: https://nuxt.com/docs/4.x/getting-started/styling
Provides an example of using Stylus syntax in a Single File Component's style block. Stylus must be installed.
```html
```
--------------------------------
### Installing NPM Stylesheets
Source: https://nuxt.com/docs/4.x/getting-started/styling
Provides commands for installing external CSS libraries via various package managers.
```bash
npm install animate.css
yarn add animate.css
pnpm install animate.css
bun install animate.css
deno install npm:animate.css
```
--------------------------------
### Start Nuxt development server
Source: https://nuxt.com/docs/4.x/api/commands/devtools
Starts the Nuxt development server with hot module replacement enabled, typically accessible at http://localhost:3000.
```bash
npx nuxt dev
```
--------------------------------
### Running Nuxt Preview Command
Source: https://nuxt.com/docs/4.x/api/commands/preview
The preview command starts a local server to serve the application after a build. It accepts optional arguments for directory specification, port configuration, and environment variable loading.
```bash
npx nuxt preview [ROOTDIR] [--cwd=] [--logLevel=] [--envName] [-e, --extends=] [-p, --port] [--dotenv]
```
--------------------------------
### Setup Nuxt End-to-End Test Context
Source: https://nuxt.com/docs/4.x/getting-started/testing
Initializes the test context for end-to-end testing in Nuxt using @nuxt/test-utils/e2e. The `setup` function prepares the testing environment, potentially including building the Nuxt app and launching a server.
```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', () => {
// ...
})
})
```
--------------------------------
### Install Dependencies (deno)
Source: https://nuxt.com/docs/4.x/bridge/overview
Installs dependencies using deno after updating the Nuxt version. This ensures all packages are correctly installed.
```bash
deno install
```
--------------------------------
### Install Nuxt Dependencies with pnpm
Source: https://nuxt.com/docs/4.x/community/framework-contribution
Installs all project dependencies using pnpm, ensuring that the installed versions match the lockfile. This is a crucial step after cloning the repository.
```bash
pnpm install --frozen-lockfile
```
--------------------------------
### Universal Rendering Example in Nuxt.js
Source: https://nuxt.com/docs/4.x/guide/concepts/rendering
This example demonstrates universal rendering in Nuxt.js, showing how refs and event handlers execute on both server and client environments. It highlights the difference between server-initialized code and client-only interactive code.
```Vue.js
Count: {{ counter }}
```
--------------------------------
### GET /api/hello/:name
Source: https://nuxt.com/docs/4.x/directory-structure/server
Demonstrates how to use dynamic route parameters in Nuxt server routes.
```APIDOC
## GET /api/hello/:name
### Description
Retrieves a personalized greeting using a dynamic name parameter from the URL.
### Method
GET
### Endpoint
/api/hello/:name
### Parameters
#### Path Parameters
- **name** (string) - Required - The name to be included in the greeting.
### Request Example
GET /api/hello/nuxt
### Response
#### Success Response (200)
- **body** (string) - Returns 'Hello, nuxt!'
#### Response Example
"Hello, nuxt!"
```
--------------------------------
### Install Nuxt 4 using Package Managers
Source: https://nuxt.com/docs/4.x/getting-started/upgrade
Provides installation commands for upgrading to Nuxt 4 using various package managers including npm, yarn, pnpm, bun, and deno. This is the first step in migrating a Nuxt 3 application to Nuxt 4.
```bash
npm install nuxt@^4.0.0
```
```bash
yarn add nuxt@^4.0.0
```
```bash
pnpm add nuxt@^4.0.0
```
```bash
bun add nuxt@^4.0.0
```
```bash
deno add npm:nuxt@^4.0.0
```
--------------------------------
### CLI Command: nuxt dev
Source: https://nuxt.com/docs/4.x/api/commands
Starts the Nuxt development server with hot module replacement at http://localhost:3000.
```APIDOC
## CLI Command: nuxt dev
### Description
The `dev` command starts a development server with hot module replacement. It sets `process.env.NODE_ENV` to `development` and allows for various configuration overrides via flags.
### Method
CLI Command
### Endpoint
npx nuxt dev [ROOTDIR]
### Parameters
#### Path Parameters
- **ROOTDIR** (string) - Optional - Specifies the working directory (default: ".")
#### Options
- **--cwd** (string) - Optional - Specify the working directory, takes precedence over ROOTDIR.
- **--logLevel** (string) - Optional - Specify build-time log level (silent, info, verbose).
- **-p, --port** (number) - Optional - Port to listen on.
- **-h, --host** (string) - Optional - Host to listen on.
- **-o, --open** (boolean) - Optional - Open the URL in the browser.
- **--https** (boolean) - Optional - Enable HTTPS.
- **--qr** (boolean) - Optional - Display the QR code of the public URL.
### Request Example
`npx nuxt dev --port 3000 --open`
### Response
#### Success Response (Console Output)
- **URL** (string) - The local and network addresses where the development server is running.
```
--------------------------------
### usePreviewMode Full Example
Source: https://nuxt.com/docs/4.x/api/composables/use-preview-mode
An example demonstrating how to use `usePreviewMode` in a Nuxt page to conditionally render content and control preview mode.
```APIDOC
## Example
The example below creates a page where part of a content is rendered only in preview mode.
### app/pages/some-page.vue
```vue
Some base content
Only preview content: {{ state.token }}
```
### Running the Example
Now you can generate your site and serve it:
Terminal
```bash
npx nuxt generate
npx nuxt preview
```
Then you can see your preview page by adding the query param `preview` to the end of the page you want to see once, for example `http://localhost:3000/?preview=true`.
**Note:** `usePreviewMode` should be tested locally with `nuxt generate` and then `nuxt preview` rather than `nuxt dev`. (The preview command is not related to preview mode.)
```
--------------------------------
### Enable Dependency Installation for Remote Layers
Source: https://nuxt.com/docs/4.x/guide/going-further/layers
Shows how to configure a remote layer to automatically install its npm dependencies by setting the install option to true.
```typescript
export default defineNuxtConfig({
extends: [
['github:username/repoName', { install: true }],
],
})
```
--------------------------------
### Nuxt App Configuration and Routing Setup
Source: https://nuxt.com/docs/4.x/examples/routing
This script sets up the main App component for a Nuxt application. It defines navigation links and uses NuxtExample and NuxtPage components to render the application's content and routing.
```vue
Current route: {{ route.path }}
```
--------------------------------
### Nuxt Project Structure Example
Source: https://nuxt.com/docs/4.x/api/nuxt-config
Illustrates a typical Nuxt project folder structure when using a custom `srcDir` like 'app/'. This includes directories for assets, components, pages, server files, and configuration files.
```plaintext
-| app/
---| assets/
---| components/
---| composables/
---| layouts/
---| middleware/
---| pages/
---| plugins/
---| utils/
---| app.config.ts
---| app.vue
---| error.vue
-| server/
-| shared/
-| public/
-| modules/
-| layers/
-| nuxt.config.ts
-| package.json
```
--------------------------------
### Install Nuxt Auth Utils
Source: https://nuxt.com/docs/4.x/guide/recipes/sessions-and-authentication
Command to add the nuxt-auth-utils module to your Nuxt project.
```bash
npx nuxt module add auth-utils
```
--------------------------------
### Nuxt Module Lifecycle Hooks: `onInstall` and `onUpgrade`
Source: https://nuxt.com/docs/4.x/api/kit/modules
Implement `onInstall` and `onUpgrade` lifecycle hooks in Nuxt modules for one-time setup or version-specific tasks. These hooks require `meta.name` and `meta.version` and run before the `setup` function, aiding in tasks like configuration setup, database migrations, or cleanup.
```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
}
},
})
```
--------------------------------
### Install Dependencies (bun)
Source: https://nuxt.com/docs/4.x/bridge/overview
Reinstalls project dependencies using bun after updating the Nuxt version. This ensures all packages are correctly installed.
```bash
bun install
```
--------------------------------
### Install Nuxt Test Utilities and Playwright
Source: https://nuxt.com/docs/4.x/getting-started/testing
Installs the necessary packages for end-to-end testing with Nuxt and Playwright using various package managers.
```bash
npm i --save-dev @playwright/test @nuxt/test-utils
```
```bash
yarn add --dev @playwright/test @nuxt/test-utils
```
```bash
pnpm add -D @playwright/test @nuxt/test-utils
```
```bash
bun add --dev @playwright/test @nuxt/test-utils
```
```bash
deno add --dev npm:@playwright/test npm:@nuxt/test-utils
```
--------------------------------
### Install Vite Plugin
Source: https://nuxt.com/docs/4.x/guide/recipes/vite-plugin
Commands to install the @rollup/plugin-yaml Vite plugin using various package managers.
```bash
npm install @rollup/plugin-yaml
```
```bash
yarn add @rollup/plugin-yaml
```
```bash
pnpm add @rollup/plugin-yaml
```
```bash
bun add @rollup/plugin-yaml
```
```bash
deno add npm:@rollup/plugin-yaml
```
--------------------------------
### Mount a Vue Component with `mountSuspended`
Source: https://nuxt.com/docs/4.x/getting-started/testing
This example demonstrates how to use the `mountSuspended` helper from `@nuxt/test-utils/runtime` to mount a Vue component within the Nuxt environment. This allows the component to leverage Nuxt's runtime features, including async setup and injections from Nuxt plugins. The component `SomeComponent` is assumed to be auto-imported.
```typescript
// @noErrors
import { expect, it } from 'vitest'
import type { Component } from 'vue'
declare module '#components' {
export const SomeComponent: Component
}
// ---cut---
// tests/components/SomeComponents.nuxt.spec.ts
import { mountSuspended } from '@nuxt/test-utils/runtime'
import { SomeComponent } from '#components'
it('can mount some component', async () => {
const component = await mountSuspended(SomeComponent)
expect(component.text()).toMatchInlineSnapshot(
'"This is an auto-imported component"',
)
})
```
--------------------------------
### Install Nuxt Image Module
Source: https://nuxt.com/docs/4.x/api/components/nuxt-img
Use the Nuxt CLI to add the image module to your project. This is a prerequisite for using the NuxtImg component.
```bash
npx nuxt module add image
```
--------------------------------
### Server-Side Data Hydration with useHydration
Source: https://nuxt.com/docs/4.x/api/composables/use-hydration
This example demonstrates how to use the `useHydration` composable within a Nuxt plugin to manage the state of a `MyStore` instance. It defines a unique key 'myStoreState', a server-side `get` function to retrieve the store's state, and a client-side `set` function to restore that state during hydration. This ensures that the store's state is synchronized between the server and the client.
```javascript
export default defineNuxtPlugin((nuxtApp) => {
const myStore = new MyStore()
useHydration(
'myStoreState',
() => myStore.getState(),
data => myStore.setState(data)
)
})
```
--------------------------------
### Programmatically Install Nuxt Modules
Source: https://nuxt.com/docs/4.x/api/kit/modules
Illustrates the use of the installModule function to programmatically install and configure a Nuxt module. Note that this method is deprecated in favor of moduleDependencies.
```typescript
import { defineNuxtModule, installModule } from '@nuxt/kit'
export default defineNuxtModule({
async setup (options, nuxt) {
await installModule('@nuxtjs/fontaine', {
fonts: [
{
family: 'Roboto',
fallbacks: ['Impact'],
fallbackName: 'fallback-a',
},
],
})
},
})
```
--------------------------------
### Install Nuxt Bridge and Nuxi
Source: https://nuxt.com/docs/4.x/bridge/overview
Installs `@nuxt/bridge` and `nuxi` as development dependencies using various package managers. These are essential for enabling Nuxt Bridge features.
```bash
npm install -D @nuxt/bridge nuxi
```
```bash
yarn add --dev @nuxt/bridge nuxi
```
```bash
pnpm add -D @nuxt/bridge nuxi
```
```bash
bun add -D @nuxt/bridge nuxi
```
```bash
deno add -D npm:@nuxt/bridge npm:nuxi
```
--------------------------------
### Registering a Nuxt Build Hook
Source: https://nuxt.com/docs/4.x/api/advanced
Demonstrates how to register a hook within a Nuxt module or configuration file to intercept build-time events. This example shows how to use the 'ready' hook to perform actions once the Nuxt instance is initialized.
```javascript
export default defineNuxtModule({
setup(options, nuxt) {
nuxt.hook('ready', (nuxt) => {
console.log('Nuxt is ready!');
});
}
});
```
```typescript
import { defineNuxtModule } from '@nuxt/kit';
export default defineNuxtModule({
setup(options, nuxt) {
nuxt.hook('ready', (nuxt) => {
console.log('Nuxt is ready!');
});
}
});
```
--------------------------------
### Install Nuxi CLI Tool
Source: https://nuxt.com/docs/4.x/bridge/nitro
Install the 'nuxi' command-line interface as a development dependency for managing your Nuxt 3-compatible project. This tool is essential for running development servers, building, and generating your application.
```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
```
--------------------------------
### Install vue-gtag-next using Package Managers
Source: https://nuxt.com/docs/4.x/directory-structure/app/plugins
These snippets demonstrate how to install the 'vue-gtag-next' package, a Vue.js plugin for Google Analytics, using various package managers including npm, yarn, pnpm, bun, and deno.
```bash
npm install --save-dev vue-gtag-next
```
```bash
yarn add --dev vue-gtag-next
```
```bash
pnpm add -D vue-gtag-next
```
```bash
bun add -D vue-gtag-next
```
```bash
deno add -D npm:vue-gtag-next
```
--------------------------------
### Configure Auto-Import Directories
Source: https://nuxt.com/docs/4.x/api/configuration/nuxt-config
Example of extending the auto-import functionality by adding custom directories to the imports configuration.
```javascript
export default defineNuxtConfig({
imports: {
dirs: ['stores'],
},
})
```
--------------------------------
### Install Stylus Preprocessor in Nuxt
Source: https://nuxt.com/docs/4.x/getting-started/styling
Installs the Stylus preprocessor for use with Stylus files in your Nuxt project. This is a development dependency.
```bash
npm install -D stylus
```
--------------------------------
### Basic Data Fetching with useFetch
Source: https://nuxt.com/docs/4.x/api/composables/use-fetch
Demonstrates the standard implementation of useFetch within a Vue component setup function, including options like picking specific fields from the response.
```typescript
```
--------------------------------
### Auth Middleware Setup
Source: https://nuxt.com/docs/4.x/api/kit/pages
This snippet demonstrates how to define and globally add a custom authentication middleware using `defineNuxtModule` and `addRouteMiddleware` from Nuxt Kit.
```APIDOC
## Module Setup for Auth Middleware
### Description
This code defines a Nuxt module that automatically adds an authentication route middleware globally. It resolves the middleware path and applies it with a prepend option.
### Method
defineNuxtModule
### Endpoint
N/A (Module setup)
### Parameters
#### Request Body
- **No direct request body for module setup**
### Request Example
```typescript
// runtime/auth.ts
import { addRouteMiddleware, createResolver, defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup () {
const { resolve } = createResolver(import.meta.url)
addRouteMiddleware({
name: 'auth',
path: resolve('runtime/auth'),
global: true,
}, { prepend: true })
},
})
```
### Response
#### Success Response (N/A for module setup)
#### Response Example
N/A
```
--------------------------------
### Nuxt Init Command
Source: https://nuxt.com/docs/4.x/api/commands/info
Initializes a fresh Nuxt project.
```APIDOC
## CLI COMMAND: npx nuxi@latest init
### Description
The init command initializes a fresh Nuxt project structure in the target directory.
### Usage
`npx nuxi@latest init `
```
--------------------------------
### Initialize New Nuxt Project (CLI)
Source: https://nuxt.com/docs/4.x/api/commands/info
The `nuxt init` command is used to initialize a new, fresh Nuxt project. It sets up the basic project structure and configuration files, allowing developers to start building their application quickly.
```bash
create nuxt
```
--------------------------------
### Nuxt Config with Layers
Source: https://nuxt.com/docs/4.x/examples/advanced/config-extends
Configuration example for Nuxt 4.x demonstrating the use of the 'extends' key to define layers. This allows for a base Nuxt application to be extended and customized.
```typescript
export default defineNuxtConfig({
extends: ['./base'],
modules: [
'@nuxt/examples-ui'
]
})
```
--------------------------------
### defineNuxtModule
Source: https://nuxt.com/docs/4.x/api/kit
Defines a Nuxt module, merging defaults, installing hooks, and providing a setup function for customization.
```APIDOC
## `defineNuxtModule`
### Description
Define a Nuxt module, automatically merging defaults with user provided options, installing any hooks that are provided, 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.
```
--------------------------------
### Simple Vitest Configuration
Source: https://nuxt.com/docs/4.x/getting-started/testing
A basic configuration setup that defaults all tests to run within the Nuxt runtime environment.
```typescript
import { defineVitestConfig } from '@nuxt/test-utils/config'
import { fileURLToPath } from 'node:url'
export default defineVitestConfig({
test: {
environment: 'nuxt',
},
})
```
--------------------------------
### Define a Nuxt Module with Options
Source: https://nuxt.com/docs/4.x/api/kit
Demonstrates how to define a Nuxt module using `defineNuxtModule`. It includes meta information, default options, and a setup function that logs a message if the module is enabled. This allows for configurable modules in Nuxt.
```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!')
}
},
})
```
--------------------------------
### Install Nuxt Testing Dependencies
Source: https://nuxt.com/docs/4.x/getting-started/testing
Installs the required testing packages including @nuxt/test-utils, vitest, and supporting libraries for DOM simulation and browser testing.
```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
```
```bash
pnpm add -D @nuxt/test-utils vitest @vue/test-utils happy-dom playwright-core
```
```bash
bun add --dev @nuxt/test-utils vitest @vue/test-utils happy-dom playwright-core
```
--------------------------------
### Run Nuxt Node.js Server Entry Point
Source: https://nuxt.com/docs/4.x/getting-started/deployment
This command launches the production Nuxt server built with the Node.js preset. It listens on a specified port and host, respecting environment variables for configuration. It's ideal for deploying to any Node.js hosting environment.
```bash
node .output/server/index.mjs
```
--------------------------------
### Applying response headers in Nuxt pages
Source: https://nuxt.com/docs/4.x/api/composables/use-response-header
An example of using useResponseHeader within a Vue component's setup script to inject a custom header into the server response for a specific route.
```vue
Test page with custom header
```
--------------------------------
### Install Nuxt Kit Dependency
Source: https://nuxt.com/docs/4.x/guide/going-further/kit
Add @nuxt/kit to the dependencies section of your package.json file. It is recommended to explicitly install this package to ensure version compatibility with Nuxt.
```json
{
"dependencies": {
"@nuxt/kit": "npm:@nuxt/kit-nightly@latest"
}
}
```
--------------------------------
### Install Dependencies for @vue/test-utils Unit Testing
Source: https://nuxt.com/docs/4.x/getting-started/testing
Installs necessary development dependencies for unit testing Vue components with @vue/test-utils and Vitest. This includes Vitest itself, the testing utility, a DOM environment, and the Vite Vue plugin.
```npm
npm i --save-dev vitest @vue/test-utils happy-dom @vitejs/plugin-vue
```
```yarn
yarn add --dev vitest @vue/test-utils happy-dom @vitejs/plugin-vue
```
```pnpm
pnpm add -D vitest @vue/test-utils happy-dom @vitejs/plugin-vue
```
```bun
bun add --dev vitest @vue/test-utils happy-dom @vitejs/plugin-vue
```
--------------------------------
### Create a Nuxt Layer Project
Source: https://nuxt.com/docs/4.x/guide/going-further/layers
Initialize a new Nuxt layer project using the `create nuxt` command with the `--template layer` flag. This sets up a basic directory structure for a reusable layer.
```bash
npm create nuxt -- --template layer nuxt-layer
```
--------------------------------
### Composable Function Example (Nuxt Layers)
Source: https://nuxt.com/docs/4.x/examples/advanced/config-extends
An example of a composable function (`useFoo`) that might be defined within a Nuxt layer. This function is intended to be used within the Nuxt application.
```javascript
export const useFoo = () => {
const foo = useState('foo', () => 'foo')
const bar = process.server ? useRuntimeConfig().bar : ''
return { foo, bar }
}
```
--------------------------------
### Dynamic Route Parameter Access (Vue Composition API)
Source: https://nuxt.com/docs/4.x/directory-structure/app/pages
Shows how to access dynamic route parameters using the `useRoute` composable function in the Composition API. This provides a reactive way to get route information within `
```
--------------------------------
### Create a Server API Route
Source: https://nuxt.com/docs/4.x/directory-structure/modules
Example of a simple server event handler used within a local module to return JSON data.
```typescript
export default defineEventHandler(() => {
return { hello: 'world' }
})
```
--------------------------------
### CLI Command: nuxt prepare
Source: https://nuxt.com/docs/4.x/api/commands/prepare
The prepare command initializes the .nuxt directory and generates necessary type definitions for the project.
```APIDOC
## CLI COMMAND: nuxt prepare
### Description
The `prepare` command creates a `.nuxt` directory in your application and generates types. This is typically used in CI environments or as a `postinstall` script in `package.json`.
### Usage
`npx nuxt prepare [ROOTDIR] [OPTIONS]`
### Arguments
- **ROOTDIR** (string) - Optional - Specifies the working directory (default: `.`).
### Options
- **--dotenv** (string) - Optional - Path to .env file to load.
- **--cwd** (string) - Optional - Specify the working directory.
- **--logLevel** (string) - Optional - Set log level (silent, info, verbose).
- **--envName** (string) - Optional - Environment to use for configuration overrides.
- **-e, --extends** (string) - Optional - Extend from a specific Nuxt layer.
### Behavior
- Sets `process.env.NODE_ENV` to `production`.
- Generates TypeScript definitions for the project.
```
--------------------------------
### Nuxt 4.x JSX Component Examples
Source: https://nuxt.com/docs/4.x/examples/advanced/jsx
Demonstrates how to create and use components with JSX syntax in Nuxt 4.x. It includes a simple functional component, a component defined with defineComponent and a render function, and an example of combining these components within a JSX structure.
```tsx
```
--------------------------------
### Accessing Nuxt Runtime Context
Source: https://nuxt.com/docs/4.x/api/composables/use-nuxt-app
Demonstrates how to initialize the Nuxt runtime context using the useNuxtApp composable within a Vue setup script.
```typescript
```
--------------------------------
### Start Nuxt with Node Inspector
Source: https://nuxt.com/docs/4.x/guide/going-further/debugging
Launches the Nuxt development server with the Node.js debugger enabled, allowing attachment from Chrome DevTools.
```bash
nuxt dev --inspect
```
--------------------------------
### GET list_documentation_pages
Source: https://nuxt.com/docs/4.x/guide/ai
Lists all available Nuxt documentation pages with their categories and basic information.
```APIDOC
## GET list_documentation_pages
### Description
Lists all available Nuxt documentation pages with their categories and basic information. Supports version filtering.
### Method
GET
### Endpoint
list_documentation_pages
### Parameters
#### Query Parameters
- **version** (string) - Optional - The Nuxt version to filter by (e.g., "3.x", "4.x", or "all").
### Request Example
{
"version": "4.x"
}
### Response
#### Success Response (200)
- **pages** (array) - A list of documentation page objects containing path, title, and category.
#### Response Example
{
"pages": [
{ "path": "/docs/getting-started", "title": "Getting Started", "category": "Guide" }
]
}
```
--------------------------------
### Nuxt File-System Routing Structure
Source: https://nuxt.com/docs/4.x/getting-started/routing
This example demonstrates how Nuxt's file-system routing maps directory structures to URL routes. Files in `pages/` create corresponding routes, with naming conventions for dynamic and nested routes.
```json
{
"routes": [
{
"path": "/about",
"component": "pages/about.vue"
},
{
"path": "/",
"component": "pages/index.vue"
},
{
"path": "/posts/:id",
"component": "pages/posts/[id].vue"
}
]
}
```
--------------------------------
### SFC Style Block with SCSS
Source: https://nuxt.com/docs/4.x/getting-started/styling
Demonstrates using SCSS syntax within a Single File Component's style block. Requires the SCSS preprocessor to be installed.
```html
```
--------------------------------
### Configuring Nuxt Layers
Source: https://nuxt.com/docs/4.x/guide/directory-structure/app/pages
Provides an example of extending a Nuxt application using layers to organize pages across different directories.
```typescript
// some-app/nuxt.config.ts
export default defineNuxtConfig({
})
// nuxt.config.ts
export default defineNuxtConfig({
extends: ['./some-app'],
})
```