or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

build-system.mdconfiguration.mdcss-processing.mddev-server.mdhmr.mdindex.mdmodule-resolution.mdplugin-system.mdssr.mdutilities.md

ssr.mddocs/

0

# Server-Side Rendering

1

2

Vite provides comprehensive server-side rendering capabilities with module runner, environment management, SSR-specific optimizations, and seamless integration between client and server environments.

3

4

## Capabilities

5

6

### Module Runner

7

8

Create and manage module runners for executing code in SSR environments.

9

10

```typescript { .api }

11

/**

12

* Create server-side module runner

13

* @param server - Vite dev server instance

14

* @param options - Module runner options

15

* @returns Promise resolving to ModuleRunner instance

16

*/

17

function createServerModuleRunner(

18

server: ViteDevServer,

19

options?: ServerModuleRunnerOptions

20

): Promise<ModuleRunner>;

21

22

interface ModuleRunner {

23

/** Import and execute module */

24

import<T = any>(url: string): Promise<T>;

25

/** Destroy runner and cleanup */

26

destroy(): Promise<void>;

27

/** Clear module cache */

28

clearCache(): void;

29

/** Module cache */

30

moduleCache: EvaluatedModules;

31

/** HMR client */

32

hmrClient?: HMRClient;

33

}

34

```

35

36

**Usage Examples:**

37

38

```typescript

39

import { createServer, createServerModuleRunner } from "vite";

40

41

// Create server and module runner

42

const server = await createServer({

43

server: { middlewareMode: true }

44

});

45

46

const runner = await createServerModuleRunner(server, {

47

hmr: {

48

logger: console

49

}

50

});

51

52

// Import and execute SSR module

53

const { render } = await runner.import('./src/entry-server.js');

54

const html = await render({ url: '/about' });

55

56

// Cleanup

57

await runner.destroy();

58

await server.close();

59

```

60

61

### Module Runner Transport

62

63

Create transport mechanisms for module runner communication.

64

65

```typescript { .api }

66

/**

67

* Create server module runner transport

68

* @param options - Transport options

69

* @returns Module runner transport handlers

70

*/

71

function createServerModuleRunnerTransport(

72

options?: {

73

runner?: ModuleRunner;

74

transport?: ModuleRunnerTransport;

75

}

76

): ModuleRunnerTransportHandlers;

77

78

interface ModuleRunnerTransport {

79

/** Connect to transport */

80

connect(): void | Promise<void>;

81

/** Disconnect from transport */

82

disconnect(): void | Promise<void>;

83

/** Send message */

84

send(data: any): void | Promise<void>;

85

/** Handle incoming messages */

86

on(event: string, handler: Function): void;

87

}

88

89

interface ModuleRunnerTransportHandlers {

90

/** Fetch module handler */

91

fetchModule: (id: string, importer?: string) => Promise<FetchResult>;

92

/** Transform handler */

93

transform: (id: string, code: string) => Promise<{ code: string; map?: any }>;

94

}

95

```

96

97

### Fetch Module

98

99

Fetch and process modules for SSR execution.

100

101

```typescript { .api }

102

/**

103

* Fetch module for SSR

104

* @param server - Vite dev server

105

* @param url - Module URL to fetch

106

* @param importer - Importing module

107

* @param options - Fetch options

108

* @returns Promise resolving to fetch result

109

*/

110

function fetchModule(

111

server: ViteDevServer,

112

url: string,

113

importer?: string,

114

options?: FetchModuleOptions

115

): Promise<FetchResult>;

116

117

interface FetchModuleOptions {

118

/** SSR mode */

119

ssr?: boolean;

120

/** Transform options */

121

transformOptions?: TransformOptions;

122

}

123

124

interface FetchResult {

125

/** Externalized module URL */

126

externalize?: string;

127

/** Module code */

128

code?: string;

129

/** Source map */

130

map?: SourceMap;

131

}

132

```

133

134

### Runner Import

135

136

Import modules in runner context with proper error handling.

137

138

```typescript { .api }

139

/**

140

* Import module in runner context

141

* @param runner - Module runner instance

142

* @param id - Module ID to import

143

* @returns Promise resolving to module exports

144

*/

145

function runnerImport<T = any>(runner: ModuleRunner, id: string): Promise<T>;

146

```

147

148

### SSR Transform

149

150

Transform modules for SSR execution with proper module format handling.

151

152

```typescript { .api }

153

/**

154

* Transform modules for SSR (alias for ssrTransform)

155

* @param code - Source code

156

* @param inMap - Input source map

157

* @param url - Module URL

158

* @param originalCode - Original untransformed code

159

* @param options - Transform options

160

* @returns Promise resolving to transform result

161

*/

162

function moduleRunnerTransform(

163

code: string,

164

inMap: SourceMap | null,

165

url: string,

166

originalCode?: string,

167

options?: ModuleRunnerTransformOptions

168

): Promise<TransformResult>;

169

170

interface ModuleRunnerTransformOptions {

171

/** SSR mode */

172

ssr?: boolean;

173

/** Environment name */

174

environment?: string;

175

}

176

```

177

178

## SSR Configuration

179

180

### SSR Options

181

182

Configure server-side rendering behavior and optimizations.

183

184

```typescript { .api }

185

interface SSROptions {

186

/** External packages (not bundled) */

187

external?: string[];

188

/** Force bundling (opposite of external) */

189

noExternal?: string[] | true;

190

/** SSR target environment */

191

target?: SSRTarget;

192

/** Resolution configuration */

193

resolve?: {

194

conditions?: string[];

195

externalConditions?: string[];

196

};

197

/** Dependency optimization for SSR */

198

optimizeDeps?: SsrDepOptimizationConfig;

199

}

200

201

interface ResolvedSSROptions extends SSROptions {

202

external: string[];

203

noExternal: string[] | true;

204

target: SSRTarget;

205

resolve: {

206

conditions: string[];

207

externalConditions: string[];

208

};

209

optimizeDeps: SsrDepOptimizationConfig;

210

}

211

212

type SSRTarget = 'node' | 'webworker';

213

```

214

215

**Usage Examples:**

216

217

```typescript

218

export default defineConfig({

219

ssr: {

220

external: ['some-large-lib'],

221

noExternal: ['@my-org/shared-components'],

222

target: 'node',

223

resolve: {

224

conditions: ['node', 'import', 'module', 'default'],

225

externalConditions: ['node']

226

}

227

}

228

});

229

```

230

231

### SSR Dependency Optimization

232

233

Configure dependency optimization specifically for SSR builds.

234

235

```typescript { .api }

236

interface SsrDepOptimizationConfig {

237

/** Dependencies to pre-bundle */

238

include?: string[];

239

/** Dependencies to exclude from pre-bundling */

240

exclude?: string[];

241

/** Additional esbuild options */

242

esbuildOptions?: any;

243

}

244

```

245

246

## Module Runner Options

247

248

### Runner Configuration

249

250

Configure module runner behavior and environment.

251

252

```typescript { .api }

253

interface ModuleRunnerOptions {

254

/** Root directory */

255

root?: string;

256

/** Fetch function for modules */

257

fetch: FetchFunction;

258

/** Source map support */

259

sourcemapInterceptor?: 'prepareStackTrace' | 'node' | InterceptorOptions | false;

260

/** Module evaluator */

261

evaluator?: ModuleEvaluator;

262

/** HMR configuration */

263

hmr?: ModuleRunnerHmr;

264

/** Environment name */

265

environment?: string;

266

}

267

268

interface ServerModuleRunnerOptions extends Omit<ModuleRunnerOptions, 'fetch'> {

269

/** Fetch function override */

270

fetch?: FetchFunction;

271

/** Transport configuration */

272

transport?: ModuleRunnerTransport;

273

}

274

275

/**

276

* Function to fetch modules

277

*/

278

type FetchFunction = (

279

id: string,

280

importer?: string,

281

options?: FetchFunctionOptions

282

) => Promise<FetchResult>;

283

284

interface FetchFunctionOptions {

285

/** Whether this is an SSR request */

286

ssr?: boolean;

287

}

288

```

289

290

### Module Evaluator

291

292

Configure how modules are evaluated in the runner environment.

293

294

```typescript { .api }

295

interface ModuleEvaluator {

296

/** Evaluate module code */

297

runInlinedModule(

298

context: ModuleRunnerContext,

299

code: string,

300

id: string

301

): Promise<any>;

302

/** Run external module */

303

runExternalModule(filepath: string): Promise<any>;

304

}

305

306

interface ModuleRunnerContext {

307

/** Module runner instance */

308

runner: ModuleRunner;

309

/** Module filename */

310

filename: string;

311

/** Module URL */

312

url: string;

313

}

314

315

class ESModulesEvaluator implements ModuleEvaluator {

316

runInlinedModule(context: ModuleRunnerContext, code: string, id: string): Promise<any>;

317

runExternalModule(filepath: string): Promise<any>;

318

}

319

```

320

321

### HMR for Module Runner

322

323

Configure Hot Module Replacement for module runner environments.

324

325

```typescript { .api }

326

interface ModuleRunnerHmr {

327

/** HMR logger */

328

logger?: HMRLogger;

329

/** Connection configuration */

330

connection?: 'ws' | ModuleRunnerHMRConnection;

331

}

332

333

interface ModuleRunnerHMRConnection {

334

/** Create connection */

335

connect(): void | Promise<void>;

336

/** Disconnect */

337

disconnect(): void | Promise<void>;

338

/** Send data */

339

send(data: any): void | Promise<void>;

340

/** Handle incoming data */

341

on(event: string, handler: (data: any) => void): void;

342

}

343

344

interface HMRLogger {

345

error(msg: string | Error): void;

346

debug(...msg: any[]): void;

347

}

348

```

349

350

## Advanced SSR Patterns

351

352

### Import Meta

353

354

Create appropriate import.meta objects for different environments.

355

356

```typescript { .api }

357

/**

358

* Create default import.meta object

359

* @param url - Module URL

360

* @param context - Runner context

361

* @returns import.meta object

362

*/

363

function createDefaultImportMeta(url: string, context?: ModuleRunnerContext): ModuleRunnerImportMeta;

364

365

/**

366

* Create Node.js-specific import.meta object

367

* @param url - Module URL

368

* @param context - Runner context

369

* @returns import.meta object with Node.js features

370

*/

371

function createNodeImportMeta(url: string, context?: ModuleRunnerContext): ModuleRunnerImportMeta;

372

373

interface ModuleRunnerImportMeta {

374

url: string;

375

env: Record<string, any>;

376

hot?: {

377

accept(): void;

378

decline(): void;

379

dispose(cb: () => void): void;

380

invalidate(): void;

381

};

382

glob?: ImportGlobFunction;

383

}

384

```

385

386

### Evaluated Modules

387

388

Manage and track evaluated modules in the runner.

389

390

```typescript { .api }

391

class EvaluatedModules {

392

/** Normalize module ID */

393

static normalizeModuleId(id: string): string;

394

/** Get evaluated module */

395

get(id: string): EvaluatedModuleNode | undefined;

396

/** Set evaluated module */

397

set(id: string, mod: EvaluatedModuleNode): void;

398

/** Delete module */

399

delete(id: string): boolean;

400

/** Clear all modules */

401

clear(): void;

402

/** Invalidate module */

403

invalidate(id: string): void;

404

}

405

406

interface EvaluatedModuleNode {

407

/** Module exports */

408

exports: any;

409

/** Module meta */

410

meta: SSRImportMetadata;

411

/** Evaluation promise */

412

promise?: Promise<any>;

413

/** Error during evaluation */

414

error?: Error;

415

}

416

417

interface SSRImportMetadata {

418

/** Module URL */

419

url: string;

420

/** Module timestamp */

421

timestamp: number;

422

/** Hot context */

423

hot?: {

424

accept(): void;

425

decline(): void;

426

dispose(cb: () => void): void;

427

invalidate(): void;

428

};

429

}

430

```