Skip to content

Commit 52f7536

Browse files
authored
feat: better behavior for 'undefined' return values from 'serialize… (#3723)
* feat: better behavior with 'undefined' return values after 'serialize' func * build: changeset added
1 parent 0ae1365 commit 52f7536

3 files changed

Lines changed: 19 additions & 3 deletions

File tree

.changeset/tidy-dots-own.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@astrojs/sitemap': patch
3+
---
4+
5+
fix: if `serialize` function returns `undefined` for the passed entry, such entry will be excluded from sitemap

packages/integrations/sitemap/README.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,9 @@ The `LinkItem` type has two required fields: `url` (the fully-qualified URL for
222222

223223
The `serialize` function should return `SitemapItem`, touched or not.
224224

225-
The example below shows the ability to add the sitemap specific properties individually.
225+
To exclude the passed entry from sitemap it should return `undefined`.
226+
227+
The example below shows the ability to exclude certain entries and add the sitemap specific properties individually.
226228

227229
__astro.config.mjs__
228230

@@ -234,6 +236,9 @@ export default {
234236
integrations: [
235237
sitemap({
236238
serialize(item) {
239+
if (/exclude-from-sitemap/.test(item.url)) {
240+
return undefined;
241+
}
237242
if (/your-special-page/.test(item.url)) {
238243
item.changefreq = 'daily';
239244
item.lastmod = new Date();

packages/integrations/sitemap/src/index.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ export type SitemapOptions =
3838
priority?: number;
3939

4040
// called for each sitemap item just before to save them on disk, sync or async
41-
serialize?(item: SitemapItem): SitemapItem | Promise<SitemapItem>;
41+
serialize?(item: SitemapItem): SitemapItem | Promise<SitemapItem | undefined> | undefined;
4242
}
4343
| undefined;
4444

@@ -117,8 +117,14 @@ const createPlugin = (options?: SitemapOptions): AstroIntegration => {
117117
const serializedUrls: SitemapItem[] = [];
118118
for (const item of urlData) {
119119
const serialized = await Promise.resolve(serialize(item));
120-
serializedUrls.push(serialized);
120+
if (serialized) {
121+
serializedUrls.push(serialized);
122+
}
121123
}
124+
if (serializedUrls.length === 0) {
125+
logger.warn('No pages found!');
126+
return;
127+
}
122128
urlData = serializedUrls;
123129
} catch (err) {
124130
logger.error(`Error serializing pages\n${(err as any).toString()}`);

0 commit comments

Comments
 (0)