### Nested Dynamic Routes Structure Example
Source: https://nitro.build/docs/routing
Demonstrates how to create nested dynamic routes by using subdirectories with bracketed parameter names.
```directory
routes/
api/
[org]/
[repo]/
index.ts <-- /api/:org/:repo
issues.ts <-- /api/:org/:repo/issues
index.ts <-- /api/:org
package.json
```
--------------------------------
### Custom HTML Template Example
Source: https://nitro.build/docs/renderer
An example of a custom HTML template file.
```html
Custom Template
Loading...
```
--------------------------------
### Install Nitro and Vite with bun
Source: https://nitro.build/docs/quick-start
Install the necessary packages for integrating Nitro into an existing Vite project using bun.
```bash
bun
i nitro vite
```
--------------------------------
### Start Development Server with bun
Source: https://nitro.build/docs/quick-start
Run the development server for your Nitro project using bun, with an option to open the browser automatically.
```bash
bun
run dev -- --open
```
--------------------------------
### Install Nitro and Vite with deno
Source: https://nitro.build/docs/quick-start
Install the necessary packages for integrating Nitro into an existing Vite project using deno.
```bash
deno
i npm:nitro vite
```
--------------------------------
### H3 Framework Integration
Source: https://nitro.build/docs/server-entry
Integrating the H3 framework as a server entry. This example sets up a basic GET route that responds with a message.
```typescript
import { H3 } from "h3";
const app = new H3()
app.get("/", () => "⚡️ Hello from H3!");
export default app;
```
--------------------------------
### Hono Framework Integration
Source: https://nitro.build/docs/server-entry
Integrating the Hono framework as a server entry. This example defines a GET route that returns plain text.
```typescript
import { Hono } from "hono";
const app = new Hono();
app.get("/", (c) => c.text("🔥 Hello from Hono!"));
export default app;
```
--------------------------------
### Start Development Server with deno
Source: https://nitro.build/docs/quick-start
Run the development server for your Nitro project using deno, with an option to open the browser automatically.
```bash
deno
run dev -- --open
```
--------------------------------
### Elysia Framework Integration
Source: https://nitro.build/docs/server-entry
Integrating the Elysia framework as a server entry. This example sets up a GET route and compiles the application.
```typescript
import { Elysia } from "elysia";
const app = new Elysia();
app.get("/", () => "🦊 Hello from Elysia!");
export default app.compile();
```
--------------------------------
### Start Development Server with npm
Source: https://nitro.build/docs/quick-start
Run the development server for your Nitro project using npm, with an option to open the browser automatically.
```bash
npm
run dev -- --open
```
--------------------------------
### Start Development Server with pnpm
Source: https://nitro.build/docs/quick-start
Run the development server for your Nitro project using pnpm, with an option to open the browser automatically.
```bash
pnpm
dev -- --open
```
--------------------------------
### WebSocket Open Hook Example
Source: https://nitro.build/docs/websocket
The `open` hook is called when a WebSocket connection is successfully established. Use it to send initial messages or perform setup for the connected peer.
```javascript
open(peer) {
peer.send("Welcome!");
}
```
--------------------------------
### Install Nitro and Vite with npm
Source: https://nitro.build/docs/quick-start
Install the necessary packages for integrating Nitro into an existing Vite project using npm.
```bash
npm
i nitro vite
```
--------------------------------
### Basic Storage Operations
Source: https://nitro.build/docs/storage
Demonstrates setting, getting, and accessing storage with a base prefix. Supports generics for typed return values.
```javascript
import { useStorage } from "nitro/storage";
// Default storage (in-memory)
await useStorage().setItem("test:foo", { hello: "world" });
const value = await useStorage().getItem("test:foo");
// You can specify a base prefix with useStorage(base)
const testStorage = useStorage("test");
await testStorage.setItem("foo", { hello: "world" });
await testStorage.getItem("foo"); // { hello: "world" }
// You can use generics to type the return value
await useStorage<{ hello: string }>("test").getItem("foo");
await useStorage("test").getItem<{ hello: string }>("foo");
```
--------------------------------
### Install Nitro and Vite with yarn
Source: https://nitro.build/docs/quick-start
Install the necessary packages for integrating Nitro into an existing Vite project using yarn.
```bash
yarn
add nitro vite
```
--------------------------------
### Fastify Node.js Framework Integration
Source: https://nitro.build/docs/server-entry
Integrating Fastify as a server entry using the `.node.ts` filename convention. This example defines a GET route and exports the routing.
```typescript
import Fastify from "fastify";
const app = Fastify();
app.get("/", () => "Hello, Fastify with Nitro!");
await app.ready();
export default app.routing;
```
--------------------------------
### HPP Control Flow Example
Source: https://nitro.build/docs/renderer
Illustrates using JavaScript control flow within HPP templates for conditional rendering and loops.
```html
if ($METHOD === 'POST') { ?>
Form submitted!
} else { ?>
} ?>
for (const item of ['a', 'b', 'c']) { ?>
- {{ item }}
} ?>
```
--------------------------------
### Install Nitro and Vite with pnpm
Source: https://nitro.build/docs/quick-start
Install the necessary packages for integrating Nitro into an existing Vite project using pnpm.
```bash
pnpm
i nitro vite
```
--------------------------------
### Storage Shorthand Methods
Source: https://nitro.build/docs/storage
Illustrates using shorthand aliases for common storage operations like getting keys, checking existence, removing items, and getting raw data or metadata.
```javascript
import { useStorage } from "nitro/storage";
// Get all keys under a prefix
const keys = await useStorage("test").getKeys();
// Check if a key exists
const exists = await useStorage().hasItem("test:foo");
// Remove a key
await useStorage().removeItem("test:foo");
// Get raw binary data
const raw = await useStorage().getItemRaw("assets/server:image.png");
// Get metadata (type, etag, mtime, etc.)
const meta = await useStorage("assets/server").getMeta("file.txt");
```
--------------------------------
### Dynamically Mounting Storage Drivers with Plugins
Source: https://nitro.build/docs/storage
Shows how to dynamically add storage mount points at runtime using Nitro plugins, with a Redis example.
```typescript
import { useStorage } from "nitro/storage";
import { definePlugin } from "nitro";
import redisDriver from "unstorage/drivers/redis";
export default definePlugin(() => {
const storage = useStorage()
// Dynamically pass in credentials from runtime configuration, or other sources
const driver = redisDriver({
base: "redis",
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
/* other redis connector options */
})
// Mount driver
storage.mount("redis", driver)
})
```
--------------------------------
### Route Groups Structure Example
Source: https://nitro.build/docs/routing
Shows how to use route groups (folders in parentheses) for organizing routes without affecting the URL path.
```directory
routes/
api/
(admin)/
users.ts <-- /api/users
reports.ts <-- /api/reports
(public)/
index.ts <-- /api
package.json
```
--------------------------------
### Greeting API
Source: https://nitro.build/docs/openapi
Example of defining OpenAPI metadata for a simple greeting route using `defineRouteMeta`.
```APIDOC
## GET /api/hello
### Description
Returns a greeting message.
### Method
GET
### Endpoint
/api/hello
### Responses
#### Success Response (200)
- Description: Successful greeting
### Response Example
{
"message": "Hello, world!"
}
```
--------------------------------
### Filesystem Routing Structure Example
Source: https://nitro.build/docs/routing
Illustrates the directory structure for Nitro's filesystem routing, showing how files map to API endpoints and method-specific routes.
```directory
routes/
api/
test.ts <-- /api/test
hello.get.ts <-- /hello (GET only)
hello.post.ts <-- /hello (POST only)
vite.config.ts
```
--------------------------------
### API Handler Example
Source: https://nitro.build/docs/renderer
An example of a simple API handler that returns a JSON object.
```typescript
import {
defineHandler
} from "nitro";
export default defineHandler((event) => {
return { hello: "API" };
});
```
--------------------------------
### Start Development Server with yarn
Source: https://nitro.build/docs/quick-start
Run the development server for your Nitro project using yarn, with an option to open the browser automatically.
```bash
yarn
dev -- --open
```
--------------------------------
### Example of defineCachedFunction and Cache Key Generation
Source: https://nitro.build/docs/cache
Demonstrates how `defineCachedFunction` is used and the resulting cache key generated based on its configuration and default getKey.
```javascript
import { defineCachedFunction } from "nitro/cache";
const getAccessToken = defineCachedFunction(() => {
return String(Date.now())
}, {
maxAge: 10,
name: "getAccessToken",
getKey: () => "default"
});
```
```text
cache:nitro/functions:getAccessToken:default.json
```
--------------------------------
### Retrieving Asset Metadata
Source: https://nitro.build/docs/storage
Illustrates how to get metadata (content type, ETag, modification time) for server assets.
```typescript
import { useStorage } from "nitro/storage";
const serverAssets = useStorage("assets/server");
const meta = await serverAssets.getMeta("image.png");
// { type: "image/png", etag: "\"...\"", mtime: "2024-01-01T00:00:00.000Z" }
// Useful for setting response headers
const raw = await serverAssets.getItemRaw("image.png");
```
--------------------------------
### Access Server Assets with useStorage
Source: https://nitro.build/docs/assets
Example of how to retrieve a server asset (data.json) from the assets:server mount point within a Nitro handler.
```typescript
import { defineHandler } from "nitro";
export default defineHandler(async () => {
const data = await useStorage("assets:server").get("data.json");
return data;
});
```
--------------------------------
### List Available Tasks via API
Source: https://nitro.build/docs/tasks
This GET endpoint returns a list of all available task names and their descriptions, along with scheduled tasks.
```json
// [GET] /_nitro/tasks
{
"tasks": {
"db:migrate": {
"description": "Run database migrations"
},
"cms:update": {
"description": "Update CMS content"
}
},
"scheduledTasks": [
{
"cron": "* * * * *",
"tasks": [
"cms:update"
]
}
]
}
```
--------------------------------
### Define a Route Handler
Source: https://nitro.build/docs/lifecycle
Define routes in the `routes/` folder to match incoming requests. This example handles a simple API route.
```typescript
export default (event) => ({ world: true })
```
--------------------------------
### Get Database Instance
Source: https://nitro.build/docs/database
Obtain a database instance using `useDatabase`. It defaults to the 'default' connection but can be configured for named connections.
```typescript
import { useDatabase } from "nitro/database";
// Use the default connection
const db = useDatabase();
// Use a named connection
const usersDb = useDatabase("users");
```
--------------------------------
### Configure Custom Public Asset Directories
Source: https://nitro.build/docs/assets
Example Nitro configuration to serve assets from a custom directory with specific caching and URL prefix.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
publicAssets: [
{
baseURL: "build",
dir: "public/build",
maxAge: 3600,
},
],
});
```
--------------------------------
### Production Public Assets Manifest
Source: https://nitro.build/docs/assets
Example of the manifest file created for production public assets, containing metadata like type, etag, mtime, and size.
```json
{
"/image.png": {
"type": "image/png",
"etag": "\"4a0c-6utWq0Kbk5OqDmksYCa9XV8irnM\"",
"mtime": "2023-03-04T21:39:45.086Z",
"size": 18956
},
"/robots.txt": {
"type": "text/plain; charset=utf-8",
"etag": "\"8-hMqyDrA8fJ0R904zgEPs3L55Jls\"",
"mtime": "2023-03-04T21:39:45.086Z",
"size": 8
},
"/video.mp4": {
"type": "video/mp4",
"etag": "\"9b943-4UwfQXKUjPCesGPr6J5j7GzNYGU\"",
"mtime": "2023-03-04T21:39:45.085Z",
"size": 637251
}
}
```
--------------------------------
### Cached Function Cache File Example
Source: https://nitro.build/docs/cache
Example of the JSON file format used for caching function results. It includes expiration time, cached value, modification time, and integrity hash.
```json
{"expires":1677851092249,"value":43991,"mtime":1677847492540,"integrity":"ZUHcsxCWEH"}
```
--------------------------------
### Define a Basic WebSocket Handler
Source: https://nitro.build/docs/websocket
Create a WebSocket handler using `defineWebSocketHandler` and export it from a route file (e.g., `routes/_ws.ts`). This example shows basic `open`, `message`, `close`, and `error` event handling.
```typescript
import { defineWebSocketHandler } from "nitro";
export default defineWebSocketHandler({
open(peer) {
console.log("Connected:", peer.id);
},
message(peer, message) {
console.log("Message:", message.text());
peer.send("Hello from server!");
},
close(peer, details) {
console.log("Disconnected:", peer.id, details.code, details.reason);
},
error(peer, error) {
console.error("Error:", error);
},
});
```
--------------------------------
### Server Status API
Source: https://nitro.build/docs/openapi
Example of defining OpenAPI metadata for a route that returns the server status, including a detailed response schema.
```APIDOC
## GET /api/status
### Description
Returns the current server status, including uptime.
### Method
GET
### Endpoint
/api/status
### Responses
#### Success Response (200)
- Description: Server status
- Content:
- application/json:
- Schema:
- type: object
- properties:
- status: { type: string, enum: ["healthy", "degraded"] }
- uptime: { type: number }
### Response Example
{
"status": "healthy",
"uptime": 1234.56
}
```
--------------------------------
### Development Storage Override
Source: https://nitro.build/docs/storage
Demonstrates using `devStorage` to override production storage configuration during development, for example, using a local filesystem driver instead of Redis.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
storage: {
db: {
driver: "redis",
host: "prod.example.com",
}
},
devStorage: {
db: {
driver: "fs",
base: "./.data/db"
}
}
})
```
--------------------------------
### Connect to WebSocket from Client
Source: https://nitro.build/docs/websocket
Use the browser's native `WebSocket` API to establish a connection to your Nitro WebSocket endpoint. This example demonstrates opening the connection, sending a message, and handling incoming messages.
```javascript
const ws = new WebSocket("ws://localhost:3000/_ws");
ws.addEventListener("open", () => {
console.log("Connected!");
ws.send("Hello from client!");
});
ws.addEventListener("message", (event) => {
console.log("Received:", event.data);
});
```
--------------------------------
### List Users API with Global Schema
Source: https://nitro.build/docs/openapi
Example of defining OpenAPI metadata for a route that lists users, referencing a globally defined reusable schema for user objects.
```APIDOC
## GET /api/users
### Description
List all users. The response uses a globally defined schema for user objects.
### Method
GET
### Endpoint
/api/users
### Responses
#### Success Response (200)
- Description: List of users
- Content:
- application/json:
- Schema:
- type: array
- items: { $ref: "#/components/schemas/User" }
### Response Example
[
{
"id": "1",
"name": "Alice",
"email": "alice@example.com"
}
]
### Global Components
- **User** (Schema):
- type: object
- properties:
- id: { type: string }
- name: { type: string }
- email: { type: string, format: "email" }
```
--------------------------------
### Execute Echo Task with Query Parameters
Source: https://nitro.build/docs/tasks
Demonstrates executing the 'echo:payload' task using GET request with query parameters. The returned JSON reflects the parsed query parameters.
```json
// [GET] /_nitro/tasks/echo:payload?field=value&array=1&array=2
{
"field": "value",
"array": ["1", "2"]
}
```
--------------------------------
### Environment Variables for Nested Runtime Config
Source: https://nitro.build/docs/configuration
Example environment variables that override the nested `database` configuration. `NITRO_DATABASE_HOST` and `NITRO_DATABASE_PORT` are used to set the values.
```shell
NITRO_DATABASE_HOST="db.example.com"
NITRO_DATABASE_PORT="5433"
```
--------------------------------
### User by ID API
Source: https://nitro.build/docs/openapi
Example of defining OpenAPI metadata for a route that retrieves a user by ID, including path parameters and query parameters.
```APIDOC
## GET /api/users/[id]
### Description
Get a user by their ID. Supports including related resources via a query parameter.
### Method
GET
### Endpoint
/api/users/[id]
### Parameters
#### Path Parameters
- **id** (string) - Required - The ID of the user to retrieve.
#### Query Parameters
- **include** (string) - Optional - Comma-separated list of related resources to include.
### Responses
#### Success Response (200)
- Description: User found
#### Error Response (404)
- Description: User not found
### Response Example
{
"id": "1",
"name": "Alice"
}
```
--------------------------------
### Accessing Runtime Configuration
Source: https://nitro.build/docs/configuration
An example Nitro handler that retrieves and returns the `apiToken` from the runtime configuration. It uses `useRuntimeConfig()` to access the configuration value.
```typescript
import { defineHandler } from "nitro";
import { useRuntimeConfig } from "nitro/runtime-config";
export default defineHandler((event) => {
return useRuntimeConfig().apiToken; // Returns `dev_token`
});
```
--------------------------------
### SSR Outlet in index.html
Source: https://nitro.build/docs/renderer
An example of an index.html file that includes an '' comment. Nitro will replace this comment with the output from the SSR entry during rendering when using Vite environments with an SSR service.
```html
SSR App
```
--------------------------------
### Retrieve Custom Server Assets
Source: https://nitro.build/docs/assets
Access custom server assets configured in Nitro using the `useStorage` function with the `assets:` identifier. This example shows how to retrieve an HTML file.
```typescript
import { defineHandler } from "nitro";
export default defineHandler(async (event) => {
const html = await useStorage("assets:templates").get("success.html");
return html;
});
```
--------------------------------
### Define Response Schemas with Content Types
Source: https://nitro.build/docs/openapi
Specify response content types and schemas using the standard OpenAPI `responses` object. This example defines a JSON response with a status and uptime.
```typescript
import { defineRouteMeta, defineHandler } from "nitro";
defineRouteMeta({
openAPI: {
description: "Returns the current server status",
responses: {
200: {
description: "Server status",
content: {
"application/json": {
schema: {
type: "object",
properties: {
status: { type: "string", enum: ["healthy", "degraded"] },
uptime: { type: "number" },
},
},
},
},
},
},
},
});
export default defineHandler(() => {
return { status: "healthy", uptime: process.uptime() };
});
```
--------------------------------
### WebSocket Upgrade Hook for Authentication
Source: https://nitro.build/docs/websocket
Implement the `upgrade` hook in your WebSocket handler to perform authentication or attach context data before the connection is established. This example checks for a valid token in the URL query parameters.
```typescript
import { defineWebSocketHandler } from "nitro";
export default defineWebSocketHandler({
upgrade(request) {
const url = new URL(request.url);
const token = url.searchParams.get("token");
if (!isValidToken(token)) {
throw new Response("Unauthorized", { status: 401 });
}
return {
context: { userId: getUserId(token) },
};
},
open(peer) {
console.log("User connected:", peer.context.userId);
},
// ...
});
```
--------------------------------
### Vite Configuration for Nitro
Source: https://nitro.build/docs
Configure Vite to use Nitro as a plugin for building full-stack applications. This setup allows `vite build` to produce an optimized output folder containing both frontend and backend code.
```typescript
import {
defineConfig
} from "vite";
import {
nitro
} from "nitro/vite";
export default defineConfig({
plugins: [nitro()],
});
```
--------------------------------
### Basic Database Usage
Source: https://nitro.build/docs/database
Demonstrates creating a table, inserting data, and querying users using the database instance.
```typescript
import { defineHandler } from "nitro";
import { useDatabase } from "nitro/database";
export default defineHandler(async () => {
const db = useDatabase();
// Create users table
await db.sql`DROP TABLE IF EXISTS users`;
await db.sql`CREATE TABLE IF NOT EXISTS users ("id" TEXT PRIMARY KEY, "firstName" TEXT, "lastName" TEXT, "email" TEXT)`;
// Add a new user
const userId = String(Math.round(Math.random() * 10_000));
await db.sql`INSERT INTO users VALUES (${userId}, 'John', 'Doe', '')`;
// Query for users
const { rows } = await db.sql`SELECT * FROM users WHERE id = ${userId}`;
return {
rows,
};
});
```
--------------------------------
### Create a New Nitro Project with deno
Source: https://nitro.build/docs/quick-start
Use this command to quickly scaffold a new Nitro project using deno.
```bash
deno
run -A npm:create-nitro-app
```
--------------------------------
### GET Request Method Specific Route
Source: https://nitro.build/docs/routing
Defines a route that only responds to GET requests. The HTTP method is appended to the filename.
```typescript
// routes/users/[id].get.ts
import { defineHandler } from "nitro";
export default defineHandler(async (event) => {
const { id } = event.context.params;
// Do something with id
return `User profile!`;
});
```
--------------------------------
### Create a New Nitro Project with bun
Source: https://nitro.build/docs/quick-start
Use this command to quickly scaffold a new Nitro project using bun.
```bash
bunx
create-nitro-app
```
--------------------------------
### Create a New Nitro Project with npm
Source: https://nitro.build/docs/quick-start
Use this command to quickly scaffold a new Nitro project using npm.
```bash
npx
crate-nitro-app
```
--------------------------------
### Accessing Server Assets
Source: https://nitro.build/docs/storage
Shows how to access server assets mounted at the `/assets` base path using `useStorage`.
```javascript
import { useStorage } from "nitro/storage";
// Access server assets via the /assets mount
const content = await useStorage("assets/server").getItem("my-file.txt");
```
--------------------------------
### WebSocket Close Hook Example
Source: https://nitro.build/docs/websocket
The `close` hook is executed when a WebSocket connection is terminated. It receives details about the closure, such as the code and reason.
```javascript
close(peer, details) {
console.log(`Closed: ${details.code} - ${details.reason}`);
}
```
--------------------------------
### Configuring Custom Asset Directories
Source: https://nitro.build/docs/storage
Shows how to register additional asset directories using the 'serverAssets' configuration option in Nitro.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
serverAssets: [
{
baseName: "templates",
dir: "./templates",
}
]
})
```
--------------------------------
### Mounting Custom Storage Driver (Redis)
Source: https://nitro.build/docs/storage
Shows how to configure and mount a custom storage driver, such as Redis, using the `storage` option in `nitro.config.ts`.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
storage: {
redis: {
driver: "redis",
/* redis connector options */
}
}
})
```
--------------------------------
### Create a New Nitro Project with pnpm
Source: https://nitro.build/docs/quick-start
Use this command to quickly scaffold a new Nitro project using pnpm.
```bash
pnpm
dlx create-nitro-app
```
--------------------------------
### Project Structure for Server Assets
Source: https://nitro.build/docs/storage
Illustrates the directory structure for bundling server assets in a Nitro project.
```tree
my-project/
assets/
data.json
templates/
welcome.html
server/
routes/
index.ts
```
--------------------------------
### WebSocket Message Hook Examples
Source: https://nitro.build/docs/websocket
The `message` hook is triggered when a message is received from a peer. It provides access to the message content as text or JSON.
```javascript
message(peer, message) {
const text = message.text();
const data = message.json();
}
```
--------------------------------
### Define a Basic Nitro Plugin
Source: https://nitro.build/docs/plugins
Use `definePlugin` to create a plugin that logs the nitroApp context during startup. This is the fundamental way to extend Nitro's runtime.
```typescript
import { definePlugin } from "nitro";
export default definePlugin((nitroApp) => {
console.log('Nitro plugin', nitroApp)
})
```
--------------------------------
### Enable and Configure OpenAPI with Metadata
Source: https://nitro.build/docs/openapi
Enable the OpenAPI feature and set API metadata like title, description, and version in the Nitro configuration.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
experimental: {
openAPI: true,
},
openAPI: {
meta: {
title: "My API",
description: "My awesome API",
version: "2.0.0",
},
},
});
```
--------------------------------
### Create a New Nitro Project with yarn
Source: https://nitro.build/docs/quick-start
Use this command to quickly scaffold a new Nitro project using yarn.
```bash
yarn
dlx create-nitro-app
```
--------------------------------
### WebSocket Error Hook Example
Source: https://nitro.build/docs/websocket
The `error` hook is called when an error occurs during a WebSocket connection. It's essential for logging and handling connection issues.
```javascript
error(peer, error) {
console.error("WebSocket error:", error);
}
```
--------------------------------
### List Tasks via CLI
Source: https://nitro.build/docs/tasks
Command to list all available tasks when the Nitro dev server is running.
```bash
nitro task list
```
--------------------------------
### Custom cache storage for blog routes
Source: https://nitro.build/docs/cache
Use a custom cache storage, 'redis' in this case, for blog routes with a 1-hour cache duration.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
storage: {
redis: {
driver: "redis",
url: "redis://localhost:6379",
},
},
routeRules: {
"/blog/**": { cache: { maxAge: 60 * 60, base: "redis" } },
},
});
```
--------------------------------
### Setting a Cookie in Nitro
Source: https://nitro.build/docs/renderer
Sets a cookie named 'visited' with the value 'true' and an expiration time of 1 hour. This is an example of using built-in Nitro functions within a script tag.
```html
```
--------------------------------
### List Available Tasks
Source: https://nitro.build/docs/tasks
This endpoint returns a list of all available task names and their associated metadata, including descriptions and scheduled task configurations.
```APIDOC
## GET /_nitro/tasks
### Description
Retrieves a list of all available tasks and their metadata, including descriptions and scheduled task configurations.
### Method
GET
### Endpoint
/_nitro/tasks
### Response
#### Success Response (200)
- **tasks** (object) - An object where keys are task names and values are objects containing task metadata like 'description'.
- **scheduledTasks** (array) - An array of objects, each specifying a cron schedule and a list of tasks to run at that schedule.
```
--------------------------------
### Modify Response Headers Based on Path
Source: https://nitro.build/docs/plugins
Use the `response` hook to conditionally modify response headers. This example appends the `Vary` header for CSS and JS files to improve caching behavior.
```typescript
import { definePlugin } from "nitro";
export default definePlugin((nitroApp) => {
nitroApp.hooks.hook("response", (res, event) => {
const { pathname } = new URL(event.req.url);
if (pathname.endsWith(".css") || pathname.endsWith(".js")) {
res.headers.append("Vary", "Origin");
}
});
});
```
--------------------------------
### Configure Custom Server Assets
Source: https://nitro.build/docs/assets
Define custom server assets by specifying their base name and directory in the Nitro configuration file. This allows assets to be accessed via the `assets:` storage driver.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
serverAssets: [
{
baseName: "templates",
dir: "./templates",
},
],
});
```
--------------------------------
### Nested Runtime Configuration
Source: https://nitro.build/docs/configuration
Demonstrates defining nested runtime configuration for database settings. Keys are mapped to environment variables using `NITRO_` prefix and `UPPER_SNAKE_CASE`.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
runtimeConfig: {
database: {
host: "localhost",
port: 5432,
},
},
});
```
--------------------------------
### Enable OpenAPI in Production
Source: https://nitro.build/docs/openapi
Enable OpenAPI endpoints in production environments using 'runtime' for dynamic generation or 'prerender' for static file serving.
```typescript
export default defineConfig({
openAPI: {
production: "runtime",
},
});
```
--------------------------------
### Custom Renderer Handler Example
Source: https://nitro.build/docs/renderer
A custom renderer handler function that receives an H3 event object and returns an HTML response. It programmatically generates the HTML content, including the current URL pathname.
```typescript
export default function renderer({ req }: { req: Request }) {
const url = new URL(req.url);
return new Response(
/* html */ `
Custom Renderer
Hello from custom renderer!
Current path: ${url.pathname}
`,
{ headers: { "content-type": "text/html; charset=utf-8" } }
);
}
```
--------------------------------
### Full Cache Options
Source: https://nitro.build/docs/routing
Configure detailed cache options, including `maxAge` and `swr`, for specific routes.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
routeRules: {
// Full cache options
'/api/data/**': {
cache: {
maxAge: 60,
swr: true,
// ...other cache options
},
},
}
});
```
--------------------------------
### Prepare SQL Statements
Source: https://nitro.build/docs/database
Prepare SQL statements for repeated execution using `db.prepare`. This can improve performance for frequently run queries.
```typescript
const db = useDatabase();
const stmt = db.prepare("SELECT * FROM users WHERE id = ?");
const result = await stmt.bind("1001").all();
```
--------------------------------
### Accessing Server Assets in Routes
Source: https://nitro.build/docs/storage
Demonstrates how to access and retrieve files from the 'assets/server' storage mount within a Nitro route handler.
```typescript
import { useStorage } from "nitro/storage";
export default defineHandler(async () => {
const serverAssets = useStorage("assets/server");
const keys = await serverAssets.getKeys();
const data = await serverAssets.getItem("data.json");
const template = await serverAssets.getItem("templates/welcome.html");
return { keys, data, template };
});
```
--------------------------------
### Local Development Environment Variables
Source: https://nitro.build/docs/configuration
Define runtime configuration variables in a .env file for local development. Restart the development server after creating or modifying the file.
```env
NITRO_API_TOKEN="123"
```
--------------------------------
### Custom Server Entry with Format Option
Source: https://nitro.build/docs/server-entry
Configuring a custom server entry with explicit `handler` and `format` options in `nitro.config.ts`. The `format` can be set to 'node' for Node.js style handlers.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
serverEntry: {
handler: "./server.ts",
format: "node" // "web" (default) or "node"
}
})
```
--------------------------------
### HPP Server Script Execution
Source: https://nitro.build/docs/renderer
Shows how to execute JavaScript on the server within an HPP template using the
{{ JSON.stringify(data) }}
```
--------------------------------
### Basic Nitro Configuration
Source: https://nitro.build/docs/configuration
This is the most basic Nitro configuration file. It uses `defineConfig` from 'nitro'.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
// Nitro options
})
```
--------------------------------
### Default In-Memory Storage
Source: https://nitro.build/docs/storage
Illustrates the default in-memory storage behavior, where data is not persisted across restarts. For persistence, a custom driver must be mounted.
```javascript
import { useStorage } from "nitro/storage";
// In-memory by default, not persisted
await useStorage().setItem("counter", 1);
```
--------------------------------
### Middleware Execution Order
Source: https://nitro.build/docs/routing
Middleware in the 'middleware/' directory are executed in alphabetical order by default. Prefixing filenames with numbers controls the order.
```bash
middleware/
auth.ts <-- First
logger.ts <-- Second
... <-- Third
```
```bash
middleware/
1.logger.ts <-- First
2.auth.ts <-- Second
3.... <-- Third
```
--------------------------------
### Extending Configurations
Source: https://nitro.build/docs/configuration
Shows how to extend Nitro configurations from other files or presets using the `extends` key. This allows for modular configuration management.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
extends: "./base.config",
})
```
--------------------------------
### Accessing Custom Asset Directories
Source: https://nitro.build/docs/storage
Demonstrates how to access custom asset directories registered via the Nitro configuration.
```typescript
import { useStorage } from "nitro/storage";
const templates = useStorage("assets/templates");
const keys = await templates.getKeys();
const html = await templates.getItem("email.html");
```
--------------------------------
### HPP Output Expressions
Source: https://nitro.build/docs/renderer
Demonstrates HTML-escaped and raw output expressions using the Hypertext Preprocessor (HPP).
```html
Hello {{ $URL.pathname }}
{{{ 'raw html' }}}
```
--------------------------------
### Mark Routes for Prerendering
Source: https://nitro.build/docs/routing
Mark specific routes to be prerendered at build time.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
routeRules: {
'/about': { prerender: true },
}
});
```
--------------------------------
### Client-side EventSource Connection
Source: https://nitro.build/docs/websocket
Demonstrates how to connect to an SSE endpoint from the client-side using the `EventSource` API and log incoming messages to the console.
```javascript
const source = new EventSource("/sse");
source.onmessage = (event) => {
console.log(event.data);
};
```
--------------------------------
### Enable SWR shortcut for route rules
Source: https://nitro.build/docs/cache
Utilize the 'swr' shortcut to enable stale-while-revalidate caching. 'true' uses default maxAge, while a number specifies the maxAge in seconds.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
routeRules: {
"/blog/**": { swr: true },
"/api/**": { swr: 3600 },
},
});
```
--------------------------------
### Proxy with Options
Source: https://nitro.build/docs/routing
Configure proxy requests with additional H3 proxy options for more advanced control.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
routeRules: {
// Proxy with options
'/external/**': {
proxy: {
to: 'https://api.example.com/**',
// Additional H3 proxy options...
},
},
}
});
```
--------------------------------
### Configure Database Connections
Source: https://nitro.build/docs/database
Define multiple database connections, including their connectors and options, in the `nitro.config.ts` file. Supports SQLite and PostgreSQL.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
database: {
default: {
connector: "sqlite",
options: { name: "db" }
},
users: {
connector: "postgresql",
options: {
url: "postgresql://username:password@hostname:port/database_name"
},
},
},
});
```
--------------------------------
### Environment Specific Route Files
Source: https://nitro.build/docs/routing
Specify routes that are only included in specific builds by adding .dev, .prod, or .prerender suffixes to route files.
```nitro
routes/
env/
index.dev.ts <-- /env (dev only)
index.get.prod.ts <-- /env (GET, prod only)
```
--------------------------------
### HPP Streaming Content
Source: https://nitro.build/docs/renderer
Demonstrates streaming content in HPP templates using the echo() function with various data types.
```html
```
--------------------------------
### Peer Subscribe Method
Source: https://nitro.build/docs/websocket
Use `peer.subscribe()` to add a peer to a specific pub/sub topic, enabling targeted message broadcasting.
```javascript
peer.subscribe("notifications");
```
--------------------------------
### Environment-Specific Configuration
Source: https://nitro.build/docs/configuration
Demonstrates environment-specific overrides for Nitro configuration using `$development` and `$production` keys. Options within these keys are applied only in their respective environments.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
logLevel: 3,
$development: {
// Options applied only in development mode
debug: true,
},
$production: {
// Options applied only in production builds
minify: true,
},
})
```
--------------------------------
### Directory Options Configuration
Source: https://nitro.build/docs/configuration
Configures various directory options for Nitro, including `serverDir`, `buildDir`, and `output` directories. These control the project's structure and build artifacts.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
serverDir: "server",
buildDir: "node_modules/.nitro",
output: {
dir: ".output",
},
})
```
--------------------------------
### Runtime Route Rules with Headers
Source: https://nitro.build/docs/routing
Define route rules dynamically using `runtimeConfig` to allow overrides via environment variables without rebuilding.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
runtimeConfig: {
nitro: {
routeRules: {
'/api/**': { headers: { 'x-env': 'production' } },
},
},
},
});
```
--------------------------------
### Enable All Compressed Public Assets
Source: https://nitro.build/docs/assets
Nitro configuration to enable automatic compression for public assets using gzip, brotli, and zstd.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
compressPublicAssets: true,
});
```
--------------------------------
### Bun Package Manager Hoisting Configuration
Source: https://nitro.build/docs/nightly
When using Bun in a monorepo, configure publicHoistPattern in bunfig.toml to ensure the nitro package is properly hoisted.
```toml
[install]
publicHoistPattern = ["nitro*"]
```
--------------------------------
### Custom Server Entry File Configuration
Source: https://nitro.build/docs/server-entry
Configuring Nitro to use a custom server entry file named `nitro.server.ts` by specifying the `serverEntry` option in `nitro.config.ts`.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
serverEntry: "./nitro.server.ts"
})
```
--------------------------------
### Configure ISR (Vercel)
Source: https://nitro.build/docs/routing
Configure Incremental Static Regeneration (ISR) for Vercel deployments.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
routeRules: {
'/isr/**': { isr: true },
}
});
```
--------------------------------
### Route Meta Definition with OpenAPI
Source: https://nitro.build/docs/routing
Define route handler meta at build-time using defineRouteMeta, currently usable for specifying OpenAPI meta.
```typescript
import { defineRouteMeta } from "nitro";
import { defineHandler } from "nitro";
defineRouteMeta({
openAPI: {
tags: ["test"],
description: "Test route description",
parameters: [{ in: "query", name: "test", required: true }],
},
});
export default defineHandler(() => "OK");
```
--------------------------------
### Configure OpenAPI UI Integrations
Source: https://nitro.build/docs/openapi
Configure or disable built-in API documentation UIs such as Scalar and Swagger, including their routes and themes.
```typescript
export default defineConfig({
openAPI: {
ui: {
scalar: {
route: "/_docs/scalar",
theme: "purple",
},
swagger: {
route: "/_docs/swagger",
},
},
},
});
```
--------------------------------
### Basic Server Entry with Fetch Handler
Source: https://nitro.build/docs/server-entry
A default `server.ts` file that handles a health check route and can be extended to add custom headers or modify requests before they proceed to route matching.
```typescript
export default {
async fetch(req: Request) {
const url = new URL(req.url);
// Handle specific routes
if (url.pathname === "/health") {
return new Response("OK", {
status: 200,
headers: { "content-type": "text/plain" }
});
}
// Add custom headers to all requests
// Return nothing to continue to the next handler
}
}
```
--------------------------------
### Environment Variable Expansion in Runtime Config
Source: https://nitro.build/docs/configuration
Enable experimental environment variable expansion to allow `{{VAR_NAME}}` syntax in runtime config string values. These variables are expanded at runtime.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
experimental: {
envExpansion: true,
},
runtimeConfig: {
url: "https://{{APP_DOMAIN}}/api",
},
});
```
```env
APP_DOMAIN="example.com"
```
--------------------------------
### Migrate Headers Handling
Source: https://nitro.build/docs/migration
Switch from h3 header utilities to standard Web `Headers` API for accessing and setting request and response headers. Header values are always strings.
```typescript
-- import { getHeader, setHeader, getResponseStatus } from "nitro/h3"
-- getHeader(event, "x-foo")
-- setHeader(event, "x-foo", "bar")
++ event.req.headers.get("x-foo")
++ event.res.headers.set("x-foo", "bar")
++ event.res.status // instead of getResponseStatus(event)
```
--------------------------------
### Public Assets Directory Structure
Source: https://nitro.build/docs/assets
Illustrates how files in the public directory are served directly by Nitro.
```text
public/
image.png <-- /image.png
video.mp4 <-- /video.mp4
robots.txt <-- /robots.txt
```
--------------------------------
### Enable Database Feature
Source: https://nitro.build/docs/database
Enable the experimental database feature in Nitro's configuration.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
experimental: {
database: true
}
})
```
--------------------------------
### Simple Redirect
Source: https://nitro.build/docs/routing
Use a string for a simple redirect, which defaults to a 307 status code.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
routeRules: {
// Simple redirect (307 status)
'/old-page': { redirect: '/new-page' },
}
});
```
--------------------------------
### Configure Nitro Server Directory
Source: https://nitro.build/docs/quick-start
Specify the server directory for Nitro routes by creating a nitro.config.ts file with the serverDir option.
```typescript
import {
defineConfig
} from "nitro";
export default defineConfig({
serverDir: "./server",
});
```
--------------------------------
### Cache all blog routes for 1 hour with stale-while-revalidate
Source: https://nitro.build/docs/cache
Configure route rules to cache all routes under '/blog/**' for 1 hour using stale-while-revalidate behavior.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
routeRules: {
"/blog/**": { cache: { maxAge: 60 * 60 } },
},
});
```