Nitro Documentation
repository·main·Indexed 27 days ago
https://github.com/nitrojs/nitroA production-ready, platform-agnostic server engine designed to extend Vite applications. Nitro provides a zero-config experience for adding server routes and deploying universal JavaScript servers across various environments. Key features include filesystem-based routing, a flexible renderer for SPAs and SSR, and integration with Rolldown for build customization.
What's inside Nitro
- Nitro is a production-ready server engine that extends Vite applications. It is designed to be platform-agnostic, allowing you to add server routes and deploy your application across multiple environments with a zero-config experience.
Overview of Nitro features
mainNitro is a production-ready server engine that extends Vite applications. Key capabilities include:
- File-system Routing: Automatically register routes in a
routes/folder or use a custom entry point (H3, Hono, Elysia, Express). - Multi-runtime Deployment: Deploy to Node.js, Cloudflare Workers, Deno, Bun, AWS Lambda, Vercel, Netlify, etc., with zero config.
- Universal Storage: A key-value storage abstraction (powered by
unstorage) that works with filesystem, Redis, Cloudflare KV, and more. - Built-in Caching: Cache route handlers and functions using various storage backends and stale-while-revalidate patterns.
- Server Entry: Support for Web standard servers including H3, Hono, Elysia, Express, or the raw fetch API.
- Universal Renderer: Works with any frontend framework as a server layer.
- Server Plugins: Extend runtime behavior by hooking into lifecycle events via the
plugins/directory. - Built-in Database: A lightweight SQL layer (powered by
db0) with support for SQLite, PostgreSQL, MySQL, and Cloudflare D1. - Assets: Serve public assets to clients or bundle server assets for programmatic access.
- File-system Routing: Automatically register routes in a
Create a Server Entry for React SSR
mainThe server entry point is responsible for rendering your React application to a streaming HTML response. For edge-compatible streaming, use
renderToReadableStreamfromreact-dom/server.edge.To manage assets (CSS and JS) correctly, import your client and server entries using the
?assets=clientand?assets=ssrquery parameters. You can then use the.merge()method on the client assets to combine them with server assets, providing a unified manifest of stylesheets, module preloads, and the main entry script.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( <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> {assets.css.map((attr: any) => ( <link key={attr.href} rel="stylesheet" {...attr} /> ))} {assets.js.map((attr: any) => ( <link key={attr.href} type="modulepreload" {...attr} /> ))} <script type="module" src={assets.entry} /> </head> <body id="app"> <App /> </body> </html> ), { headers: { "Content-Type": "text/html;charset=utf-8" } } ); }, };Deploy to Cloudflare Pages
mainTo deploy a Nitro application to Cloudflare Pages, use the
cloudflare_pagespreset.Note: Cloudflare Workers (
cloudflare_module) is currently the recommended preset. Use Pages only if specific features are required.Configuration
import { defineConfig } from "nitro"; export default defineConfig({ preset: "cloudflare_pages" })Nitro automatically generates a
_routes.jsonfile for routing. You can override this using thecloudflare.pages.routesconfig option.Local Preview
npm run build wrangler pages devManual Deploy
wrangler login wrangler pages deployConfigure GitHub Actions workflow for GitHub Pages deployment
mainUse the following GitHub Actions workflow configuration to build your Nitro app and deploy it to GitHub Pages. This workflow includes a
buildjob that generates the output and adeployjob that uses theactions/deploy-pagesaction.Key requirements:
- Set
NITRO_PRESET: github_pagesin the build step. - Upload the
./.output/publicdirectory usingactions/upload-pages-artifact@v1. - The
deployjob must havepermissionsforpages: writeandid-token: write. - The
deployjob must depend on thebuildjob vianeeds: build.
name: Deploy to GitHub Pages on: workflow_dispatch: push: branches: - main jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - run: corepack enable - uses: actions/setup-node@v6 with: node-version: "18" - run: npx nypm install - run: npm run build env: NITRO_PRESET: github_pages - name: Upload artifact uses: actions/upload-pages-artifact@v1 with: path: ./.output/public deploy: needs: build permissions: pages: write id-token: write environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} runs-on: ubuntu-latest steps: - name: Deploy to GitHub Pages id: deployment uses: actions/deploy-pages@v1- Set
Define dynamic routes with parameters
mainYou can define dynamic routes using the
[<param>]syntax. Parameters are accessible viaevent.context.paramsor thegetRouterParamutility.- Single param: Use
[name].ts(e.g.,routes/hello/[name].tsmatches/hello/nitro). - Multiple params: Use nested folders like
[name]/[age].ts(e.g.,routes/hello/[name]/[age].ts). You cannot define multiple params in a single filename. - Catch-all params: Use
[...name].tsto capture all remaining URL segments (e.g.,routes/hello/[...name].tsmatches/hello/nitro/is/hot).
import { defineHandler } from "nitro"; export default defineHandler((event) => { const { name } = event.context.params; return `Hello ${name}!`; });- Single param: Use
Deploy Nitro apps to Cleavr
mainTo deploy a Nitro application to Cleavr, you must set the Nitro preset to
cleavr. This allows Nitro to build the application in a format compatible with Cleavr's environment.Configuration
Update your configuration file (e.g.,
nitro.config.tsor your framework's config) to include thecleavrpreset:export default { nitro: { preset: 'cleavr' } }Cleavr Panel Setup
After pushing your changes to your code repository, follow these steps in the Cleavr dashboard:
- Provision a new server.
- Add a website, selecting Nuxt 3 as the app type.
- Navigate to web app > settings > Code Repo and point it to your project's code repository.
Note: Integration with this provider is possible with zero configuration.
Define specific HTTP methods for routes
mainYou can restrict a route to a specific HTTP method by suffixing the filename with the method name followed by.ts(e.g.,.get.ts,.post.ts,.put.ts,.delete.ts).Integrate Express with Nitro using a custom server entry
mainTo use Express as your backend framework with Nitro, you must provide a custom server entry file named
server.node.tsin your project root. Nitro will auto-detect this file and use it as the entry point. This approach gives you full control over Express routing and middleware, but note that the.node.tssuffix indicates this entry is Node.js specific and is not compatible with other runtimes like Cloudflare Workers or Deno.Setup Requirements
- Dependencies: Ensure
expressand@types/expressare installed. - Vite Configuration: Include the
nitro()plugin in yourvite.config.ts. - Server Entry: Create
server.node.tsand export your Express application instance as the default export.
import Express from "express"; const app = Express(); app.use("/", (_req, res) => { res.send("Hello from Express with Nitro!"); }); export default app;- Dependencies: Ensure
Deploy Nitro apps to EdgeOne Pages via Control Panel
mainTo deploy your Nitro application to EdgeOne Pages using the web control panel, follow these steps:
- Go to the EdgeOne pages control panel and click Create project.
- Select Import Git repository as the deployment method (supports GitHub, GitLab, Gitee, and CNB).
- Select the appropriate repository and branch for your application.
- Crucial Step: Add the environment variable
NITRO_PRESETwith the valueedgeone-pagesduring the setup process. - Click Deploy.
Implement Global Middleware
mainGlobal middleware is defined in the
middleware/directory. These handlers run after route rules. You can useevent.contextto pass data through the lifecycle.Warning: Returning from a middleware will close the request; avoid doing this unless you intend to terminate the request early.
import { defineHandler } from "nitro"; export default defineHandler((event) => { event.context.info = { name: "Nitro" }; });Enable OpenAPI support in Nitro
mainTo use Nitro's automatic OpenAPI specification generation and interactive documentation UIs, enable the experimental
openAPIfeature in yournitro.config.ts.Once enabled, the following endpoints are available during development:
/_openapi.json: The OpenAPI 3.1.0 JSON specification./_scalar: The Scalar API reference UI./_swagger: The Swagger UI.
IMPORTANT OpenAPI support is currently experimental.
import { defineConfig } from "nitro"; export default defineConfig({ experimental: { openAPI: true, }, });