### Add Start Script to package.json
Source: https://nitro.build/llms-full.txt
Add a `start` script to your `package.json` to define the command DigitalOcean will run after a build. This example uses `npm run start` which executes `node .output/server/index.mjs`.
```json
{
"scripts": {
"start": "node .output/server/index.mjs"
}
}
```
--------------------------------
### Basic API Route Example
Source: https://nitro.build/llms-full.txt
Defines a simple GET API endpoint at /api/hello. Ensure the file is placed in the api/ directory.
```typescript
import { defineHandler } from "nitro";
export default defineHandler(() => "Nitro is amazing!");
```
--------------------------------
### Nitro Storage API Examples
Source: https://nitro.build/docs/storage
Demonstrates common storage operations like getting keys, checking item existence, removing items, retrieving raw data, and getting 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");
```
--------------------------------
### HTML Structure for API Routes Example
Source: https://nitro.build/llms-full.txt
An example HTML file demonstrating links to various API routes, including basic and dynamic paths.
```html
```
--------------------------------
### Local Preview with Azure CLI
Source: https://nitro.build/deploy/providers/azure
Use this command to start a local development environment for previewing your Nitro app before deploying to Azure Static Web Apps. Ensure Azure Functions Core Tools are installed.
```bash
NITRO_PRESET=azure npx nypm@latest build
npx @azure/static-web-apps-cli start .output/public --api-location .output/server
```
--------------------------------
### Basic Database Operations Example
Source: https://nitro.build/docs/database
This example demonstrates creating a table, inserting a user, and querying for users using the `db.sql` tagged template literal. It requires the database feature to be enabled.
```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,
};
});
```
--------------------------------
### Project Dependencies
Source: https://nitro.build/llms-full.txt
Install necessary development dependencies for building and running the project with Preact, Tailwind CSS, and Nitro.
```json
{
"type": "module",
"scripts": {
"build": "vite build",
"preview": "vite preview",
"dev": "vite dev"
},
"devDependencies": {
"@preact/preset-vite": "^2.10.5",
"@tailwindcss/vite": "^4.2.2",
"nitro": "latest",
"preact": "^10.29.0",
"preact-render-to-string": "^6.6.7",
"tailwindcss": "^4.2.2",
"vite": "latest"
}
}
```
--------------------------------
### Vercel Deployment Configuration
Source: https://nitro.build/deploy/providers/vercel
Example configuration for Vercel deployment, specifying the output directory and public directory.
```javascript
export default defineNitroConfig({
vercel: {
// Vercel output directory
// Default: .vercel/output
dir: ".vercel/output",
// Vercel public directory
// Default: public
publicDir: "public"
}
})
```
--------------------------------
### CI Build and Deploy Example
Source: https://nitro.build/deploy/providers/zephyr
An example GitHub Actions workflow that builds and deploys a Nitro app to Zephyr Cloud. It uses `npm run build` and sets the `ZE_SECRET_TOKEN` environment variable for authentication.
```yaml
name: Deploy with Zephyr
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
env:
ZE_SECRET_TOKEN: ${{ secrets.ZEPHYR_AUTH_TOKEN }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- run: npm run build
```
--------------------------------
### Koyeb Control Panel Run Command
Source: https://nitro.build/llms-full.txt
Specify this run command in the Koyeb control panel if your package.json does not have a 'start' command.
```bash
node .output/server/index.mjs
```
--------------------------------
### Heroku: package.json Scripts for Build and Start
Source: https://nitro.build/llms-full.txt
Defines the 'build' and 'start' scripts required in package.json for Heroku deployment. The 'build' script runs the Nitro build process, and 'start' runs the server.
```json5
"scripts": {
"build": "nitro build", // or `nuxt build` if using nuxt
"start": "node .output/server/index.mjs"
}
```
--------------------------------
### Node.js Runtime with Serverless Function Support
Source: https://nitro.build/deploy/runtimes/node
Example of configuring a Node.js runtime for serverless environments. This setup is optimized for deployment on platforms like AWS Lambda or Vercel.
```javascript
export default defineNitroPreset({
preset: "node-serverless",
node: {
version: "18.0.0"
}
})
```
--------------------------------
### Heroku Nginx Preset: Procfile
Source: https://nitro.build/llms-full.txt
Procfile content to instruct Heroku to start Nginx and use the custom app runner to start the Node.js server.
```text
web: bin/start-nginx node apprunner.mjs
```
--------------------------------
### Accessing Server Assets
Source: https://nitro.build/docs/storage
Example of accessing server-side assets mounted under the '/assets' 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");
```
--------------------------------
### Elysia Server Entry Point
Source: https://nitro.build/llms-full.txt
Example of an Elysia server entry point. Call `app.compile()` before exporting for production optimization.
```typescript
import { Elysia } from "elysia";
const app = new Elysia();
app.get("/", () => "Hello, Elysia with Nitro!");
export default app.compile();
```
--------------------------------
### Deploy Project with Genezio CLI
Source: https://nitro.build/llms-full.txt
Use the `genezio deploy` command to deploy your project after building. Ensure the Genezio CLI is installed and configured.
```bash
genezio deploy
```
--------------------------------
### Custom HTML Template Example
Source: https://nitro.build/docs/renderer
An example of a custom HTML template file that can be used with the Nitro renderer. This template includes basic HTML structure and a script tag for application initialization.
```html
Custom Template
Loading...
```
--------------------------------
### Main Handler Example
Source: https://nitro.build/llms-full.txt
A simple Nitro handler that returns an HTML string.
```typescript
import { defineHandler } from "nitro";
export default defineHandler(() => "
Hello Nitro!
");
```
--------------------------------
### Basic KV Storage Usage
Source: https://nitro.build/llms-full.txt
Demonstrates setting and getting items from the default in-memory storage and a prefixed storage instance.
```typescript
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");
```
--------------------------------
### Static Route Example
Source: https://nitro.build/llms-full.txt
Defines a static API endpoint. The filename directly corresponds to the route path.
```APIDOC
## Static Route
### Description
Defines a static API endpoint. The filename directly corresponds to the route path.
### File Structure
```text
routes/
api/
test.ts
```
### Example Handler
```ts [routes/api/test.ts]
import { defineHandler } from "nitro";
export default defineHandler(() => {
return { hello: "API" };
});
```
### Route Mapping
`/api/test`
```
--------------------------------
### Create a Nitro Project
Source: https://nitro.build/docs/quick-start
Use the create-nitro-app command to quickly scaffold a new Nitro project. Ensure you have Node.js, Bun, or Deno installed.
```bash
npx create-nitro-app
```
```bash
yarn dlx create-nitro-app
```
```bash
pnpm dlx create-nitro-app
```
```bash
bunx create-nitro-app
```
```bash
deno run -A npm:create-nitro-app
```
--------------------------------
### Bundle Server Assets
Source: https://nitro.build/llms-full.txt
Configure server assets to be accessed in server logic and bundled in production. This example bundles the templates/ directory.
```typescript
export default defineConfig({
serverAssets: [
{
baseName: "templates",
dir: "./templates", // bundle templates/ as server assets
},
],
});
```
--------------------------------
### Install Nitro and Vite
Source: https://nitro.build/docs/quick-start
Add Nitro and Vite as dependencies to your existing project. This is the first step to integrating Nitro into a Vite project.
```bash
npm i nitro vite
```
```bash
yarn add nitro vite
```
```bash
pnpm i nitro vite
```
```bash
bun i nitro vite
```
```bash
deno i npm:nitro vite
```
--------------------------------
### Start Development Server
Source: https://nitro.build/docs/quick-start
Run the development server command to make your API routes accessible. The `--open` flag automatically opens the application in your browser.
```bash
npm run dev -- --open
```
```bash
yarn dev -- --open
```
```bash
pnpm dev -- --open
```
```bash
bun run dev -- --open
```
```bash
deno run dev -- --open
```
--------------------------------
### Configure Custom Storage Driver (Redis)
Source: https://nitro.build/docs/storage
Example of configuring a custom storage driver, specifically Redis, in the Nitro configuration file.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
storage: {
redis: {
driver: "redis",
/* redis connector options */
}
}
})
```
--------------------------------
### Client Entry Point
Source: https://nitro.build/examples/vite-ssr-vue-router
Set up the client entry point to mount the Vue application and initialize the router.
```javascript
import { createRouterConfig } from './router';
import App from './App.vue';
const router = createRouterConfig();
const app = createApp(App);
app.use(router);
router.isReady().then(() => {
app.mount('#app');
});
```
--------------------------------
### Execute Task via GET API
Source: https://nitro.build/docs/tasks
Example of executing the 'echo:payload' task using a GET request to `/_nitro/tasks/echo:payload`. Query parameters are directly used as the payload.
```json
// [GET] /_nitro/tasks/echo:payload?field=value&array=1&array=2
{
"field": "value",
"array": ["1", "2"]
}
```
--------------------------------
### Build and Deploy with deployctl CLI
Source: https://nitro.build/llms-full.txt
Builds the application using the deno_deploy preset and deploys it to Deno Deploy using the deployctl command. Ensure the DENO_DEPLOY_TOKEN environment variable is set.
```bash
# Build with the deno_deploy NITRO preset
NITRO_PRESET=deno_deploy npm run build
# Make sure to run the deployctl command from the output directory
cd .output
deployctl deploy --project=my-project server/index.ts
```
--------------------------------
### Firebase Deployment Configuration
Source: https://nitro.build/deploy/providers/firebase
Example nitro.config.ts file for Firebase deployment. Ensure you have the Firebase CLI installed and configured.
```typescript
import { defineNitroPreset } from 'nitropack'
export default defineNitroPreset({
preset: 'firebase',
// Optional: Specify a Firebase project ID
// firebase: {
// projectId: 'your-project-id'
// },
// Optional: Specify functions name
// firebase: {
// functionsName: 'nitro-app'
// },
// Optional: Specify functions region
// firebase: {
// region: 'us-central1'
// },
// Optional: Specify functions memory
// firebase: {
// memory: '256MB'
// },
// Optional: Specify functions runtime
// firebase: {
// runtime: 'nodejs18'
// },
// Optional: Specify functions entrypoint
// firebase: {
// entrypoint: 'nitro'
// },
// Optional: Specify functions timeout
// firebase: {
// timeoutSeconds: 60
// },
// Optional: Specify functions max instances
// firebase: {
// maxInstances: 10
// },
// Optional: Specify functions secrets
// firebase: {
// secrets: ['MY_SECRET']
// },
// Optional: Specify functions environment variables
// firebase: {
// env: {
// MY_VAR: 'my-value'
// }
// },
// Optional: Specify functions trigger
// firebase: {
// trigger: 'http'
// },
// Optional: Specify functions trigger options
// firebase: {
// triggerOptions: {
// invoker: ['project-owners']
// }
// },
// Optional: Specify functions ingress settings
// firebase: {
// ingressSettings: 'ALLOW_INTERNAL_ONLY'
// },
// Optional: Specify functions egress settings
// firebase: {
// egressSettings: 'ALLOW_ALL'
// },
// Optional: Specify functions vpc connector
// firebase: {
// vpcConnector: 'projects/your-project-id/locations/us-central1/connectors/your-connector'
// },
// Optional: Specify functions vpc connector Egress settings
// firebase: {
// vpcConnectorEgressSettings: 'PRIVATE_RANGES_ONLY'
// },
// Optional: Specify functions service account
// firebase: {
// serviceAccount: 'your-service-account@your-project-id.iam.gserviceaccount.com'
// },
// Optional: Specify functions ingress settings
// firebase: {
// ingressSettings: 'ALLOW_INTERNAL_ONLY'
// },
// Optional: Specify functions egress settings
// firebase: {
// egressSettings: 'ALLOW_ALL'
// },
// Optional: Specify functions vpc connector
// firebase: {
// vpcConnector: 'projects/your-project-id/locations/us-central1/connectors/your-connector'
// },
// Optional: Specify functions vpc connector Egress settings
// firebase: {
// vpcConnectorEgressSettings: 'PRIVATE_RANGES_ONLY'
// },
// Optional: Specify functions service account
// firebase: {
// serviceAccount: 'your-service-account@your-project-id.iam.gserviceaccount.com'
// },
// Optional: Specify functions ingress settings
// firebase: {
// ingressSettings: 'ALLOW_INTERNAL_ONLY'
// },
// Optional: Specify functions egress settings
// firebase: {
// egressSettings: 'ALLOW_ALL'
// },
// Optional: Specify functions vpc connector
// firebase: {
// vpcConnector: 'projects/your-project-id/locations/us-central1/connectors/your-connector'
// },
// Optional: Specify functions vpc connector Egress settings
// firebase: {
// vpcConnectorEgressSettings: 'PRIVATE_RANGES_ONLY'
// },
// Optional: Specify functions service account
// firebase: {
// serviceAccount: 'your-service-account@your-project-id.iam.gserviceaccount.com'
// }
})
```
--------------------------------
### Fastify Framework Integration with Nitro
Source: https://nitro.build/llms-full.txt
Integrating the Fastify framework as a Nitro server entry using `server.node.ts`. This example sets up a simple GET route.
```typescript
import Fastify from "fastify";
const app = Fastify();
app.get("/", () => "Hello, Fastify with Nitro!");
await app.ready();
export default app.routing;
```
--------------------------------
### Elysia Framework Integration as Server Entry
Source: https://nitro.build/docs/server-entry
Integrates the Elysia framework as a Nitro server entry. This example sets up a basic GET route for the root path.
```typescript
import { Elysia } from "elysia";
const app = new Elysia();
app.get("/", () => "🦊 Hello from Elysia!");
export default app.compile();
```
--------------------------------
### Hono Framework Integration as Server Entry
Source: https://nitro.build/docs/server-entry
Integrates the Hono framework as a Nitro server entry. This example sets up a basic GET route for the root path.
```typescript
import { Hono } from "hono";
const app = new Hono();
app.get("/", (c) => c.text("🔥 Hello from Hono!"));
export default app;
```
--------------------------------
### H3 Framework Integration as Server Entry
Source: https://nitro.build/docs/server-entry
Integrates the H3 framework as a Nitro server entry. This example sets up a basic GET route for the root path.
```typescript
import { H3 } from "h3";
const app = new H3()
app.get("/", () => "⚡️ Hello from H3!");
export default app;
```
--------------------------------
### Run Node.js Server
Source: https://nitro.build/llms-full.txt
Launches the built Node.js server. Ensure the output directory is correctly specified.
```bash
$ node .output/server/index.mjs
Listening on http://localhost:3000
```
--------------------------------
### Build and Run Node.js Server
Source: https://nitro.build/deploy/runtimes/node
Build your Nitro project using the 'nitro build' command with the Node.js server preset. Then, run the generated server entry point.
```bash
nitro build
node .output/server/index.mjs
```
--------------------------------
### Amplify.yml for Monorepo Build
Source: https://nitro.build/deploy/providers/aws-amplify
A sample `amplify.yml` file for a monorepo setup. It specifies build commands, including Node.js version selection and package installation, and defines artifact locations.
```yaml
version: 1
frontend:
phases:
preBuild:
commands:
- nvm use 24 && node --version
- corepack enable && npx --yes nypm install
build:
commands:
- pnpm build
artifacts:
baseDirectory: .amplify-hosting
files:
- "**/*"
```
--------------------------------
### Nuxt Configuration Example
Source: https://nitro.build/docs/configuration
This snippet shows a partial Nuxt configuration object, including settings for Plausible analytics, MDC components, and code highlighting.
```javascript
window.__NUXT__={};window.__NUXT__.config={public:{plausible:{enabled:true,hashMode:false,domain:"",ignoredHostnames:["localhost"],ignoreSubDomains:false,apiHost:"https://plausible.io",autoPageviews:true,autoOutboundTracking:false,fileDownloads:false,formSubmissions:false,logIgnoredEvents:false,proxy:false,proxyBaseEndpoint:"/_plausible"},mdc:{components:{prose:true,map:{accordion:"ProseAccordion","accordion-item":"ProseAccordionItem",badge:"ProseBadge",callout:"ProseCallout",card:"ProseCard","card-group":"ProseCardGroup",caution:"ProseCaution","code-collapse":"ProseCodeCollapse","code-group":"ProseCodeGroup","code-icon":"ProseCodeIcon","code-preview":"ProseCodePreview","code-tree":"ProseCodeTree",collapsible:"ProseCollapsible",field:"ProseField","field-group":"ProseFieldGroup",icon:"ProseIcon",kbd:"ProseKbd",note:"ProseNote",steps:"ProseSteps",tabs:"ProseTabs","tabs-item":"ProseTabsItem",tip:"ProseTip",warning:"ProseWarning"},customElements:[]},headings:{anchorLinks:{h1:false,h2:true,h3:true,h4:true,h5:false,h6:false}},highlight:{noApiRoute:true,theme:{light:"github-light",default:"github-dark",dark:"github-dark"},langs:["json","json5","jsonc","toml","yaml","html","sh","shell","bash","mdc","markdown","md","vue","js","ts","javascript","typescript","ini","diff","jsx","tsx","json","json5","jsonc","toml","yaml","html","sh","shell","bash","mdc","markdown","md","vue","js","ts","javascript","typescript","ini","diff","jsx","tsx"],highlighter:"shiki",shikiEngine:"oniguruma"}},content:{wsUrl:""}},app:{baseURL:"/",buildId:"c33655ee-fcdf-48ba-aa6c-f63bf779d707",buildAssetsDir:"/_nuxt/",cdnURL:""}}}
```
--------------------------------
### Example flightcontrol.json Configuration
Source: https://nitro.build/llms-full.txt
This JSON configuration defines a production environment for a Nitro application using Flightcontrol. It specifies deployment details for an AWS Fargate service, including build type, domain, output directory, start command, CPU, and memory.
```json
{
"$schema": "https://app.flightcontrol.dev/schema.json",
"environments": [
{
"id": "production",
"name": "Production",
"region": "us-west-2",
"source": {
"branch": "main"
},
"services": [
{
"id": "nitro",
"buildType": "nixpacks",
"name": "My Nitro site",
"type": "fargate",
"domain": "www.yourdomain.com",
"outputDirectory": ".output",
"startCommand": "node .output/server/index.mjs",
"cpu": 0.25,
"memory": 0.5
}
]
}
]
}
```
--------------------------------
### Generated Cache Key Example
Source: https://nitro.build/llms-full.txt
Shows the resulting cache key for the example getAccessToken function.
```typescript
cache:nitro/functions:getAccessToken:default.json
```
--------------------------------
### Build and Run Nitro Server for Deno Runtime
Source: https://nitro.build/llms-full.txt
Build your Nitro project with the 'deno_server' preset and run the production server using the Deno runtime.
```bash
# Build with the deno NITRO preset
NITRO_PRESET=deno_server npm run build
```
```bash
# Start production server
deno run --unstable --allow-net --allow-read --allow-env .output/server/index.ts
```
--------------------------------
### 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!`;
});
```
--------------------------------
### GET HTTP Method Handler
Source: https://nitro.build/llms-full.txt
Defines a specific handler for GET requests to an API endpoint. This is the default if no method suffix is used.
```typescript
import { defineHandler } from "nitro";
export default defineHandler(() => "Test get handler");
```
--------------------------------
### Client Entry Point (main.client.js)
Source: https://nitro.build/examples/vite-ssr-vue-router
The client-side entry point for the Vue application. It initializes the Vue app and mounts it to the DOM.
```javascript
import { createApp } from "vue";
import App from "./App.vue";
import { createRouter, createWebHistory } from "vue-router";
// Import routes
import routes from "./routes";
// Create router instance
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes,
});
// Create Vue app instance
const app = createApp(App);
// Use router
app.use(router);
// Mount app
app.mount("#app");
```
--------------------------------
### Server Entry Point
Source: https://nitro.build/examples/vite-ssr-vue-router
Create a server entry point for SSR that renders the Vue application and resolves the initial route.
```javascript
import { renderToString } from 'vue/server-render';
import { createRouterConfig } from './router';
import App from './App.vue';
export async function render(url) {
const router = createRouterConfig();
router.push(url);
await router.isReady();
const app = createSSRApp(App);
app.use(router);
const html = await renderToString(app);
return html;
}
```
--------------------------------
### Custom API Handler Example
Source: https://nitro.build/docs/renderer
An example of a custom handler function that can be used with the Nitro renderer. This handler processes incoming requests and returns a JSON response.
```typescript
import { defineHandler } from "nitro";
export default defineHandler((event) => {
return { hello: "API" };
});
```
--------------------------------
### Specify Preview and Deploy Commands
Source: https://nitro.build/config
The `commands` option provides hints for preview and deploy commands, which are often populated by deployment presets. You can manually specify commands, such as a custom preview command.
```javascript
export default defineConfig({
commands: {
preview: "node ./server/index.mjs",
},
});
```
--------------------------------
### Define a GET Request Handler
Source: https://nitro.build/llms-full.txt
Specify the HTTP method by appending `.get.ts` to the filename to create a route that only responds to GET requests. Access route parameters from `event.context.params`.
```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!`;
});
```
--------------------------------
### Vite SSR Entry Point
Source: https://nitro.build/examples/vite-ssr-vue-router
This is the main entry point for the Vite SSR build. It sets up the Vue app and renders it to a string.
```javascript
import { createSSRApp } from 'vue'
import App from './App.vue'
import { createRouter } from './router'
export function render({
url,
state
}) {
const app = createSSRApp(App)
const router = createRouter()
app.use(router)
router.push(url)
// wait until router is ready
return new Promise((resolve, reject) => {
router.isReady().then(() => {
try {
const ctx = { url, state }
const html = app.render(ctx)
resolve({ html, state: ctx.state })
} catch (e) {
reject(e)
}
})
})
}
```
--------------------------------
### Create a Page Route with TanStack Start
Source: https://nitro.build/llms-full.txt
Defines the root page route for a TanStack Start application. This snippet shows how to import `createFileRoute` and define a component for the home page.
```tsx
import { createFileRoute } from "@tanstack/react-router";
export const Route = createFileRoute("/")({
component: Home,
});
function Home() {
return (
);
}
```
--------------------------------
### Run Nitro Server with Bun Preset
Source: https://nitro.build/llms-full.txt
Build your Nitro project with the 'bun' preset and run the production server using the Bun runtime.
```bash
bun run ./.output/server/index.mjs
```
--------------------------------
### Shiki Highlighter Setup and API Route
Source: https://nitro.build/llms-full.txt
This snippet shows how to create a Shiki highlighter instance with specific themes and languages. The API route then uses this highlighter to convert raw code into HTML, suitable for display.
```typescript
import { createHighlighterCore } from "shiki/core";
import { createOnigurumaEngine } from "shiki/engine/oniguruma";
const highlighter = await createHighlighterCore({
engine: createOnigurumaEngine(import("shiki/wasm")),
themes: [await import("shiki/themes/vitesse-dark.mjs")],
langs: [await import("shiki/langs/ts.mjs")],
});
export default async ({ req }: { req: Request }) => {
const code = await req.text();
const html = await highlighter.codeToHtml(code, {
lang: "ts",
theme: "vitesse-dark",
});
return new Response(html, {
headers: { "Content-Type": "text/html; charset=utf-8" },
});
};
```
--------------------------------
### Configure Project Root Directory
Source: https://nitro.build/config
Sets the project's main directory.
```javascript
export default defineConfig({
rootDir: "./src/server",
});
```
--------------------------------
### Package.json Configuration for Module Aliases
Source: https://nitro.build/llms-full.txt
Sets up module aliases for server files using the 'imports' field in package.json.
```json
{
"type": "module",
"imports": {
"#server/*": "./server/*"
},
"scripts": {
"build": "nitro build",
"dev": "nitro dev",
"preview": "node .output/server/index.mjs"
},
"devDependencies": {
"nitro": "latest"
}
}
```
--------------------------------
### Example of defineCachedFunction Usage
Source: https://nitro.build/llms-full.txt
Demonstrates how to define a cached function with custom options.
```typescript
import { defineCachedFunction } from "nitro/cache";
const getAccessToken = defineCachedFunction(() => {
return String(Date.now())
}, {
maxAge: 10,
name: "getAccessToken",
getKey: () => "default"
});
```
--------------------------------
### Get Storage Value
Source: https://nitro.build/docs/configuration
Retrieves a value from local storage. If no value is found, it defaults to 'dark'.
```javascript
const t = window,
e = document.documentElement,
c = ["dark", "light"],
n = getStorageValue("localStorage", "nuxt-color-mode") || "dark";
let i = n === "system" ? u() : n;
```
--------------------------------
### Server Entry Point for SSR
Source: https://nitro.build/llms-full.txt
Handles incoming requests, renders the React app to a readable stream, and includes necessary assets. Sets up the HTML structure and links CSS/JS.
```tsx
import "./styles.css";
import { renderToReadableStream } from "react-dom/server.edge";
import { App } from "./app.tsx";
import clientAssets from "./entry-client?assets=client";
import serverAssets from "./entry-server?assets=ssr";
export default {
async fetch(_req: Request) {
const assets = clientAssets.merge(serverAssets);
return new Response(
await renderToReadableStream(
{assets.css.map((attr: any) => (
))}
{assets.js.map((attr: any) => (
))}
),
{ headers: { "Content-Type": "text/html;charset=utf-8" } }
);
},
};
```
--------------------------------
### Node.js Runtime with Custom Build Options
Source: https://nitro.build/deploy/runtimes/node
Shows how to provide custom build options for the Node.js runtime. This can include flags or configurations for the build process.
```javascript
export default defineNitroPreset({
preset: "node",
node: {
buildOptions: {
// Example: specify a custom entry point
entry: "server.js"
}
}
})
```
--------------------------------
### Server Entry Point
Source: https://nitro.build/llms-full.txt
Configures the server entry point for SSR using `@tanstack/react-start/server-entry`.
```typescript
import handler, { createServerEntry } from "@tanstack/react-start/server-entry";
export default createServerEntry({
fetch(request) {
return handler.fetch(request);
},
});
```
--------------------------------
### Home Route Component
Source: https://nitro.build/llms-full.txt
Defines the component for the home route ('/'). Includes a link to an example API route.
```tsx
import { createFileRoute } from "@tanstack/react-router";
export const Route = createFileRoute("/")({
component: Home,
});
function Home() {
return (
);
}
```
--------------------------------
### Server Entry Point for Streaming Response
Source: https://nitro.build/llms-full.txt
Defines the server's entry point to fetch data and stream it as a tokenized response. This example fetches a quote and streams it word by word with a delay.
```typescript
import {
fetch
} from "nitro";
export default {
async fetch() {
const quote = (await fetch("/quote").then((res) => res.json())) as {
text: string;
};
return tokenizedStream(quote.text, 50);
},
};
function tokenizedStream(text: string, delay: number): ReadableStream {
const tokens = text.split(" ");
return new ReadableStream({
start(controller) {
let index = 0;
function push() {
if (index < tokens.length) {
const word = tokens[index++] + (index < tokens.length ? " " : "");
controller.enqueue(new TextEncoder().encode(word));
setTimeout(push, delay);
} else {
controller.close();
}
}
push();
},
});
}
```
--------------------------------
### Initialize Color Mode Management
Source: https://nitro.build/deploy
Sets up the color mode management system for the application. It defaults to 'dark' and respects system preferences or local storage.
```javascript
"use strict";
(()=>{const t=window,e=document.documentElement,c=["dark","light"],n=getStorageValue("localStorage","nuxt-color-mode")||"dark";let i=n==="system"?u():n;const r=e.getAttribute("data-color-mode-forced");r&&(i=r),l(i),t["__NUXT_COLOR_MODE__"]={preference:n,value:i,getColorScheme:u,addColorScheme:l,removeColorScheme:d};function l(o){const s=""+o+"",a="";e.classList?e.classList.add(s):e.className+=" "+s,a&&e.setAttribute("data-"+a,o)}function d(o){const s=""+o+"",a="";e.classList?e.classList.remove(s):e.className=e.className.replace(new RegExp(s,"g"),""),a&&e.removeAttribute("data-"+a)}function f(o){return t.matchMedia("(prefers-color-scheme"+o+")")}function u(){if(t.matchMedia&&f("").media!=="not all"){for(const o of c)if(f(":"+o).matches)return o}return"dark"}})();function getStorageValue(t,e){switch(t){case"localStorage":return
```
--------------------------------
### Vite SVG Asset
Source: https://nitro.build/llms-full.txt
Example of an SVG asset used with Vite. This snippet shows the raw SVG code.
```text
```
--------------------------------
### Nitro Configuration for Custom Renderer
Source: https://nitro.build/docs/renderer
Example of configuring a custom renderer handler in Nitro's configuration file.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
renderer: {
handler: './renderer.ts'
}
})
```
--------------------------------
### Azure Functions Deployment
Source: https://nitro.build/deploy/providers/azure
Example of configuring Nitro to deploy as Azure Functions. This is useful for serverless deployments on Azure.
```javascript
import { defineNitroPreset } from 'nitropack/kit'
export default defineNitroPreset({
// ...
azure: {
// ...
functions: {
// ...
}
}
})
```
--------------------------------
### SolidJS Server Entry with SSR and Hydration
Source: https://nitro.build/llms-full.txt
This snippet demonstrates how to create a server entry point for a SolidJS application. It uses `renderToStringAsync` for server-side rendering and `HydrationScript` for client-side hydration. Assets are managed using query parameters.
```tsx
import { renderToStringAsync, HydrationScript } from "solid-js/web";
import { App } from "./app.jsx";
import clientAssets from "./entry-client?assets=client";
import serverAssets from "./entry-server?assets=ssr";
export default {
async fetch(req: Request): Promise {
const appHTML = await renderToStringAsync(() => );
const rootHTML = await renderToStringAsync(() => );
return new Response(rootHTML, {
headers: { "Content-Type": "text/html" },
});
},
};
function Root(props: { appHTML?: string }) {
const assets = clientAssets.merge(serverAssets);
return (
{assets.css.map((attr: any) => (
))}
{assets.js.map((attr: any) => (
))}
);
}
```
--------------------------------
### Server Action for Counter
Source: https://nitro.build/llms-full.txt
Defines server-side functions to get and update a counter. These actions are intended for server-only operations.
```typescript
"use server";
let serverCounter = 0;
export async function getServerCounter() {
return serverCounter;
}
export async function updateServerCounter(change: number) {
serverCounter += change;
}
```
--------------------------------
### Configure Development Server Options
Source: https://nitro.build/config
Customize the dev server using `devServer` options like `port`, `hostname`, and `watch`. Use `watch` to trigger reloads on file changes.
```javascript
export default defineConfig({
devServer: {
port: 3001,
watch: ["./server/plugins"],
},
});
```
--------------------------------
### Package JSON for nano-jsx Integration
Source: https://nitro.build/llms-full.txt
Defines project scripts and dependencies for Nitro with nano-jsx. Installs 'nano-jsx' and 'nitro'.
```json
{
"type": "module",
"scripts": {
"dev": "nitro dev",
"build": "nitro build"
},
"devDependencies": {
"nano-jsx": "^0.2.1",
"nitro": "latest"
}
}
```
--------------------------------
### Dynamic Routes - Single Param
Source: https://nitro.build/docs/routing
Create routes with parameters by using the `[]` syntax in filenames or directory names. The parameter value will be accessible in `event.context.params` or via the `getRouterParam` utility.
```APIDOC
## Dynamic Routes - Single Param
To define a route with params, use the `[]` syntax where `` is the name of the param. The param will be available in the `event.context.params` object or using the [`getRouterParam`](https://h3.dev/utils/request#getrouterparamevent-name-opts-decode) utility.
```typescript
// routes/hello/[name].ts
import { defineHandler } from "nitro";
export default defineHandler((event) => {
const { name } = event.context.params;
return `Hello ${name}!`;
});
```
Calling the route with `/hello/nitro` will return `Hello nitro!`.
```
--------------------------------
### Configure Production Output Directories
Source: https://nitro.build/config
Specifies the output directories for the production bundle, including the main directory, server directory, and public directory.
```javascript
export default defineConfig({
output: {
dir: "dist",
serverDir: "dist/server",
publicDir: "dist/public",
},
});
```
--------------------------------
### Build Project with Genezio Nitro Preset
Source: https://nitro.build/llms-full.txt
Execute this command to build your project using the Genezio Nitro preset. This command is typically run before deployment.
```bash
NITRO_PRESET=genezio npm run build
```
--------------------------------
### Production Public Assets Manifest
Source: https://nitro.build/llms-full.txt
Example of a manifest file generated during the build process, containing metadata for public assets.
```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
}
}
```
--------------------------------
### Specify Server Entry with Handler and Format
Source: https://nitro.build/llms-full.txt
Configure the server entry with explicit `handler` and `format` options for more control.
```typescript
import { defineConfig } from "nitro";
export default defineConfig({
serverEntry: {
handler: "./server.ts",
format: "node" // "web" (default) or "node"
}
})
```
--------------------------------
### Customize OpenAPI Scalar UI
Source: https://nitro.build/config
Customize the Scalar UI integration by passing a configuration object, for example, to set a theme.
```javascript
openAPI: {
ui: {
scalar: {
theme: 'purple'
}
}
}
```
--------------------------------
### Client Entrypoint for Vue SSR
Source: https://nitro.build/examples/vite-ssr-vue-router
Sets up the Vue app, Vue Router with server-rendered routes, and mounts the application for client-side hydration.
```typescript
import { createSSRApp } from "vue";
import { RouterView, createRouter, createWebHistory } from "vue-router";
import { routes } from "./routes.ts";
async function main() {
const app = createSSRApp(RouterView);
const router = createRouter({
history: createWebHistory(),
routes,
});
app.use(router);
await router.isReady();
app.mount("#root");
}
// eslint-disable-next-line unicorn/prefer-top-level-await
main();
```