Getting Started β
Welcome to vite-plugin-universal-api! This guide will help you get up and running with mock APIs in your Vite project.
What is vite-plugin-universal-api? β
vite-plugin-universal-api is a comprehensive Vite plugin that transforms your development server into a powerful mock backend. It provides three complementary approaches to handle API requests:
- π File-System Based API - Automatically serve mock data from your file system
- π REST API Handlers - Define custom programmatic handlers for dynamic responses
- β‘ WebSocket Support - Real-time bidirectional communication with rooms and broadcast capabilities
Why Use This Plugin? β
Building modern web applications often requires mocking backend APIs during development. This plugin provides three complementary approaches:
- π File-System API - Perfect for static mock data, quick prototyping, and testing
- π REST Handlers - Full control for complex logic, validation, and dynamic responses
- β‘ WebSocket - Real-time features like chat, notifications, and live updates
All integrated seamlessly into your Vite development server, with hot reload and zero configuration required.
Perfect for Frontend Developers β
- Develop Without Backend: Start building your frontend immediately without waiting for backend APIs
- Work Offline: No internet or VPN required during development
- Test Edge Cases: Easily simulate errors, timeouts, and unusual scenarios
- Prototype Quickly: Rapid prototyping and demos without backend infrastructure
Key Benefits β
- β Zero Configuration - Point to a directory and start serving files
- β Full TypeScript Support - Comprehensive type definitions included
- β Express Compatible - Use familiar Express middleware and parsers
- β Hot Reload - Changes reflected immediately during development
- β Production Ready - Well-tested with comprehensive test coverage
Requirements β
Before you begin, make sure you have:
- Node.js:
^16.0.0 || ^18.0.0 || >=20.0.0 - Vite:
^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || >=8.0.0
Installation β
Install the plugin as a development dependency:
pnpm add -D @ndriadev/vite-plugin-universal-apinpm install -D @ndriadev/vite-plugin-universal-apiyarn add -D @ndriadev/vite-plugin-universal-apiBasic Setup β
1. Configure Vite β
Add the plugin to your vite.config.ts:
import { defineConfig } from 'vite'
// import mockApi from '@ndriadev/vite-plugin-universal-api' //Default export
import { universalApi } from '@ndriadev/vite-plugin-universal-api' // Named export
export default defineConfig({
plugins: [
universalApi({
endpointPrefix: '/api',
fsDir: 'mock'
})
]
})2. Create Mock Data β
Create a directory for your mock files:
project/
βββ mock/
β βββ users.json
β βββ posts.json
βββ src/
βββ vite.config.tsAdd some mock data:
// mock/users.json
[
{
"id": 1,
"name": "John Doe",
"email": "john@example.com"
},
{
"id": 2,
"name": "Jane Smith",
"email": "jane@example.com"
}
]This file will handle requests to:
GET /api/users3. Call the API from your app β
// services/users.ts
export async function getUsers() {
const res = await fetch('/api/users')
if (!res.ok) {
throw new Error('Failed to fetch users')
}
return res.json()
}4. Start Development Server β
npm run dev5. Access Your Mock API β
Your mock data is now available:
# Fetch all users
...
const result = await getUsers();
# Returns:
# [
# {"id": 1, "name": "John Doe", "email": "john@example.com"},
# {"id": 2, "name": "Jane Smith", "email": "jane@example.com"}
# ]Using real APIs in production β
In a real application, you usually want:
- mocked endpoints during development
- real APIs in production
You can achieve this with a simple configuration.
Centralize your API base URL β
// api.ts
export const API_BASE_URL=import.meta.env.PROD
? 'https://api.example.com'
: '/api'Use it in your services β
// services/users.ts
import {API_BASE_URL }from'../api'
export async function getUsers() {
const res = await fetch(`${API_BASE_URL}/users`)
if (!res.ok) {
throw new Error('Failed to fetch users')
}
return res.json()
}How it works β
- Development
/api/usersΒ is handled byΒvite-plugin-universal-api- responses come from your local files (e.g.Β
api/users.get.ts)
- Production
- requests go toΒ
https://api.example.com/users - your app behaves like a standard client
- requests go toΒ
TIP
vite-plugin-universal-apiΒ only affects development.
In production, your application performs real HTTP requests.
Optional: Environment variables β
For more flexibility, useΒ .envΒ files:
# .env.development
VITE_API_BASE_URL=/api
# .env.production
VITE_API_BASE_URL=https://api.example.com// api.ts
export const API_BASE_URL = import.meta.env.VITE_API_BASE_URLAlternative: Vite proxy β
If you prefer not to define local endpoints, you can proxy requests:
// vite.config.ts
export default {
server: {
proxy: {
'/api': {
target:'https://api.example.com',
changeOrigin:true,
rewrite: (path) =>path.replace(/^\/api/,'')
}
}
}
}Summary β
- define API routes as files during development
- call them usingΒ
fetch('/api/...') - switch to real APIs in production with a base URL
- no changes needed in your business logic
What's Next? β
Now that you have a basic setup running, explore more features:
- Quick Start - Learn the three main approaches
- File-System API - Deep dive into file-based mocking
- REST Handlers - Create custom dynamic handlers
- WebSocket - Add real-time communication
- Examples - See real-world examples
Getting Help β
If you run into issues:
- Check the Troubleshooting guide
- Search GitHub Issues
- Ask in GitHub Discussions
Next Steps β
Recommended Path
- β You are here - Getting Started
- π Quick Start - Try all three approaches
- π― File-System API - Master file-based mocking
- π‘ Examples - See real-world use cases
