0
# Configuration
1
2
SvelteKit provides extensive configuration options through the `svelte.config.js` file to customize the framework's behavior, build process, and deployment settings.
3
4
## Capabilities
5
6
### Core Configuration Interface
7
8
The main configuration object that extends Svelte's configuration.
9
10
```typescript { .api }
11
interface Config {
12
/** SvelteKit configuration options */
13
kit?: KitConfig;
14
/** Vite plugin Svelte configuration (inherited) */
15
extensions?: string[];
16
compilerOptions?: any;
17
preprocess?: any;
18
[key: string]: any;
19
}
20
21
interface KitConfig {
22
/** Adapter for deployment platform */
23
adapter?: Adapter;
24
/** Path aliases for imports */
25
alias?: Record<string, string>;
26
/** Directory name for SvelteKit assets */
27
appDir?: string;
28
/** Content Security Policy configuration */
29
csp?: CSPConfig;
30
/** Cross-Site Request Forgery protection */
31
csrf?: CSRFConfig;
32
/** Environment variable configuration */
33
env?: EnvConfig;
34
/** File and directory paths */
35
files?: FilesConfig;
36
/** CSS inlining threshold */
37
inlineStyleThreshold?: number;
38
/** Path configuration for deployment */
39
paths?: PathsConfig;
40
/** Prerendering configuration */
41
prerender?: PrerenderConfig;
42
/** Service worker configuration */
43
serviceWorker?: ServiceWorkerConfig;
44
/** TypeScript configuration */
45
typescript?: TypeScriptConfig;
46
/** Version management */
47
version?: VersionConfig;
48
}
49
```
50
51
### Adapter Configuration
52
53
Configure deployment adapters for different platforms.
54
55
```typescript { .api }
56
interface Adapter {
57
/** Name of the adapter */
58
name: string;
59
/** Function called after SvelteKit builds the app */
60
adapt: (builder: Builder) => Promise<void> | void;
61
/** Feature support checks */
62
supports?: {
63
read?: (details: { config: any; route: { id: string } }) => boolean;
64
};
65
/** Environment emulation during development */
66
emulate?: () => Promise<Emulator> | Emulator;
67
}
68
```
69
70
**Usage Examples:**
71
72
```javascript
73
// svelte.config.js
74
import adapter from '@sveltejs/adapter-auto';
75
76
export default {
77
kit: {
78
// Auto-detect deployment platform
79
adapter: adapter()
80
}
81
};
82
```
83
84
```javascript
85
// Static site generation
86
import adapter from '@sveltejs/adapter-static';
87
88
export default {
89
kit: {
90
adapter: adapter({
91
pages: 'build',
92
assets: 'build',
93
fallback: '404.html',
94
precompress: false,
95
strict: true
96
})
97
}
98
};
99
```
100
101
```javascript
102
// Node.js deployment
103
import adapter from '@sveltejs/adapter-node';
104
105
export default {
106
kit: {
107
adapter: adapter({
108
out: 'build',
109
precompress: false,
110
envPrefix: 'MY_CUSTOM_'
111
})
112
}
113
};
114
```
115
116
## Configuration Examples
117
118
### Basic Configuration
119
120
```javascript
121
// svelte.config.js
122
import adapter from '@sveltejs/adapter-auto';
123
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
124
125
/** @type {import('@sveltejs/kit').Config} */
126
const config = {
127
// Svelte options
128
extensions: ['.svelte'],
129
preprocess: vitePreprocess(),
130
131
kit: {
132
// Basic SvelteKit options
133
adapter: adapter(),
134
135
// Custom app directory name
136
appDir: '_app',
137
138
// Path aliases
139
alias: {
140
$components: 'src/components',
141
$stores: 'src/stores',
142
$utils: 'src/utils'
143
}
144
}
145
};
146
147
export default config;
148
```
149
150
### Advanced Configuration
151
152
```javascript
153
// svelte.config.js
154
import adapter from '@sveltejs/adapter-node';
155
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
156
157
/** @type {import('@sveltejs/kit').Config} */
158
const config = {
159
extensions: ['.svelte'],
160
preprocess: vitePreprocess(),
161
162
kit: {
163
adapter: adapter({
164
out: 'build',
165
precompress: true
166
}),
167
168
// Path configuration
169
paths: {
170
base: process.env.NODE_ENV === 'production' ? '/my-app' : '',
171
assets: 'https://cdn.example.com',
172
relative: false
173
},
174
175
// Environment variables
176
env: {
177
dir: '.',
178
publicPrefix: 'PUBLIC_',
179
privatePrefix: 'PRIVATE_'
180
},
181
182
// Content Security Policy
183
csp: {
184
mode: 'auto',
185
directives: {
186
'default-src': ['self'],
187
'script-src': ['self', 'unsafe-inline'],
188
'style-src': ['self', 'unsafe-inline'],
189
'img-src': ['self', 'data:', 'https:'],
190
'font-src': ['self'],
191
'connect-src': ['self'],
192
'frame-src': ['none']
193
}
194
},
195
196
// CSRF protection
197
csrf: {
198
checkOrigin: true,
199
trustedOrigins: ['https://trusted-site.com']
200
},
201
202
// Prerendering
203
prerender: {
204
entries: ['*'],
205
crawl: true,
206
concurrency: 2,
207
handleHttpError: 'warn',
208
handleMissingId: 'warn'
209
},
210
211
// Service worker
212
serviceWorker: {
213
register: true,
214
files: (filename) => !/\.DS_Store/.test(filename)
215
},
216
217
// TypeScript
218
typescript: {
219
config: (config) => {
220
config.compilerOptions.strict = true;
221
return config;
222
}
223
},
224
225
// Version management
226
version: {
227
name: process.env.npm_package_version,
228
pollInterval: 30000
229
}
230
}
231
};
232
233
export default config;
234
```
235
236
### Multi-Environment Configuration
237
238
```javascript
239
// svelte.config.js
240
import adapterNode from '@sveltejs/adapter-node';
241
import adapterStatic from '@sveltejs/adapter-static';
242
import adapterVercel from '@sveltejs/adapter-vercel';
243
244
const dev = process.env.NODE_ENV === 'development';
245
const preview = process.env.NODE_ENV === 'preview';
246
247
// Choose adapter based on environment
248
function getAdapter() {
249
if (process.env.VERCEL) {
250
return adapterVercel();
251
}
252
253
if (process.env.BUILD_STATIC) {
254
return adapterStatic({
255
pages: 'dist',
256
assets: 'dist',
257
fallback: '404.html'
258
});
259
}
260
261
return adapterNode({
262
out: 'build'
263
});
264
}
265
266
/** @type {import('@sveltejs/kit').Config} */
267
const config = {
268
kit: {
269
adapter: getAdapter(),
270
271
// Environment-specific paths
272
paths: {
273
base: dev ? '' : process.env.BASE_PATH || '',
274
assets: process.env.ASSETS_URL || ''
275
},
276
277
// Development-only features
278
...(dev && {
279
// Hot reload configuration
280
vite: {
281
server: {
282
hmr: {
283
overlay: true
284
}
285
}
286
}
287
}),
288
289
// Production optimizations
290
...(!dev && {
291
inlineStyleThreshold: 1024,
292
prerender: {
293
entries: ['*'],
294
crawl: true
295
}
296
})
297
}
298
};
299
300
export default config;
301
```
302
303
## Configuration Options
304
305
### Path Configuration
306
307
```javascript
308
export default {
309
kit: {
310
paths: {
311
// Base path for deployment to subdirectory
312
base: '/my-app',
313
314
// CDN or asset server URL
315
assets: 'https://cdn.example.com',
316
317
// Use relative paths in HTML
318
relative: true
319
}
320
}
321
};
322
```
323
324
### File Structure Configuration
325
326
```javascript
327
export default {
328
kit: {
329
files: {
330
// Source directory
331
src: 'src',
332
333
// Static assets
334
assets: 'static',
335
336
// Hook files
337
hooks: {
338
client: 'src/hooks.client',
339
server: 'src/hooks.server',
340
universal: 'src/hooks'
341
},
342
343
// Library directory
344
lib: 'src/lib',
345
346
// Route parameter matchers
347
params: 'src/params',
348
349
// Routes directory
350
routes: 'src/routes',
351
352
// Service worker
353
serviceWorker: 'src/service-worker',
354
355
// HTML templates
356
appTemplate: 'src/app.html',
357
errorTemplate: 'src/error.html'
358
}
359
}
360
};
361
```
362
363
### Security Configuration
364
365
```javascript
366
export default {
367
kit: {
368
// Content Security Policy
369
csp: {
370
mode: 'hash', // or 'nonce' or 'auto'
371
directives: {
372
'default-src': ['self'],
373
'script-src': ['self'],
374
'style-src': ['self', 'unsafe-inline'],
375
'img-src': ['self', 'data:', 'https:'],
376
'font-src': ['self'],
377
'connect-src': ['self', 'https://api.example.com'],
378
'frame-src': ['none'],
379
'object-src': ['none'],
380
'base-uri': ['self']
381
},
382
reportOnly: {
383
'default-src': ['self'],
384
'report-uri': ['/csp-report']
385
}
386
},
387
388
// CSRF protection
389
csrf: {
390
checkOrigin: true,
391
trustedOrigins: [
392
'https://checkout.stripe.com',
393
'https://js.stripe.com'
394
]
395
}
396
}
397
};
398
```
399
400
### Build Configuration
401
402
```javascript
403
export default {
404
kit: {
405
// CSS inlining threshold (characters)
406
inlineStyleThreshold: 1024,
407
408
// Output configuration
409
output: {
410
preloadStrategy: 'modulepreload' // or 'preload-js' or 'preload-mjs'
411
},
412
413
// Module extensions
414
moduleExtensions: ['.js', '.ts'],
415
416
// Output directory
417
outDir: '.svelte-kit'
418
}
419
};
420
```
421
422
### Prerendering Configuration
423
424
```javascript
425
export default {
426
kit: {
427
prerender: {
428
// Which pages to prerender
429
entries: ['*', '/sitemap.xml'],
430
431
// Follow links to find more pages
432
crawl: true,
433
434
// Concurrent prerendering
435
concurrency: 4,
436
437
// Error handling
438
handleHttpError: ({ status, path, referrer, message }) => {
439
if (path === '/admin' && status === 404) {
440
return; // Ignore admin 404s
441
}
442
throw new Error(message);
443
},
444
445
handleMissingId: 'warn',
446
handleEntryGeneratorMismatch: 'warn',
447
448
// Origin for absolute URLs during prerendering
449
origin: 'https://example.com'
450
}
451
}
452
};
453
```
454
455
### TypeScript Configuration
456
457
```javascript
458
export default {
459
kit: {
460
typescript: {
461
config: (config) => {
462
// Modify generated tsconfig.json
463
config.compilerOptions.strict = true;
464
config.compilerOptions.noImplicitReturns = true;
465
config.include.push('../shared/**/*');
466
467
return config;
468
}
469
}
470
}
471
};
472
```
473
474
### Version Management
475
476
```javascript
477
import { execSync } from 'child_process';
478
479
export default {
480
kit: {
481
version: {
482
// Use git commit hash as version
483
name: execSync('git rev-parse HEAD').toString().trim(),
484
485
// Poll for updates every 30 seconds
486
pollInterval: 30000
487
}
488
}
489
};
490
```
491
492
### Service Worker Configuration
493
494
```javascript
495
export default {
496
kit: {
497
serviceWorker: {
498
register: true,
499
500
// Filter which static files to include
501
files: (filename) => {
502
return !/\.DS_Store/.test(filename) &&
503
!filename.includes('admin') &&
504
!filename.endsWith('.map');
505
}
506
}
507
}
508
};
509
```
510
511
## Platform-Specific Configurations
512
513
### Vercel Configuration
514
515
```javascript
516
// svelte.config.js
517
import adapter from '@sveltejs/adapter-vercel';
518
519
export default {
520
kit: {
521
adapter: adapter({
522
runtime: 'edge', // or 'nodejs18.x'
523
regions: ['iad1'],
524
split: true
525
})
526
}
527
};
528
```
529
530
### Netlify Configuration
531
532
```javascript
533
// svelte.config.js
534
import adapter from '@sveltejs/adapter-netlify';
535
536
export default {
537
kit: {
538
adapter: adapter({
539
edge: false,
540
split: false
541
})
542
}
543
};
544
```
545
546
### Cloudflare Pages Configuration
547
548
```javascript
549
// svelte.config.js
550
import adapter from '@sveltejs/adapter-cloudflare';
551
552
export default {
553
kit: {
554
adapter: adapter({
555
routes: {
556
include: ['/*'],
557
exclude: ['/admin/*']
558
}
559
})
560
}
561
};
562
```
563
564
## Best Practices
565
566
1. **Environment-specific configs**: Use environment variables for different deployment targets
567
2. **Security headers**: Configure CSP and CSRF protection appropriately
568
3. **Path configuration**: Set correct base and assets paths for deployment
569
4. **Prerendering**: Configure prerendering for better performance and SEO
570
5. **Type safety**: Use TypeScript configuration for better development experience
571
6. **Asset optimization**: Set appropriate inlining thresholds and compression
572
7. **Service worker**: Configure service worker file filtering for optimal caching
573
8. **Version management**: Use meaningful version identifiers for cache busting
574
9. **Adapter selection**: Choose the right adapter for your deployment platform
575
10. **Development optimization**: Use different configurations for development and production