0
# Simple API
1
2
High-level convenience functions for quickly generating sitemaps and indices with minimal configuration. This API provides the easiest way to create sitemaps for most common use cases.
3
4
## Capabilities
5
6
### simpleSitemapAndIndex
7
8
A comprehensive function that handles sitemap generation, file management, and index creation automatically.
9
10
```typescript { .api }
11
/**
12
* Creates sitemaps and sitemap index files with automatic file management
13
* Handles large datasets by splitting into multiple sitemap files
14
* @param options - Configuration object for sitemap generation
15
* @returns Promise that resolves when all files are written
16
*/
17
function simpleSitemapAndIndex(options: {
18
/** Base hostname for all URLs */
19
hostname: string;
20
21
/** Hostname for sitemap URLs if different from main hostname */
22
sitemapHostname?: string;
23
24
/** Source data: array, file path, stream, or array of URLs */
25
sourceData: SitemapItemLoose[] | string | Readable | string[];
26
27
/** Directory where sitemaps and index will be written */
28
destinationDir: string;
29
30
/** Base path for sitemap URLs relative to hostname */
31
publicBasePath?: string;
32
33
/** Maximum URLs per sitemap file (default: 50000) */
34
limit?: number;
35
36
/** Whether to gzip compress output files (default: true) */
37
gzip?: boolean;
38
}): Promise<void>;
39
```
40
41
**Usage Examples:**
42
43
```typescript
44
import { simpleSitemapAndIndex } from "sitemap";
45
46
// Basic usage with URL array
47
await simpleSitemapAndIndex({
48
hostname: "https://example.com",
49
sourceData: [
50
{ url: "/", changefreq: "daily", priority: 1.0 },
51
{ url: "/about", changefreq: "monthly", priority: 0.7 },
52
{ url: "/contact", changefreq: "monthly", priority: 0.5 }
53
],
54
destinationDir: "./public/sitemaps/"
55
});
56
57
// From file (line-separated URLs or JSON)
58
await simpleSitemapAndIndex({
59
hostname: "https://example.com",
60
sourceData: "./urls.txt", // File path
61
destinationDir: "./public/sitemaps/",
62
limit: 45000,
63
gzip: true
64
});
65
66
// From stream
67
import { Readable } from "stream";
68
69
const urlStream = Readable.from([
70
"/page-1",
71
"/page-2",
72
"/page-3"
73
]);
74
75
await simpleSitemapAndIndex({
76
hostname: "https://example.com",
77
sourceData: urlStream,
78
destinationDir: "./dist/sitemaps/",
79
publicBasePath: "/sitemaps/",
80
sitemapHostname: "https://cdn.example.com"
81
});
82
83
// Large dataset with custom settings
84
const largeUrls = Array.from({ length: 100000 }, (_, i) => ({
85
url: `/product/${i}`,
86
changefreq: "weekly" as const,
87
priority: 0.6,
88
lastmod: new Date().toISOString()
89
}));
90
91
await simpleSitemapAndIndex({
92
hostname: "https://shop.example.com",
93
sourceData: largeUrls,
94
destinationDir: "./public/sitemaps/",
95
limit: 50000,
96
gzip: true,
97
publicBasePath: "/sitemaps/"
98
});
99
```
100
101
## Source Data Formats
102
103
The `sourceData` parameter accepts multiple input formats:
104
105
### Array of Sitemap Items
106
107
Direct array of sitemap item objects:
108
109
```typescript
110
const sitemapItems: SitemapItemLoose[] = [
111
{
112
url: "/",
113
changefreq: "daily",
114
priority: 1.0,
115
lastmod: "2023-01-01T00:00:00.000Z"
116
},
117
{
118
url: "/products",
119
changefreq: "weekly",
120
priority: 0.8,
121
img: [
122
{
123
url: "https://example.com/product-image.jpg",
124
caption: "Product showcase",
125
title: "Featured Product"
126
}
127
]
128
}
129
];
130
131
await simpleSitemapAndIndex({
132
hostname: "https://example.com",
133
sourceData: sitemapItems,
134
destinationDir: "./sitemaps/"
135
});
136
```
137
138
### File Path (String)
139
140
Path to a file containing URLs or sitemap items:
141
142
```typescript
143
// urls.txt (line-separated URLs)
144
/*
145
/
146
/about
147
/contact
148
/products
149
*/
150
151
// urls.json (JSON array)
152
/*
153
[
154
{"url": "/", "priority": 1.0},
155
{"url": "/about", "priority": 0.7}
156
]
157
*/
158
159
// urls.jsonl (line-separated JSON objects)
160
/*
161
{"url": "/", "changefreq": "daily", "priority": 1.0}
162
{"url": "/about", "changefreq": "monthly", "priority": 0.7}
163
*/
164
165
await simpleSitemapAndIndex({
166
hostname: "https://example.com",
167
sourceData: "./urls.txt", // or ./urls.json or ./urls.jsonl
168
destinationDir: "./sitemaps/"
169
});
170
```
171
172
### Stream
173
174
Any readable stream of URLs or sitemap items:
175
176
```typescript
177
import { Readable } from "stream";
178
import { createReadStream } from "fs";
179
180
// From file stream
181
await simpleSitemapAndIndex({
182
hostname: "https://example.com",
183
sourceData: createReadStream("./large-urls.txt"),
184
destinationDir: "./sitemaps/"
185
});
186
187
// From generated stream
188
async function* generateUrls() {
189
for (let i = 0; i < 10000; i++) {
190
yield { url: `/page-${i}`, priority: 0.5 };
191
}
192
}
193
194
await simpleSitemapAndIndex({
195
hostname: "https://example.com",
196
sourceData: Readable.from(generateUrls()),
197
destinationDir: "./sitemaps/"
198
});
199
```
200
201
### Array of URL Strings
202
203
Simple array of URL strings:
204
205
```typescript
206
const urls = [
207
"/",
208
"/about",
209
"/contact",
210
"/products",
211
"/services"
212
];
213
214
await simpleSitemapAndIndex({
215
hostname: "https://example.com",
216
sourceData: urls,
217
destinationDir: "./sitemaps/"
218
});
219
```
220
221
## Advanced Configuration
222
223
### Custom Public Path
224
225
Control how sitemap URLs appear in the index:
226
227
```typescript
228
await simpleSitemapAndIndex({
229
hostname: "https://example.com",
230
sourceData: [...],
231
destinationDir: "./public/sitemaps/",
232
publicBasePath: "/static/sitemaps/", // Sitemaps accessible at /static/sitemaps/
233
sitemapHostname: "https://cdn.example.com" // Different hostname for sitemaps
234
});
235
```
236
237
### File Size Management
238
239
```typescript
240
await simpleSitemapAndIndex({
241
hostname: "https://example.com",
242
sourceData: [...],
243
destinationDir: "./sitemaps/",
244
limit: 25000, // Smaller files for faster processing
245
gzip: true // Compress for bandwidth savings
246
});
247
```
248
249
### Error Handling
250
251
```typescript
252
try {
253
await simpleSitemapAndIndex({
254
hostname: "https://example.com",
255
sourceData: "./invalid-file.txt",
256
destinationDir: "./sitemaps/"
257
});
258
} catch (error) {
259
console.error("Sitemap generation failed:", error.message);
260
261
if (error.code === 'ENOENT') {
262
console.error("Source file not found");
263
}
264
}
265
```
266
267
## Output Files
268
269
The function creates the following files in the destination directory:
270
271
### Without Gzip
272
273
- `sitemap-0.xml` - First sitemap file
274
- `sitemap-1.xml` - Second sitemap file (if needed)
275
- `sitemap-index.xml` - Index file referencing all sitemaps
276
277
### With Gzip (default)
278
279
- `sitemap-0.xml.gz` - Compressed first sitemap
280
- `sitemap-1.xml.gz` - Compressed second sitemap (if needed)
281
- `sitemap-index.xml.gz` - Compressed index file
282
283
## Integration Examples
284
285
### Express.js Route
286
287
```typescript
288
import express from "express";
289
import { simpleSitemapAndIndex } from "sitemap";
290
import { join } from "path";
291
292
const app = express();
293
294
app.get("/generate-sitemap", async (req, res) => {
295
try {
296
const urls = await getUrlsFromDatabase(); // Your data source
297
298
await simpleSitemapAndIndex({
299
hostname: "https://example.com",
300
sourceData: urls,
301
destinationDir: join(__dirname, "public", "sitemaps"),
302
publicBasePath: "/sitemaps/"
303
});
304
305
res.json({ success: true, message: "Sitemap generated" });
306
} catch (error) {
307
res.status(500).json({ error: error.message });
308
}
309
});
310
```
311
312
### Build Script
313
314
```typescript
315
// scripts/generate-sitemap.ts
316
import { simpleSitemapAndIndex } from "sitemap";
317
import { resolve } from "path";
318
319
async function buildSitemap() {
320
console.log("Generating sitemap...");
321
322
await simpleSitemapAndIndex({
323
hostname: process.env.SITE_URL || "https://example.com",
324
sourceData: resolve(__dirname, "../data/urls.json"),
325
destinationDir: resolve(__dirname, "../dist/sitemaps"),
326
limit: 50000,
327
gzip: true
328
});
329
330
console.log("Sitemap generation complete!");
331
}
332
333
buildSitemap().catch(console.error);
334
```