diff --git a/packages/next-sitemap/src/builders/sitemap-builder.ts b/packages/next-sitemap/src/builders/sitemap-builder.ts index 3e6c2b55..ff27c898 100644 --- a/packages/next-sitemap/src/builders/sitemap-builder.ts +++ b/packages/next-sitemap/src/builders/sitemap-builder.ts @@ -28,6 +28,26 @@ export class SitemapBuilder { ` } + /** + * Normalize sitemap field keys to stay consistent with order + * @link https://www.w3schools.com/xml/el_sequence.asp + * @link https://github.com/iamvishnusankar/next-sitemap/issues/345 + * @param x + * @returns + */ + normalizeSitemapField(x: ISitemapField) { + const { loc, lastmod, changefreq, priority, ...restProps } = x + + // Return keys in following order + return { + loc, + lastmod, + changefreq, + priority, + ...restProps, + } + } + /** * Generates sitemap.xml * @param fields @@ -35,31 +55,35 @@ export class SitemapBuilder { */ buildSitemapXml(fields: ISitemapField[]): string { const content = fields - .map((fieldData) => { - const field: Array = [] + .map((x: ISitemapField) => { + // Normalize sitemap field keys to stay consistent with order + const filed = this.normalizeSitemapField(x) + + // Field array to keep track of properties + const fieldArr: Array = [] // Iterate all object keys and key value pair to field-set - for (const key of Object.keys(fieldData)) { + for (const key of Object.keys(filed)) { // Skip reserved keys if (['trailingSlash'].includes(key)) { continue } - if (fieldData[key]) { + if (filed[key]) { if (key !== 'alternateRefs') { - field.push(`<${key}>${fieldData[key]}`) + fieldArr.push(`<${key}>${filed[key]}`) } else { const altRefField = this.buildAlternateRefsXml( - fieldData.alternateRefs + filed.alternateRefs ) - field.push(altRefField) + fieldArr.push(altRefField) } } } // Append previous value and return - return `${field.join('')}\n` + return `${fieldArr.join('')}\n` }) .join('') diff --git a/packages/next-sitemap/src/utils/defaults.ts b/packages/next-sitemap/src/utils/defaults.ts index e9412d25..d86bb42e 100644 --- a/packages/next-sitemap/src/utils/defaults.ts +++ b/packages/next-sitemap/src/utils/defaults.ts @@ -7,9 +7,9 @@ export const defaultSitemapTransformer = async ( ): Promise => { return { loc, + lastmod: config?.autoLastmod ? new Date().toISOString() : undefined, changefreq: config?.changefreq, priority: config?.priority, - lastmod: config?.autoLastmod ? new Date().toISOString() : undefined, alternateRefs: config.alternateRefs ?? [], trailingSlash: config?.trailingSlash, }