0
# Development Server
1
2
Vite's development server provides instant server start, native ES modules, and lightning-fast Hot Module Replacement (HMR). It includes middleware support, proxy configuration, and comprehensive file serving capabilities.
3
4
## Capabilities
5
6
### Create Server
7
8
Creates a Vite development server instance.
9
10
```typescript { .api }
11
/**
12
* Create a Vite development server
13
* @param config - Inline configuration options
14
* @returns Promise resolving to ViteDevServer instance
15
*/
16
function createServer(config?: InlineConfig): Promise<ViteDevServer>;
17
18
interface ViteDevServer {
19
/** The resolved vite config object */
20
config: ResolvedConfig;
21
/** Connect middleware stack */
22
middlewares: Connect.Server;
23
/** Underlying HTTP server (null in middleware mode) */
24
httpServer: HttpServer | null;
25
/** Chokidar watcher instance */
26
watcher: FSWatcher;
27
/** WebSocket server for HMR */
28
ws: WebSocketServer;
29
/** Hot channel (alias to server.environments.client.hot) */
30
hot: NormalizedHotChannel;
31
/** Plugin container */
32
pluginContainer: PluginContainer;
33
/** Module execution environments */
34
environments: Record<'client' | 'ssr' | (string & {}), DevEnvironment>;
35
/** Module graph for tracking dependencies */
36
moduleGraph: ModuleGraph;
37
/** Resolved server URLs */
38
resolvedUrls: ResolvedServerUrls | null;
39
/** Transform request without HTTP pipeline */
40
transformRequest(url: string, options?: TransformOptions): Promise<TransformResult | null>;
41
/** Warm up URLs for caching */
42
warmupRequest(url: string, options?: TransformOptions): Promise<void>;
43
/** Apply HTML transforms */
44
transformIndexHtml(url: string, html: string, originalUrl?: string): Promise<string>;
45
/** Transform module code into SSR format */
46
ssrTransform(code: string, inMap: SourceMap | null, url: string, originalCode?: string): Promise<TransformResult | null>;
47
/** Load URL as instantiated module for SSR */
48
ssrLoadModule(url: string, opts?: { fixStacktrace?: boolean }): Promise<Record<string, any>>;
49
/** Fix SSR stack trace */
50
ssrRewriteStacktrace(stack: string): string;
51
/** Mutate SSR error by rewriting stacktrace */
52
ssrFixStacktrace(e: Error): void;
53
/** Trigger HMR for a module */
54
reloadModule(module: ModuleNode): Promise<void>;
55
/** Start the server */
56
listen(port?: number, isRestart?: boolean): Promise<ViteDevServer>;
57
/** Stop the server */
58
close(): Promise<void>;
59
/** Print server URLs */
60
printUrls(): void;
61
/** Bind CLI shortcuts */
62
bindCLIShortcuts(options?: BindCLIShortcutsOptions): void;
63
/** Restart the server */
64
restart(forceOptimize?: boolean): Promise<void>;
65
}
66
```
67
68
**Usage Examples:**
69
70
```typescript
71
import { createServer } from "vite";
72
73
// Basic server
74
const server = await createServer({
75
server: {
76
port: 3000,
77
host: 'localhost'
78
}
79
});
80
81
await server.listen();
82
console.log('Server running at:', server.resolvedUrls?.local[0]);
83
84
// Server with middleware
85
const server2 = await createServer();
86
server2.middlewares.use('/api', (req, res, next) => {
87
if (req.url === '/api/health') {
88
res.end('OK');
89
} else {
90
next();
91
}
92
});
93
94
await server2.listen(4000);
95
```
96
97
### Server Configuration
98
99
Configure server behavior, ports, proxy, and middleware options.
100
101
```typescript { .api }
102
interface ServerOptions {
103
/** Server host (default: 'localhost') */
104
host?: string | boolean;
105
/** Server port (default: 5173) */
106
port?: number;
107
/** Strictly enforce port */
108
strictPort?: boolean;
109
/** HTTPS options */
110
https?: boolean | HttpsOptions;
111
/** Open browser on server start */
112
open?: boolean | string | OpenOptions;
113
/** Proxy rules */
114
proxy?: Record<string, string | ProxyOptions>;
115
/** CORS options */
116
cors?: boolean | CorsOptions;
117
/** Headers to send */
118
headers?: OutgoingHttpHeaders;
119
/** File system serving options */
120
fs?: FileSystemServeOptions;
121
/** Origin checking */
122
origin?: string;
123
/** Force dependency pre-bundling */
124
force?: boolean;
125
/** HMR options */
126
hmr?: boolean | HmrOptions;
127
/** Watch options */
128
watch?: WatchOptions;
129
/** Middleware mode */
130
middlewareMode?: boolean | 'html' | 'ssr';
131
/** Middleware options */
132
middlewareOptions?: {
133
/** Base path for middleware */
134
base?: string;
135
};
136
}
137
138
interface ResolvedServerOptions extends ServerOptions {
139
host: string | undefined;
140
port: number;
141
https: boolean;
142
open: boolean;
143
proxy: Record<string, ProxyOptions> | undefined;
144
cors: CorsOptions | boolean;
145
fs: Required<FileSystemServeOptions>;
146
hmr: HmrOptions | boolean;
147
watch: WatchOptions;
148
middlewareMode: boolean | 'html' | 'ssr';
149
}
150
```
151
152
### File System Serving
153
154
Control which files can be served and how file system access is managed.
155
156
```typescript { .api }
157
interface FileSystemServeOptions {
158
/** Allow serving files outside root */
159
strict?: boolean;
160
/** Allowed directories */
161
allow?: string[];
162
/** Deny patterns */
163
deny?: string[];
164
/** Case sensitive file names */
165
caseSensitive?: boolean | 'auto';
166
}
167
168
/**
169
* Check if file serving is allowed
170
* @param filename - File path to check
171
* @param server - Vite dev server instance
172
* @returns Whether file can be served
173
*/
174
function isFileServingAllowed(filename: string, server: ViteDevServer): boolean;
175
176
/**
177
* Check if file loading is allowed
178
* @param filename - File path to check
179
* @param server - Vite dev server instance
180
* @returns Whether file can be loaded
181
*/
182
function isFileLoadingAllowed(filename: string, server: ViteDevServer): boolean;
183
```
184
185
### Server URLs Resolution
186
187
Resolve and format server URLs for different network interfaces.
188
189
```typescript { .api }
190
interface ResolvedServerUrls {
191
/** Local URLs (localhost) */
192
local: string[];
193
/** Network URLs (LAN) */
194
network: string[];
195
}
196
```
197
198
### Proxy Configuration
199
200
Configure proxy rules for API requests and external services.
201
202
```typescript { .api }
203
interface ProxyOptions {
204
/** Target URL to proxy to */
205
target?: string;
206
/** Change origin header */
207
changeOrigin?: boolean;
208
/** Rewrite path */
209
pathRewrite?: Record<string, string> | ((path: string) => string);
210
/** Proxy WebSocket */
211
ws?: boolean;
212
/** Configure proxy agent */
213
agent?: any;
214
/** Custom request headers */
215
headers?: Record<string, string>;
216
/** Proxy timeout */
217
timeout?: number;
218
/** Secure proxy */
219
secure?: boolean;
220
/** Configure response handler */
221
configure?: (proxy: any, options: ProxyOptions) => void;
222
}
223
```
224
225
### HTTP Send
226
227
Send HTTP responses with proper headers and caching.
228
229
```typescript { .api }
230
/**
231
* Send HTTP response with appropriate headers
232
* @param req - HTTP request
233
* @param res - HTTP response
234
* @param content - Response content
235
* @param type - Content type
236
* @param options - Send options
237
*/
238
function send(
239
req: IncomingMessage,
240
res: ServerResponse,
241
content: string | Buffer,
242
type: string,
243
options: SendOptions
244
): void;
245
246
interface SendOptions {
247
/** Enable etag header */
248
etag?: string;
249
/** Cache control header */
250
cacheControl?: string;
251
/** Additional headers */
252
headers?: OutgoingHttpHeaders;
253
/** Source map */
254
map?: SourceMap | null;
255
}
256
```
257
258
## Server Types
259
260
```typescript { .api }
261
type HttpServer = http.Server | http2.Http2SecureServer;
262
263
interface HttpsOptions {
264
key?: string | Buffer | Array<string | Buffer>;
265
cert?: string | Buffer | Array<string | Buffer>;
266
ca?: string | Buffer | Array<string | Buffer>;
267
pfx?: string | Buffer | Array<string | Buffer>;
268
passphrase?: string;
269
}
270
271
interface OpenOptions {
272
/** URL or pathname to open */
273
url?: string;
274
/** Browser app name */
275
app?: string | readonly string[];
276
/** Wait for app */
277
wait?: boolean;
278
}
279
280
type ServerHook = (
281
server: ViteDevServer
282
) => (() => void) | void | Promise<(() => void) | void>;
283
284
interface CommonServerOptions {
285
/** Server port */
286
port?: number;
287
/** Server host */
288
host?: string | boolean;
289
/** HTTPS configuration */
290
https?: boolean | HttpsOptions;
291
/** Open browser */
292
open?: boolean | string | OpenOptions;
293
/** Proxy configuration */
294
proxy?: Record<string, string | ProxyOptions>;
295
/** CORS configuration */
296
cors?: boolean | CorsOptions;
297
/** Custom headers */
298
headers?: OutgoingHttpHeaders;
299
}
300
```