This folder contains examples of how to use vite-node-api in your Vite projects.
- basic.js - Basic configuration example
- with-cors.js - Configuration with CORS enabled
- custom-options.js - Configuration with custom options (body limit, timeout, etc.)
The api-routes/ folder contains example API route handlers:
- hello.js - Simple GET endpoint that returns a greeting
- users.js - GET endpoint with query parameter support
- create-user.js - POST endpoint with request body validation
npm install vite vite-node-apiCopy one of the configuration examples to your vite.config.js:
import { defineConfig } from 'vite'
import viteNodeApi from 'vite-node-api'
export default defineConfig({
plugins: [
viteNodeApi({
apiDir: 'server/api',
port: 3000,
cors: true
})
]
})Create your API route files in server/api/ directory:
// server/api/hello.js
export default function handler(req, res) {
return {
message: 'Hello World!'
}
}# Development
npm run dev
# Production build
npm run build
# Preview production
npm run previewYour API routes will be available at:
- Development:
http://localhost:5173/api/hello - Production:
http://localhost:3000/api/hello
Each API route file should export a default function that receives req and res objects:
export default function handler(req, res) {
// Access query parameters
const { id } = req.query
// Access request body (POST/PUT/PATCH)
const { name } = req.body
// Set custom status code
res.statusCode = 201
// Return JSON response
return {
success: true,
data: { id, name }
}
}| Option | Type | Default | Description |
|---|---|---|---|
apiDir |
string | "server/api" |
Directory containing API route files |
port |
number | 4173 |
Port for production runtime |
bodyLimit |
number | 1000000 |
Maximum request body size (bytes) |
timeout |
number | 30000 |
Request timeout (milliseconds) |
cors |
boolean | object | false |
Enable CORS headers |
req.method- HTTP method (GET, POST, PUT, PATCH, DELETE)req.url- Full request URLreq.query- Parsed query parametersreq.body- Parsed JSON body (POST/PUT/PATCH only)req.headers- Request headers
res.statusCode- Set HTTP status coderes.setHeader(name, value)- Set response headerres.end(data)- End response manuallyres.writableEnded- Check if response has ended