Nitro (Universal JavaScript Servers)

2.13.3 · maintenance · verified Sun Apr 19

Nitro is a powerful framework for building universal JavaScript servers, enabling developers to write code once and deploy it across various environments including Node.js, serverless platforms, and edge functions. The current stable version is v2.13.3, which is maintained with regular dependency updates and critical security fixes. Active development is focused on the upcoming v3 beta, which promises further performance enhancements and features. Key differentiators include its "run anywhere" philosophy, exceptional runtime performance (approaching native levels on platforms like Bun), and a minimal install footprint. It integrates deeply with ecosystem tools like Nuxt and provides advanced features such as experimental tracing channels and smarter dependency tracing, ensuring timely updates and security patches.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure Nitro, define a basic API route using `defineEventHandler`, and access runtime configuration using `useRuntimeConfig`.

import { defineNitroConfig, defineEventHandler, useRuntimeConfig } from 'nitropack';

// nitro.config.ts
export default defineNitroConfig({
  preset: 'node', // Choose your deployment target: 'vercel', 'netlify', 'cloudflare', 'bun', etc.
  output: {
    dir: '.output', // Default output directory for the build artifacts
    publicDir: '.output/public' // Directory for static assets
  },
  // Environment variables can be exposed to the runtime here
  runtimeConfig: {
    apiSecret: process.env.API_SECRET ?? 'default_secret', // Accessible via useRuntimeConfig()
  },
  // Define a simple route directly in the config (alternative to server/ directory)
  routes: {
    '/inline-hello': 'Hello from inline route!'
  }
});

// server/api/hello.ts
export default defineEventHandler(async (event) => {
  const config = useRuntimeConfig();
  return {
    message: 'Hello from Nitro API!',
    timestamp: new Date().toISOString(),
    apiSecretPartial: config.apiSecret.substring(0, 5) + '...', // Accessing runtime config
    path: event.path
  };
});

/*
To run this example:
1. Create a `nitro.config.ts` file with the above configuration.
2. Create a `server/api/hello.ts` file with the event handler.
3. Install dependencies: `npm install nitropack xml2js` (xml2js is a peer dep).
4. Build the project: `npx nitro build`
5. Start the server: `node .output/server/index.mjs`
6. Access in browser: `http://localhost:3000/api/hello` and `http://localhost:3000/inline-hello`
*/

view raw JSON →