Nitro Universal Server Framework

3.0.1-20260420-010726-8c3f16b2 · active · verified Tue Apr 21

Nitro is a versatile framework for building and deploying universal JavaScript servers, extending existing Vite applications with production-ready server capabilities. The `nitro-nightly` package represents the active development line for Nitro v3, which is currently in beta. Nitro v3 aims for a significantly smaller install size (down to 9MB), near-native runtime performance, and enhanced features like experimental tracing channels and smarter dependency tracing. While the stable release series remains v2, `nitro-nightly` provides access to cutting-edge features and improvements for upcoming major versions. Nitro focuses on a "run anywhere" philosophy, abstracting deployment complexities, and often offers a zero-configuration experience for common use cases. New `nitro-nightly` releases are frequent, reflecting active development and testing against real-world projects.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a basic Nitro server, define multiple API routes using defineEventHandler, access request parameters, and start the server. It also shows a placeholder for accessing runtime configuration.

import { defineEventHandler, createApp, toNodeListener, useRuntimeConfig } from 'nitro';
import { listen } from 'listhen';

// Define a simple server route
const helloHandler = defineEventHandler(() => {
  const message = 'Hello from Nitro!';
  const date = new Date().toISOString();
  // Example of using runtime config (though not explicitly set here)
  const secretKey = process.env.MY_SECRET_KEY ?? 'default_secret';
  console.log(`Request received at ${date}. Using secret: ${secretKey}`);
  return { api: message, timestamp: date, secretUsed: secretKey };
});

const userHandler = defineEventHandler((event) => {
  const name = event.context.params?.name || 'Guest';
  return { message: `Hello, ${name}!` };
});

// Create a Nitro application
const app = createApp();

// Add routes to the app
app.router.get('/', helloHandler);
app.router.get('/api/hello/:name', userHandler);
app.router.get('/api/config', defineEventHandler(() => {
  const config = useRuntimeConfig(); // Access runtime config
  return {
    public: config.public,
    serverSecret: config.serverSecret // Example of a server-only secret
  };
}));

// Define configuration for the server
const serverConfig = {
  host: process.env.HOST || '0.0.0.0',
  port: parseInt(process.env.PORT || '3000')
};

// Start the server
async function startServer() {
  const listener = toNodeListener(app);
  console.log(`Nitro server running on http://${serverConfig.host}:${serverConfig.port}`);
  await listen(listener, serverConfig);
}

startServer().catch((error) => {
  console.error('Failed to start Nitro server:', error);
  process.exit(1);
});

view raw JSON →