Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sitemap: support SSR routes #6534

Merged
merged 6 commits into from
May 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/chatty-dolls-visit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/sitemap': minor
---

Adds support to SSR routes to sitemap generation.
1 change: 1 addition & 0 deletions packages/integrations/sitemap/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"zod": "^3.17.3"
},
"devDependencies": {
"@astrojs/node": "workspace:*",
"astro": "workspace:*",
"astro-scripts": "workspace:*",
"chai": "^4.3.6",
Expand Down
54 changes: 36 additions & 18 deletions packages/integrations/sitemap/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ const OUTFILE = 'sitemap-index.xml';

const createPlugin = (options?: SitemapOptions): AstroIntegration => {
let config: AstroConfig;
const logger = new Logger(PKG_NAME);

return {
name: PKG_NAME,

Expand All @@ -59,10 +61,15 @@ const createPlugin = (options?: SitemapOptions): AstroIntegration => {
config = cfg;
},

'astro:build:done': async ({ dir, pages }) => {
const logger = new Logger(PKG_NAME);

'astro:build:done': async ({ dir, routes }) => {
try {
if (!config.site) {
logger.warn(
'The Sitemap integration requires the `site` astro.config option. Skipping.'
);
return;
}

const opts = validateOptions(config.site, options);

const { filter, customPages, serialize, entryLimit } = opts;
Expand All @@ -78,12 +85,30 @@ const createPlugin = (options?: SitemapOptions): AstroIntegration => {
return;
}

let pageUrls = pages.map((p) => {
if (p.pathname !== '' && !finalSiteUrl.pathname.endsWith('/'))
finalSiteUrl.pathname += '/';
const path = finalSiteUrl.pathname + p.pathname;
return new URL(path, finalSiteUrl).href;
});
let pageUrls = routes.reduce<string[]>((urls, r) => {
/**
* Dynamic URLs have entries with `undefined` pathnames
*/
if (r.pathname) {
/**
* remove the initial slash from relative pathname
* because `finalSiteUrl` always has trailing slash
*/
const path = finalSiteUrl.pathname + r.generate(r.pathname).substring(1);

let newUrl = new URL(path, finalSiteUrl).href;

if (config.trailingSlash === 'never') {
urls.push(newUrl);
} else if (config.build.format === 'directory' && !newUrl.endsWith('/')) {
urls.push(newUrl + '/');
} else {
urls.push(newUrl);
}
}

return urls;
}, []);

try {
if (filter) {
Expand All @@ -95,18 +120,11 @@ const createPlugin = (options?: SitemapOptions): AstroIntegration => {
}

if (customPages) {
pageUrls = [...pageUrls, ...customPages];
pageUrls = Array.from(new Set([...pageUrls, ...customPages]));
}

if (pageUrls.length === 0) {
// offer suggestion for SSR users
if (config.output !== 'static') {
logger.warn(
`No pages found! We can only detect sitemap routes for "static" builds. Since you are using an SSR adapter, we recommend manually listing your sitemap routes using the "customPages" integration option.\n\nExample: \`sitemap({ customPages: ['https://example.com/route'] })\``
);
} else {
logger.warn(`No pages found!\n\`${OUTFILE}\` not created.`);
}
logger.warn(`No pages found!\n\`${OUTFILE}\` not created.`);
return;
}

Expand Down
12 changes: 12 additions & 0 deletions packages/integrations/sitemap/test/fixtures/ssr/astro.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { defineConfig } from 'astro/config';
import sitemap from '@astrojs/sitemap';
import nodeServer from '@astrojs/node'

export default defineConfig({
integrations: [sitemap()],
site: 'http://example.com',
output: 'server',
adapter: nodeServer({
mode: "standalone"
})
})
9 changes: 9 additions & 0 deletions packages/integrations/sitemap/test/fixtures/ssr/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "@test/sitemap-trailing-slash",
"version": "0.0.0",
"private": true,
"dependencies": {
"astro": "workspace:*",
"@astrojs/sitemap": "workspace:*"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<html>
<head>
<title>One</title>
</head>
<body>
<h1>One</h1>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<html>
<head>
<title>Two</title>
</head>
<body>
<h1>Two</h1>
</body>
</html>
22 changes: 22 additions & 0 deletions packages/integrations/sitemap/test/ssr.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { loadFixture, readXML } from './test-utils.js';
import { expect } from 'chai';

describe('SSR support', () => {
/** @type {import('./test-utils.js').Fixture} */
let fixture;

before(async () => {
fixture = await loadFixture({
root: './fixtures/ssr/',
});
await fixture.build();
});

it('SSR pages require zero config', async () => {
const data = await readXML(fixture.readFile('/client/sitemap-0.xml'));
const urls = data.urlset.url;

expect(urls[0].loc[0]).to.equal('http://example.com/one/');
expect(urls[1].loc[0]).to.equal('http://example.com/two/');
});
});
12 changes: 12 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.