A Vite plugin that seamlessly integrates Nitro for server-side rendering, API routes, and full-stack development in a single unified framework.
npm install nitropack-vite$fetch on both client and server
bash
pnpm add nitropack-vite -D
pnpm add ofetch -S
`
Configure
- vite.config.ts
`ts
import React from '@vitejs/plugin-react'
import Nitro from 'nitropack-vite'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
React(),
// Nitro Options
Nitro({
// The source directory for the application.
// srcDir - default: './src'
// Additional automatic imports will take effect on the all page and server
// see - https://github.com/unjs/unimport
// imports - default: null
// Is it compressed during construction
// minify - default: false
})
]
})
`
- nitro.config.ts
`ts
// your nitro config
export default defineNitroConfig({
// Do not use plugins with the same configuration here (srcDir, imports, minify)
// Additional Nitro-specific configuration can be added here
})
`
- package.json
`json
{
"scripts": {
"dev": "vite dev",
"build": "vite build",
"prepare": "nitro prepare",
"preview": "node .output/server/index.mjs"
}
}
`
Usage
`sh
pnpm run dev
`
print:
`
VITE v7.0.0 ready in 1275 ms
ā Local: http://localhost:5173/
ā Network: use --host to expose
ā press h + enter to show help
ā Nitro Server built in 451ms
`
Add an API route, for example src/routes/hello.ts
`ts
export default defineEventHandler((event) => {
return 'Hello World'
})
`
> nitropack-vite will automatically handle the relationship between routes and page routes without the need for additional configuration.
Visit http://localhost:5173/hello, and you will see the response "Hello World".
Use $fetch to make API requests on the page.
`tsx
// App.tsx
function App() {
useEffect(() => {
$fetch('/hello').then((response) => {
console.log(response) // "Hello World"
})
}, [])
return null
}
`
And you can customize the $fetch instance:
`ts
// Customize $fetch with additional options
import type { $Fetch } from 'nitropack'
import { createFetch } from 'ofetch'
globalThis.$fetch = createFetch({
baseURL: 'http://...',
headers: { 'x-custom-header': 'value' },
retry: 3
}) as $Fetch
`
Deployment
The built application can be deployed to various platforms:
`bash
Build for production
pnpm build
Preview the production build
pnpm preview
`
Vercel
You need to edit vercel.json and select nitro when selecting project deployment
`json
{
"$schema": "https://openapi.vercel.sh/vercel.json",
"installCommand": "pnpm install",
"buildCommand": "pnpm build",
"outputDirectory": ".output",
"devCommand": "pnpm dev"
}
``