or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

adapter-configuration.mdindex.mdplatform-integration.md

platform-integration.mddocs/

0

# Platform Integration

1

2

Cloudflare-specific platform context and runtime environment integration for SvelteKit applications running on Cloudflare Workers and Pages.

3

4

## Capabilities

5

6

### Platform Context

7

8

Global platform interface providing access to Cloudflare runtime environment within SvelteKit applications.

9

10

```typescript { .api }

11

import {

12

CacheStorage,

13

IncomingRequestCfProperties,

14

ExecutionContext

15

} from '@cloudflare/workers-types';

16

17

declare global {

18

namespace App {

19

interface Platform {

20

/**

21

* Environment variables and bindings from Wrangler configuration

22

* Includes KV stores, Durable Objects, R2 buckets, etc.

23

*/

24

env: unknown;

25

26

/**

27

* Cloudflare execution context for request handling

28

* Used for waitUntil() and passThroughOnException()

29

*/

30

ctx: ExecutionContext;

31

32

/**

33

* @deprecated Use ctx instead

34

* Legacy alias for execution context

35

*/

36

context: ExecutionContext;

37

38

/**

39

* Cloudflare cache storage interface

40

* Provides access to Cloudflare's edge caching

41

*/

42

caches: CacheStorage;

43

44

/**

45

* Cloudflare-specific request properties

46

* Includes country, IP geolocation, bot detection, etc.

47

*/

48

cf?: IncomingRequestCfProperties;

49

}

50

}

51

}

52

```

53

54

**Usage in SvelteKit Routes:**

55

56

```typescript

57

// src/routes/api/data/+server.ts

58

import type { RequestHandler } from './$types';

59

60

export const GET: RequestHandler = async ({ platform }) => {

61

// Access environment variables/bindings

62

const db = platform?.env?.DB; // KV or D1 database

63

const bucket = platform?.env?.MY_BUCKET; // R2 storage

64

65

// Use execution context

66

platform?.ctx.waitUntil(

67

fetch('https://api.example.com/webhook', {

68

method: 'POST',

69

body: JSON.stringify({ event: 'processed' })

70

})

71

);

72

73

// Access Cloudflare request properties

74

const country = platform?.cf?.country;

75

const isBot = platform?.cf?.botManagement?.score;

76

77

return new Response(JSON.stringify({

78

country,

79

isBot: isBot < 30

80

}));

81

};

82

```

83

84

### Environment Access

85

86

Access to Cloudflare environment variables and bindings configured in your Wrangler configuration.

87

88

```typescript { .api }

89

import {

90

KVNamespace,

91

D1Database,

92

R2Bucket,

93

DurableObjectNamespace

94

} from '@cloudflare/workers-types';

95

96

// Environment bindings are accessed via platform.env

97

interface CloudflareEnv {

98

// KV Namespace

99

MY_KV?: KVNamespace;

100

101

// D1 Database

102

DB?: D1Database;

103

104

// R2 Storage

105

MY_BUCKET?: R2Bucket;

106

107

// Durable Objects

108

MY_DURABLE_OBJECT?: DurableObjectNamespace;

109

110

// Environment Variables

111

API_KEY?: string;

112

SECRET?: string;

113

114

// And any other bindings from wrangler.toml

115

[key: string]: unknown;

116

}

117

```

118

119

**Usage Examples:**

120

121

```typescript

122

// Accessing KV storage

123

const value = await platform.env.MY_KV.get('cache-key');

124

await platform.env.MY_KV.put('cache-key', 'value', { expirationTtl: 3600 });

125

126

// Using D1 database

127

const result = await platform.env.DB

128

.prepare('SELECT * FROM users WHERE id = ?')

129

.bind(userId)

130

.first();

131

132

// R2 storage operations

133

const file = await platform.env.MY_BUCKET.get('uploads/image.jpg');

134

await platform.env.MY_BUCKET.put('uploads/new-file.txt', 'content');

135

```

136

137

### Execution Context

138

139

Control over request lifecycle and background task scheduling.

140

141

```typescript { .api }

142

interface ExecutionContext {

143

/**

144

* Extend the lifetime of the request handler

145

* Allows background tasks to complete

146

*/

147

waitUntil(promise: Promise<any>): void;

148

149

/**

150

* Prevent the runtime from cancelling the request

151

* when an uncaught exception occurs

152

*/

153

passThroughOnException(): void;

154

}

155

```

156

157

**Usage Examples:**

158

159

```typescript

160

// Background logging without blocking response

161

platform.ctx.waitUntil(

162

fetch('https://analytics.example.com/track', {

163

method: 'POST',

164

body: JSON.stringify({

165

event: 'page_view',

166

timestamp: Date.now()

167

})

168

})

169

);

170

171

// Graceful error handling

172

try {

173

// Request processing logic

174

const data = await processRequest();

175

return new Response(JSON.stringify(data));

176

} catch (error) {

177

platform.ctx.passThroughOnException();

178

throw error; // Will be handled by Cloudflare's error page

179

}

180

```

181

182

### Cache Integration

183

184

Access to Cloudflare's edge caching system for optimized performance.

185

186

```typescript { .api }

187

import { CacheStorage, Cache, CacheQueryOptions } from '@cloudflare/workers-types';

188

189

interface CacheStorage {

190

/**

191

* Default cache for the current zone

192

*/

193

default: Cache;

194

195

/**

196

* Open a named cache

197

*/

198

open(cacheName: string): Promise<Cache>;

199

}

200

201

interface Cache {

202

match(request: RequestInfo, options?: CacheQueryOptions): Promise<Response | undefined>;

203

put(request: RequestInfo, response: Response): Promise<void>;

204

delete(request: RequestInfo, options?: CacheQueryOptions): Promise<boolean>;

205

}

206

```

207

208

**Usage Examples:**

209

210

```typescript

211

// Cache API responses

212

const cacheKey = new URL(request.url);

213

const cachedResponse = await platform.caches.default.match(cacheKey);

214

215

if (cachedResponse) {

216

return cachedResponse;

217

}

218

219

const apiResponse = await fetch('https://api.example.com/data');

220

const responseClone = apiResponse.clone();

221

222

// Cache for 1 hour

223

responseClone.headers.set('Cache-Control', 'public, max-age=3600');

224

await platform.caches.default.put(cacheKey, responseClone);

225

226

return apiResponse;

227

```

228

229

### Request Properties

230

231

Access to Cloudflare-specific request metadata and geolocation information.

232

233

```typescript { .api }

234

interface IncomingRequestCfProperties {

235

/**

236

* Two-letter country code (ISO 3166-1 alpha-2)

237

*/

238

country?: string;

239

240

/**

241

* Cloudflare data center processing the request

242

*/

243

colo?: string;

244

245

/**

246

* Bot management information

247

*/

248

botManagement?: {

249

score: number; // 1-99, lower = more likely to be bot

250

staticResource: boolean;

251

verifiedBot: boolean;

252

};

253

254

/**

255

* Request geolocation data

256

*/

257

city?: string;

258

region?: string;

259

regionCode?: string;

260

postalCode?: string;

261

timezone?: string;

262

latitude?: string;

263

longitude?: string;

264

265

/**

266

* Additional metadata

267

*/

268

asn?: number;

269

asOrganization?: string;

270

tlsVersion?: string;

271

tlsCipher?: string;

272

}

273

```

274

275

**Usage Examples:**

276

277

```typescript

278

// Geolocation-based responses

279

const userCountry = platform.cf?.country;

280

const userCity = platform.cf?.city;

281

282

if (userCountry === 'US') {

283

// Serve US-specific content

284

} else if (userCountry === 'GB') {

285

// Serve UK-specific content

286

}

287

288

// Bot detection

289

const botScore = platform.cf?.botManagement?.score || 100;

290

if (botScore < 30) {

291

return new Response('Access denied', { status: 403 });

292

}

293

294

// Regional content delivery

295

const timezone = platform.cf?.timezone || 'UTC';

296

const localizedTime = new Date().toLocaleString('en-US', {

297

timeZone: timezone

298

});

299

```