0
# SvelteKit
1
2
SvelteKit is a comprehensive web application framework built on top of Svelte that provides a streamlined development experience for building modern web applications. It offers file-based routing, server-side rendering (SSR), static site generation (SSG), and client-side rendering capabilities with automatic code splitting and optimized builds. SvelteKit includes built-in TypeScript support, extensive adapter ecosystem for various deployment platforms, and integrates seamlessly with Vite for fast development and building.
3
4
## Package Information
5
6
- **Package Name**: @sveltejs/kit
7
- **Package Type**: npm
8
- **Language**: JavaScript/TypeScript
9
- **Installation**: `npm install @sveltejs/kit`
10
11
## Core Imports
12
13
```typescript
14
import { error, redirect, json, fail } from "@sveltejs/kit";
15
```
16
17
For Node.js server integration:
18
19
```typescript
20
import { getRequest, setResponse } from "@sveltejs/kit/node";
21
```
22
23
For Vite configuration:
24
25
```typescript
26
import { sveltekit } from "@sveltejs/kit/vite";
27
```
28
29
## Basic Usage
30
31
```typescript
32
// Basic page load function (+page.server.js)
33
import { error, json } from "@sveltejs/kit";
34
35
export async function load({ params, fetch }) {
36
const response = await fetch(`/api/posts/${params.id}`);
37
38
if (!response.ok) {
39
throw error(404, 'Post not found');
40
}
41
42
return {
43
post: await response.json()
44
};
45
}
46
47
// API endpoint (+server.js)
48
export async function GET({ url, params }) {
49
const data = { message: 'Hello World' };
50
return json(data);
51
}
52
53
// Form action (+page.server.js)
54
export const actions = {
55
default: async ({ request }) => {
56
const data = await request.formData();
57
const email = data.get('email');
58
59
if (!email) {
60
return fail(400, { message: 'Email required' });
61
}
62
63
// Process form...
64
return { success: true };
65
}
66
};
67
```
68
69
## Architecture
70
71
SvelteKit is built around several key concepts:
72
73
- **File-based routing**: Routes are defined by the filesystem structure in `src/routes`
74
- **Universal load functions**: Share data loading logic between server and client
75
- **Form actions**: Progressive enhancement for form submissions
76
- **Adapters**: Deploy to different platforms (Vercel, Netlify, Node.js, static, etc.)
77
- **Hooks**: Customize request/response handling at the application level
78
- **App shell**: Minimal HTML shell for client-side navigation
79
80
## Capabilities
81
82
### Error Handling
83
84
Create HTTP errors and redirects that integrate with SvelteKit's error handling system.
85
86
```typescript { .api }
87
function error(status: number, body: App.Error | string): never;
88
function isHttpError(e: unknown, status?: number): boolean;
89
function redirect(status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308, location: string | URL): never;
90
function isRedirect(e: unknown): boolean;
91
```
92
93
[Error Handling](./error-handling.md)
94
95
### Response Creation
96
97
Create properly formatted HTTP responses for APIs and endpoints.
98
99
```typescript { .api }
100
function json(data: any, init?: ResponseInit): Response;
101
function text(body: string, init?: ResponseInit): Response;
102
```
103
104
[Response Creation](./response-creation.md)
105
106
### Form Actions
107
108
Handle form submissions with progressive enhancement and validation.
109
110
```typescript { .api }
111
function fail(status: number, data?: any): ActionFailure;
112
function isActionFailure(e: unknown): boolean;
113
114
interface ActionFailure<T = undefined> {
115
status: number;
116
data: T;
117
}
118
```
119
120
[Form Actions](./form-actions.md)
121
122
### Load Functions
123
124
Load data for pages and layouts on both server and client.
125
126
```typescript { .api }
127
interface LoadEvent<Params = Record<string, string>, Data = Record<string, any>, ParentData = Record<string, any>> {
128
params: Params;
129
url: URL;
130
route: { id: string };
131
fetch: typeof fetch;
132
data: Data;
133
parent: () => Promise<ParentData>;
134
depends: (...deps: string[]) => void;
135
setHeaders: (headers: Record<string, string>) => void;
136
untrack: <T>(fn: () => T) => T;
137
}
138
139
interface ServerLoadEvent<Params = Record<string, string>, ParentData = Record<string, any>> extends RequestEvent<Params> {
140
parent: () => Promise<ParentData>;
141
depends: (...deps: string[]) => void;
142
}
143
```
144
145
[Load Functions](./load-functions.md)
146
147
### Request Handling
148
149
Handle incoming HTTP requests with full access to request data and server context.
150
151
```typescript { .api }
152
interface RequestEvent<Params = Record<string, string>> {
153
cookies: Cookies;
154
fetch: typeof fetch;
155
getClientAddress: () => string;
156
locals: App.Locals;
157
params: Params;
158
platform: Readonly<App.Platform> | undefined;
159
request: Request;
160
route: { id: string };
161
setHeaders: (headers: Record<string, string>) => void;
162
url: URL;
163
isDataRequest: boolean;
164
isSubRequest: boolean;
165
}
166
```
167
168
[Request Handling](./request-handling.md)
169
170
### Node.js Integration
171
172
Convert between Node.js HTTP objects and Web API Request/Response objects.
173
174
```typescript { .api }
175
function getRequest(options: {
176
request: import('http').IncomingMessage;
177
base: string;
178
bodySizeLimit?: number;
179
}): Promise<Request>;
180
181
function setResponse(res: import('http').ServerResponse, response: Response): Promise<void>;
182
183
function createReadableStream(file: string): ReadableStream;
184
```
185
186
[Node.js Integration](./nodejs-integration.md)
187
188
### Hooks
189
190
Customize request/response handling and compose multiple hooks.
191
192
```typescript { .api }
193
type Handle = (input: {
194
event: RequestEvent;
195
resolve: (event: RequestEvent, opts?: ResolveOptions) => Promise<Response>;
196
}) => Promise<Response>;
197
198
function sequence(...handlers: Handle[]): Handle;
199
```
200
201
[Hooks](./hooks.md)
202
203
### Vite Integration
204
205
Configure SvelteKit with Vite for development and building.
206
207
```typescript { .api }
208
function sveltekit(): Promise<import('vite').Plugin[]>;
209
```
210
211
[Vite Integration](./vite-integration.md)
212
213
### App State and Navigation
214
215
Access page state, handle navigation, and manage client-side routing.
216
217
```typescript { .api }
218
interface Page<Params = Record<string, string>> {
219
url: URL;
220
params: Params;
221
route: { id: string };
222
status: number;
223
error: App.Error | null;
224
data: App.PageData;
225
state: App.PageState;
226
form: any;
227
}
228
229
interface Navigation {
230
from: NavigationTarget | null;
231
to: NavigationTarget | null;
232
type: 'form' | 'leave' | 'link' | 'goto' | 'popstate';
233
willUnload: boolean;
234
delta?: number;
235
complete: Promise<void>;
236
}
237
```
238
239
[App State and Navigation](./app-state-navigation.md)
240
241
### Configuration
242
243
Configure SvelteKit behavior, adapters, and build options.
244
245
```typescript { .api }
246
interface Config {
247
kit?: KitConfig;
248
}
249
250
interface KitConfig {
251
adapter?: Adapter;
252
alias?: Record<string, string>;
253
appDir?: string;
254
csp?: CSPConfig;
255
csrf?: CSRFConfig;
256
env?: EnvConfig;
257
files?: FilesConfig;
258
inlineStyleThreshold?: number;
259
paths?: PathsConfig;
260
prerender?: PrerenderConfig;
261
serviceWorker?: ServiceWorkerConfig;
262
typescript?: TypeScriptConfig;
263
version?: VersionConfig;
264
}
265
```
266
267
[Configuration](./configuration.md)
268
269
### App Server
270
271
Server-side utilities and remote functions for accessing request context and executing distributed operations.
272
273
```typescript { .api }
274
function getRequestEvent(): RequestEvent;
275
function read(asset: string): ReadableStream;
276
function query(id: string, ...args: any[]): Promise<any>;
277
function prerender(id: string, ...args: any[]): Promise<any>;
278
function command(id: string, ...args: any[]): Promise<any>;
279
function form(id: string, formData: FormData): Promise<any>;
280
```
281
282
[App Server](./app-server.md)
283
284
### App State
285
286
Reactive state management using Svelte 5 runes for page data, navigation state, and update notifications.
287
288
```typescript { .api }
289
const page: {
290
url: URL;
291
params: Record<string, string>;
292
route: { id: string };
293
status: number;
294
error: App.Error | null;
295
data: App.PageData;
296
state: App.PageState;
297
form: any;
298
};
299
300
const navigating: Navigation | null;
301
302
const updated: {
303
current: boolean;
304
check: () => Promise<boolean>;
305
};
306
```
307
308
[App State](./app-state.md)
309
310
### Service Worker
311
312
Service Worker utilities for caching strategies and offline functionality.
313
314
```typescript { .api }
315
const build: string[];
316
const files: string[];
317
const prerendered: string[];
318
const version: string;
319
```
320
321
[Service Worker](./service-worker.md)
322
323
### URL Normalization
324
325
Normalize URLs by stripping SvelteKit-internal suffixes and trailing slashes, with utilities to restore them.
326
327
```typescript { .api }
328
function normalizeUrl(url: URL | string): {
329
url: URL;
330
wasNormalized: boolean;
331
denormalize: (url?: string | URL) => URL;
332
};
333
```
334
335
### CLI Commands
336
337
SvelteKit provides command-line utilities for development and build processes.
338
339
```bash { .api }
340
# Synchronize generated type definitions
341
svelte-kit sync
342
```
343
344
## Global Types
345
346
```typescript { .api }
347
declare namespace App {
348
interface Error {
349
message: string;
350
}
351
352
interface Locals {}
353
354
interface PageData {}
355
356
interface PageState {}
357
358
interface Platform {}
359
}
360
```