or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

content-integration.mddata-types-configuration.mdindex.mdmodule-configuration.mdserver-composables.mdxml-html-utilities.md

server-composables.mddocs/

0

# Server Composables

1

2

Server-side composables and utilities for runtime sitemap generation, URL processing, and event handler creation within the Nuxt server context.

3

4

```typescript { .api }

5

// Available only in Nuxt server context

6

import { asSitemapUrl, defineSitemapEventHandler } from '#sitemap/server/composables';

7

```

8

9

## Capabilities

10

11

### URL Type Conversion

12

13

Type-safe converter for sitemap URL inputs in server context.

14

15

```typescript { .api }

16

/**

17

* Type-safe converter for sitemap URL inputs

18

* Ensures proper typing for sitemap URL objects or strings

19

* @param url - URL input as SitemapUrlInput or generic object

20

* @returns Properly typed SitemapUrlInput

21

*/

22

function asSitemapUrl(url: SitemapUrlInput | Record<string, any>): SitemapUrlInput;

23

```

24

25

### Event Handler Definition

26

27

Typed wrapper for H3 event handlers specifically for sitemap URL sources.

28

29

```typescript { .api }

30

/**

31

* Typed event handler definition for sitemap URL sources

32

* Provides type safety for server endpoints that return sitemap URLs

33

*/

34

const defineSitemapEventHandler: typeof defineEventHandler<

35

EventHandlerRequest,

36

EventHandlerResponse<SitemapUrlInput[]>

37

>;

38

```

39

40

### Runtime Configuration Access

41

42

Access to runtime sitemap configuration within server context.

43

44

```typescript { .api }

45

/**

46

* Get runtime sitemap configuration with normalized filters

47

* @param e - Optional H3 event context

48

* @returns Frozen runtime configuration object

49

*/

50

function useSitemapRuntimeConfig(e?: H3Event): ModuleRuntimeConfig;

51

52

interface ModuleRuntimeConfig {

53

version: string;

54

isNuxtContentDocumentDriven: boolean;

55

sitemaps: Record<string, SitemapDefinition>;

56

autoI18n?: AutoI18nConfig;

57

isMultiSitemap: boolean;

58

isI18nMapped: boolean;

59

sitemapsPathPrefix: string | false;

60

cacheMaxAgeSeconds: number | false;

61

sitemapName: string;

62

excludeAppSources: true | AppSourceContext[];

63

sortEntries: boolean;

64

defaultSitemapsChunkSize: number | false;

65

xslColumns?: XslColumn[];

66

xslTips: boolean;

67

debug: boolean;

68

discoverImages: boolean;

69

discoverVideos: boolean;

70

autoLastmod: boolean;

71

xsl: string | false;

72

credits: boolean;

73

minify: boolean;

74

}

75

```

76

77

### XML Escaping Utility

78

79

XML-safe string escaping for content inserted into XML/XSL.

80

81

```typescript { .api }

82

/**

83

* XML escape function for content inserted into XML/XSL

84

* Escapes special XML characters to prevent malformed XML

85

* @param str - String to escape

86

* @returns XML-safe escaped string

87

*/

88

function xmlEscape(str: string): string;

89

```

90

91

### Route Rule Matching

92

93

Utilities for working with Nitro route rules in server context.

94

95

```typescript { .api }

96

/**

97

* Remove query parameters from path

98

* @param path - URL path with potential query parameters

99

* @returns Path without query string

100

*/

101

function withoutQuery(path: string): string;

102

103

/**

104

* Create a matcher function for Nitro route rules

105

* @returns Function that matches paths against route rules

106

*/

107

function createNitroRouteRuleMatcher(): (pathOrUrl: string) => NitroRouteRules;

108

```

109

110

### Pure Utility Functions

111

112

Framework-agnostic utilities available in server context.

113

114

```typescript { .api }

115

/**

116

* Pre-configured logger instance for sitemap operations

117

*/

118

const logger: ConsolaInstance;

119

120

/**

121

* Merge array items by a specific key, combining duplicate entries

122

* @param arr - Array of objects to merge

123

* @param key - Key to merge on

124

* @returns Array with merged items

125

*/

126

function mergeOnKey<T, K extends keyof T>(arr: T[], key: K): T[];

127

128

/**

129

* Split path for i18n locale extraction

130

* @param path - URL path

131

* @param locales - Array of valid locale codes

132

* @returns Tuple of [locale, path] or [null, path]

133

*/

134

function splitForLocales(path: string, locales: string[]): [string | null, string];

135

136

/**

137

* Normalize runtime filter inputs for pattern matching

138

* @param filters - Array of filter inputs

139

* @returns Normalized filters for runtime use

140

*/

141

function normalizeRuntimeFilters(filters: FilterInput[]): NormalizedFilter[];

142

```

143

144

**Usage Examples:**

145

146

```typescript

147

// server/api/_sitemap-urls.ts - Dynamic sitemap source

148

import { defineSitemapEventHandler, asSitemapUrl } from '#sitemap/server/composables';

149

150

export default defineSitemapEventHandler(async (event) => {

151

// Fetch dynamic data

152

const products = await $fetch('/api/products');

153

154

// Convert to sitemap URLs

155

return products.map(product => asSitemapUrl({

156

loc: `/products/${product.slug}`,

157

lastmod: product.updatedAt,

158

priority: product.featured ? 0.8 : 0.5,

159

changefreq: 'weekly'

160

}));

161

});

162

163

// server/api/custom-sitemap-handler.ts - Custom sitemap endpoint

164

import {

165

useSitemapRuntimeConfig,

166

xmlEscape,

167

defineSitemapEventHandler

168

} from '#sitemap/server/composables';

169

170

export default defineSitemapEventHandler(async (event) => {

171

const config = useSitemapRuntimeConfig(event);

172

173

// Use configuration for custom logic

174

if (!config.isMultiSitemap) {

175

return [];

176

}

177

178

// Safe XML content

179

const safeTitle = xmlEscape('Products & Services');

180

181

return [

182

asSitemapUrl({

183

loc: '/products',

184

lastmod: new Date(),

185

// Use escaped content in custom fields

186

_customField: safeTitle

187

})

188

];

189

});

190

191

// server/plugins/sitemap-source.ts - Server plugin for URL sources

192

import { logger, mergeOnKey } from '#sitemap/server/utils';

193

194

export default defineNitroPlugin(async (nitroApp) => {

195

// Use logger for debugging

196

logger.info('Initializing sitemap sources');

197

198

// Example of merging duplicate URLs by location

199

const urls = [

200

{ loc: '/page-1', priority: 0.5 },

201

{ loc: '/page-1', priority: 0.8 }, // Will be merged

202

{ loc: '/page-2', priority: 0.6 }

203

];

204

205

const mergedUrls = mergeOnKey(urls, 'loc');

206

// Result: [{ loc: '/page-1', priority: 0.8 }, { loc: '/page-2', priority: 0.6 }]

207

});

208

209

// server/api/i18n-urls.ts - i18n-aware URL generation

210

import {

211

splitForLocales,

212

defineSitemapEventHandler,

213

asSitemapUrl

214

} from '#sitemap/server/composables';

215

216

export default defineSitemapEventHandler(async (event) => {

217

const locales = ['en', 'fr', 'es'];

218

const path = '/blog/my-post';

219

220

const [locale, cleanPath] = splitForLocales('/fr/blog/my-post', locales);

221

// Result: ['fr', '/blog/my-post']

222

223

return [

224

asSitemapUrl({

225

loc: cleanPath,

226

_locale: locale

227

})

228

];

229

});

230

231

// server/middleware/route-rules.ts - Route rule matching

232

import { createNitroRouteRuleMatcher, withoutQuery } from '#sitemap/server/kit';

233

234

const routeRuleMatcher = createNitroRouteRuleMatcher();

235

236

export default defineEventHandler(async (event) => {

237

const url = getRequestURL(event);

238

const path = withoutQuery(url.pathname);

239

240

// Get matching route rules

241

const rules = routeRuleMatcher(path);

242

243

// Use rules for custom logic

244

if (rules.sitemap === false) {

245

// Skip this route in sitemap

246

return;

247

}

248

});

249

```

250

251

## Server Context Integration

252

253

**Nitro Plugin Integration**

254

255

Server composables work seamlessly with Nitro plugins for:

256

- Custom URL source registration

257

- Dynamic sitemap generation based on database content

258

- Integration with external APIs for URL discovery

259

- Custom filtering and transformation logic

260

261

**H3 Event Handler Context**

262

263

All composables are designed to work within H3 event handlers, providing:

264

- Access to request context and headers

265

- Integration with Nuxt's server-side rendering

266

- Proper error handling and response formatting

267

- Type safety for sitemap-specific endpoints

268

269

**Runtime Configuration Access**

270

271

The `useSitemapRuntimeConfig` provides access to:

272

- Normalized filter patterns for URL matching

273

- Multi-sitemap configuration details

274

- i18n settings and locale mapping

275

- Cache and performance settings

276

- Debug and development flags