Spec RegistrySpec Registry

Help your agents use open-source better. Learn more.

Find usage specs for your project’s dependencies

>

npm-svelte

Describes: npmnpm/svelte

Description
A cybernetically enhanced web application framework that compiles to highly optimized JavaScript with reactive state management and component-based architecture.
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/npm-svelte@5.38.0

ssr.md docs/

1
# Server-Side Rendering
2
3
Svelte provides server-side rendering capabilities that allow you to generate HTML on the server for improved performance, SEO, and user experience.
4
5
## Capabilities
6
7
### render
8
9
Renders a Svelte component on the server and returns HTML string with CSS and metadata.
10
11
```typescript { .api }
12
/**
13
* Render a component on the server
14
* @param component - Component to render
15
* @param options - Server rendering options
16
* @returns Rendered HTML with CSS and metadata
17
*/
18
function render<Comp extends Component<any>>(
19
component: Comp,
20
options?: RenderOptions<ComponentProps<Comp>>
21
): RenderOutput;
22
```
23
24
**Usage Examples:**
25
26
```typescript
27
import { render } from "svelte/server";
28
import App from "./App.svelte";
29
30
// Basic server rendering
31
const result = render(App, {
32
props: {
33
title: "My App",
34
initialData: { users: [], posts: [] }
35
}
36
});
37
38
console.log(result.body); // HTML string
39
console.log(result.css?.code); // CSS string (if any)
40
console.log(result.head); // Head elements
41
42
// Express.js integration
43
app.get("*", async (req, res) => {
44
const { body, head, css } = render(App, {
45
props: {
46
url: req.url,
47
user: req.user
48
}
49
});
50
51
const html = `
52
<!DOCTYPE html>
53
<html>
54
<head>
55
<title>My App</title>
56
${head}
57
${css ? `<style>${css.code}</style>` : ""}
58
</head>
59
<body>
60
<div id="app">${body}</div>
61
<script src="/build/bundle.js"></script>
62
</body>
63
</html>
64
`;
65
66
res.send(html);
67
});
68
69
// With context and props
70
const result = render(App, {
71
props: {
72
initialState: serverData
73
},
74
context: new Map([
75
["theme", { mode: "dark" }],
76
["api", { baseUrl: process.env.API_URL }]
77
])
78
});
79
```
80
81
### SvelteKit Integration
82
83
```typescript
84
// In SvelteKit, SSR is handled automatically
85
// src/routes/+page.server.js
86
export async function load({ params, url, cookies }) {
87
const data = await fetchData(params.id);
88
89
return {
90
props: {
91
data,
92
url: url.pathname
93
}
94
};
95
}
96
97
// src/routes/+page.svelte
98
let { data } = $props();
99
100
// This component will be server-rendered with the data
101
```
102
103
### Hydration Considerations
104
105
```typescript
106
// Client-side hydration
107
import { hydrate } from "svelte";
108
import App from "./App.svelte";
109
110
// Hydrate server-rendered content
111
const app = hydrate(App, {
112
target: document.getElementById("app"),
113
props: {
114
// Must match server-side props
115
initialData: window.__INITIAL_DATA__
116
}
117
});
118
119
// Handle hydration mismatches
120
const app = hydrate(App, {
121
target: document.getElementById("app"),
122
props: serverProps,
123
recover: true // Attempt to recover from mismatches
124
});
125
```
126
127
## SSR-Specific Patterns
128
129
### Environment Detection
130
131
```typescript
132
import { browser } from "$app/environment"; // SvelteKit
133
// or
134
import { BROWSER } from "esm-env"; // Universal
135
136
let data = $state([]);
137
138
// Only run on client
139
if (browser || BROWSER) {
140
// Browser-only code
141
data = JSON.parse(localStorage.getItem("data") || "[]");
142
}
143
144
// Server-safe initialization
145
onMount(() => {
146
// This only runs on the client
147
initializeClientOnlyFeatures();
148
});
149
```
150
151
### Conditional Rendering
152
153
```typescript
154
let mounted = $state(false);
155
156
onMount(() => {
157
mounted = true;
158
});
159
160
// Template
161
/*
162
{#if mounted}
163
<ClientOnlyComponent />
164
{:else}
165
<div>Loading...</div>
166
{/if}
167
*/
168
```
169
170
### API Integration
171
172
```typescript
173
// Server-side data loading
174
export async function load({ fetch }) {
175
const response = await fetch("/api/data");
176
const data = await response.json();
177
178
return {
179
props: { data }
180
};
181
}
182
183
// Component receives pre-loaded data
184
let { data } = $props();
185
186
// Client-side updates still work
187
async function refreshData() {
188
const response = await fetch("/api/data");
189
data = await response.json();
190
}
191
```
192
193
## Types
194
195
```typescript { .api }
196
interface RenderOptions<Props extends Record<string, any> = Record<string, any>> {
197
/** Component properties */
198
props?: Props;
199
/** Context map for the component tree */
200
context?: Map<any, any>;
201
}
202
203
interface RenderOutput {
204
/** Rendered HTML body */
205
body: string;
206
/** CSS code (null if no styles) */
207
css: null | {
208
code: string;
209
map: SourceMap;
210
};
211
/** Head elements to insert */
212
head: string;
213
/** Server-side warnings */
214
warnings: Warning[];
215
}
216
217
interface HydrateOptions<Props extends Record<string, any> = Record<string, any>> {
218
/** Target element containing server-rendered content */
219
target: Document | Element | ShadowRoot;
220
/** Component properties (must match server props) */
221
props?: Props;
222
/** Context map accessible via getContext() */
223
context?: Map<any, any>;
224
/** Whether to play transitions during hydration */
225
intro?: boolean;
226
/** Attempt to recover from hydration mismatches */
227
recover?: boolean;
228
}
229
```
230
231
## Best Practices
232
233
### Data Serialization
234
235
```typescript
236
// Serialize complex data safely
237
function serializeData(data) {
238
return JSON.stringify(data, (key, value) => {
239
if (value instanceof Date) {
240
return { __type: "Date", value: value.toISOString() };
241
}
242
return value;
243
});
244
}
245
246
// Deserialize on client
247
function deserializeData(serialized) {
248
return JSON.parse(serialized, (key, value) => {
249
if (value && value.__type === "Date") {
250
return new Date(value.value);
251
}
252
return value;
253
});
254
}
255
```
256
257
### Head Management
258
259
```typescript
260
// In SvelteKit
261
import { page } from "$app/stores";
262
263
// Dynamic head content
264
$effect(() => {
265
document.title = `${$page.data.title} - My App`;
266
267
// Meta tags
268
let metaDescription = document.querySelector('meta[name="description"]');
269
if (metaDescription) {
270
metaDescription.content = $page.data.description;
271
}
272
});
273
```
274
275
### Progressive Enhancement
276
277
```typescript
278
let enhanced = $state(false);
279
280
onMount(() => {
281
enhanced = true;
282
});
283
284
// Template with progressive enhancement
285
/*
286
<form method="POST" action="/api/submit">
287
<input name="email" type="email" required />
288
289
{#if enhanced}
290
<button type="button" on:click={handleClientSubmit}>
291
Submit (Enhanced)
292
</button>
293
{:else}
294
<button type="submit">
295
Submit
296
</button>
297
{/if}
298
</form>
299
*/
300
301
async function handleClientSubmit(event) {
302
event.preventDefault();
303
// Enhanced client-side submission
304
const formData = new FormData(event.target.form);
305
const response = await fetch("/api/submit", {
306
method: "POST",
307
body: formData
308
});
309
// Handle response...
310
}
311
```
312
313
## Common Patterns
314
315
1. **Data loading**: Use server-side load functions to pre-populate component props
316
2. **Environment detection**: Check `browser` or `BROWSER` flags for client-only code
317
3. **Graceful degradation**: Ensure forms and navigation work without JavaScript
318
4. **Hydration matching**: Server and client props must match exactly
319
5. **Progressive enhancement**: Add client-side features while maintaining server functionality
320
6. **Head management**: Use `svelte:head` or meta frameworks for SEO tags
321
7. **Error boundaries**: Handle both server and client errors appropriately