Package Exports
- nitropack
- nitropack/cli
- nitropack/dist/runtime/app
- nitropack/dist/runtime/cache
- nitropack/dist/runtime/client
- nitropack/dist/runtime/config
- nitropack/dist/runtime/entries/aws-lambda
- nitropack/dist/runtime/entries/azure
- nitropack/dist/runtime/entries/azure-functions
- nitropack/dist/runtime/entries/cli
- nitropack/dist/runtime/entries/cloudflare
- nitropack/dist/runtime/entries/firebase
- nitropack/dist/runtime/entries/netlify-builder
- nitropack/dist/runtime/entries/nitro-dev
- nitropack/dist/runtime/entries/nitro-prerenderer
- nitropack/dist/runtime/entries/node
- nitropack/dist/runtime/entries/node-server
- nitropack/dist/runtime/entries/service-worker
- nitropack/dist/runtime/entries/vercel
- nitropack/dist/runtime/error
- nitropack/dist/runtime/index
- nitropack/dist/runtime/plugin
- nitropack/dist/runtime/static
- nitropack/dist/runtime/timing
- nitropack/dist/runtime/utils
- nitropack/dist/runtime/virtual/polyfills
- nitropack/runtime/app
- nitropack/runtime/cache
- nitropack/runtime/client
- nitropack/runtime/config
- nitropack/runtime/entries/aws-lambda
- nitropack/runtime/entries/azure
- nitropack/runtime/entries/azure-functions
- nitropack/runtime/entries/cli
- nitropack/runtime/entries/cloudflare
- nitropack/runtime/entries/firebase
- nitropack/runtime/entries/netlify-builder
- nitropack/runtime/entries/nitro-dev
- nitropack/runtime/entries/nitro-prerenderer
- nitropack/runtime/entries/node
- nitropack/runtime/entries/node-server
- nitropack/runtime/entries/service-worker
- nitropack/runtime/entries/vercel
- nitropack/runtime/error
- nitropack/runtime/index
- nitropack/runtime/plugin
- nitropack/runtime/static
- nitropack/runtime/timing
- nitropack/runtime/utils
- nitropack/runtime/virtual/polyfills
Readme
⚗️ nitro
The complete solution to build and deploy universal JavaScript servers. nitro provides both build tooling and a runtime framework from the UnJS ecosystem.
🌱 nitro is young and under development 🌱
🐛 Check open issues for roadmap and known issues.
🎁 Contributions are more than welcome to improve documentation.
🏀 Online playground on StackBlitz
❯ Rapid development experience with hot module replacement
❯ Multi-provider deployments with a single codebase and zero-configuration
❯ Portable and compact deployments without node_modules dependency
❯ Directory structure aware to register API routes and more with zero configuration
❯ Minimal Design to fit into any solution with minimum overhead
❯ Code-splitting and async chunk loading for fast server startup time
❯ TypeScript fully supported
❯ Multi-driver storage and caching layer
❯ Route caching and static pre-rendering with built-in crawler
❯ Hackable to extend almost any part of nitro using options
❯ Auto imports for lazy folks and a tidy minimal codebase
❯ Best-effort compatibility for using legacy npm packages and mocking Node.js modules
⚡️ Quick Start
0️⃣ Create an empty directory nitro-app
mkdir nitro-app
cd nitro-app1️⃣ Create api/hello.ts:
export default () => 'nitro is amazing!'2️⃣ Start development server:
npx nitropack dev🪄 Your API is ready at http://localhost:3000/api/hello
🤓 [TIP] Check .nitro/dev/index.mjs if want to know what is happening
3️⃣ You can now build your production-ready server:
npx nitropack build4️⃣ Output is in the .output directory and ready to be deployed on almost any VPS with no dependencies. You can locally try it too:
node .output/server/index.mjsTypescript Support
nitro uses the #nitro alias for runtime helpers and global imports. To add type support within your project,
you should add the following to your tsconfig.json file:
{
"extends": "./.nitro/types/tsconfig.json"
}API Routes
API files inside api/ directory will be automatically mapped to API routes and served using h3 router.
Example: Simple API route
// api/test.ts
import { eventHandler } from 'h3'
export default eventHandler(() => 'Hello World!')Example: API route with params
// api/hello/[name].ts
import { eventHandler } from 'h3'
export default eventHandler(event => `Hello ${event.params.name}!`)Storage
nitro provides a built-in storage layer using unjs/unstorage that can abstract filesystem access.
import { useStorage } from '#nitro'ℹ️ See unjs/unstorage for more usage information.
Example: Simple operations
import { useStorage } from '#nitro'
await useStorage().setItem('test:foo', { hello: world })
await useStorage().getItem('test:foo')By default storage is in-memory with mounted cache: prefix only for development.
You can add more mountpoints using storage option:
// nitro.config.ts
import { definenitroConfig } from 'nitropack'
export default definenitroConfig({
storage: {
'/redis': {
driver: 'redis',
/* redis connector options */
}
}
})Cache API
nitro provides a powerful caching system built on top of storage layer.
import { defineCachedFunction } from '#nitro'
import { cachedEventHandler } from '#nitro'Example: Cache an API handler
// api/test.ts
import { defineCachedFunction } from '#nitro'
const myFn = cachedEventHandler(async () => {
new Promise(resolve => setTimeout(resolve, 1000))
return `Response generated at ${new Date().toISOString()})`
}, { swr: true })Example: Cache a utility function
// utils/index.ts
import { defineCachedFunction } from '#nitro'
const myFn = defineCachedFunction(async () => {
new Promise(resolve => setTimeout(resolve, 1000))
return Math.random()
}, { swr: true })Example: Enable cache on group of routes
// nitro.config.ts
import { definenitroConfig } from 'nitropack'
export default definenitroConfig({
routes: {
'/blog/**': { swr: true }
}
})Public Assets
All assets in public/ directory will be automatically served.
Nitro plugins
In order to extend nitro's runtime behavior, we can register plugins.
They will be synchronously on first nitro initialization given nitroApp context which can be used to hook into lifecycle events.
Example: Simple plugin
// plugins/test.ts
import { defineNitroPlugin } from '#nitro'
export default defineNitroPlugin((nitroApp) => {
console.log('Nitro plugin', nitroApp)
})// nitro.config.ts
import { definenitroConfig } from 'nitropack'
export default definenitroConfig({
plugins: [
'~/plugins/test'
]
})Deployment Presets
Built-in presets:
aws-lambdaazure,azure-functions(deployment guide)clicloudflare(deployment guide)firebase(deployment guide)netlify(deployment guide)nitro-devnitro-prerendernodenode-server(deployment guide)node-cliservice-workervercel(deployment guide)
You can build nitro project against a specific preset using NITRO_PRESET=name npx nitropack build
There is a demo repository for nitro deployments: https://github.com/unjs/nitro-deploys
📚 Options
nitro provides lots of options them to customize any part of its behavior. It is powerful enough that all deployment providers are built on the exact options API.
Create a new nitro.config.ts file to provide options:
// nitro.config.ts
import { definenitroConfig } from 'nitropack'
export default definenitroConfig({
})🤓 [TIP] nitro handles configuration loading using unjs/c12. You have more advanced possibilities such as using .env. And .nitrorc.
General
preset
Use preset option NITRO_PRESET environment variable for custom production preset.
Preset for development mode is always nitro-dev and default node-server for production building a standalone Node.js server.
The preset will automatically be detected when the preset option is not set and running in known environments.
logLevel
- Default:
3(1when testing environment is detected)
Log verbosity level. See unjs/consola#level for more information.
runtimeConfig
- Default:
{ nitro: { ... }, ...yourOptions }
Server runtime configuration.
Note:: nitro namespace is reserved.
Directories
rootDir
Project main directory
srcDir
Project source directory. Same as rootDir unless specified. Helpful to move code into src/.
scanDirs
- Default: (source directory when empty array)
List of directories to scan and auto-register files, such as API routes.
buildDir
- Default:
.nitro
nitro's temporary working directory for generating build-related files.
output
- Default:
{ dir: '.output', serverDir: '.output/server', publicDir: '.output/public' }
Output directories for production bundle.
Features
experimental
- Default:
{}
Enable experimental features. Currently, non are available!
storage
- Default:
{}
Storage configuration.
timing
- Default:
false
Enable timing information.
renderer
Path to main render (file should export an event handler as default)
serveStatic
- Default:
false
Serve public/ assets in production.
Note: It is highly recommended that your edge CDN (nginx, apache, cloud) serves the public/ directory instead.
publicAssets
Public asset directories to serve in development and bundle in production.
If a public/ directory is detected, it will be added by default, but you can add more by yourself too!
serverAssets
Assets can be accessed in server logic and bundled in production.
dev
- Default:
truefor development andfalsefor production.
You probably don't want to override it!
devServer
- Default:
{ watch: [] }
Dev server options. You can use watch to make the dev server reload if any file changes in specified paths.
watchOptions
Watch options for development mode. See chokidar for more information.
autoImport
Auto import options. See unjs/unimport for more information.
plugins
- Default:
[]
Array of paths to nitro plugins. They will be executed by order on first initialization.
Routing
baseURL
Default: / (or NITRO_APP_BASE_URL environment variable if provided)
Server's main base URL.
handlers
Server handlers and routes.
If api/ and middleware/ directories exist, they will be automatically added to the handlers array.
devHandlers
Regular handlers refer to the path of handlers to be imported and transformed by rollup.
There are situations in that we directly want to provide a handler instance with programmatic usage.
We can use devHandlers but note that they are only available in development mode and not in production build.
routes
Route options. It is a map from route pattern (following unjs/radix3) to options.
Example:
{
routes: {
'/blog/**': { swr: true }
}
}prerenderer
Default: { crawlLinks: false, routes: [] }
Prerendered options. Any route specified will be fetched during the build and copied to the .output/public directory as a static asset.
If crawlLinks option is set to true, nitro starts with / by default (or all routes in routes array) and for HTML pages extracts <a href=""> tags and prerender them as well.
Rollup
⚠️ Caution! Rollup options are considered advanced, and things can go wrong if misconfigured. nitro and presets provide the best defaults.
rollupConfig
Additional rollup configuration.
entry
Rollup entry.
unenv
Options for unjs/unenv preset.
alias
Rollup aliases options.
minify
- Default:
false
Minify bundle.
inlineDynamicImports
Avoid creating chunks.
sourceMap
Enable source-map generation
node
Specify whether the build is used for Node.js or not. If set to false, nitro tried to mock Node.js dependencies using unjs/unenv and adjust its behavior.
analyze
If enabled, will analyze server bundle after build using rollup-plugin-visualizer. You can also pass your custom options.
moduleSideEffects
Default: [unenv/runtime/polyfill/]
Rollup specific option. Specifies module imports that have side-effects
replace
Rollup specific option.
Advanced
⚠️ Caution! These options are considered advanced, and things can go wrong if misconfigured. nitro and presets provide the best defaults.
typescript
Default: { generateTsConfig: true }
nodeModulesDirs
Additional node_modules to search when resolving a module. By default user directory is added.
hooks
nitro hooks. See unjs/hookable for more information.
commands
Preview and deploy command hints are usually filled by deployment presets.
🎁 Contribution
Before everything, please make sure there is an option issue either confirming issue/bug 🐛 or you have an explicit 👍 to add an enhancement or new feature. Thanks in advance 🙏
- Fork and clone this repository
- Enable corepack using
corepack enable(usenpm i -g corepackfor Node.js < 16.10) - Install dependencies using
yarn install. - Start playground with
yarn devand open http://localhost:3000 - Make changes
- Ensure all tests pass using the
yarn testcommand - Open that lovely PR!
License
Made with 💛 Published under MIT.