Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

sitemap.xml.ts

42 lines1.5 KB

1import type { APIRoute } from "astro";
2​
3import {
4 DEFAULT_LOCALE,
5 isLocalizedPath,
6 LOCALES,
7 type LocalizedPath,
8 localizedHref,
9} from "../i18n/locales";
10import { absoluteUrl, STATIC_PAGES } from "../lib/seo";
11​
12// Each localized URL lists every translation plus x-default, as Google's sitemap hreflang format asks.
13const alternateLinks = (path: LocalizedPath) =>
14 [
15 ...LOCALES.map((entry) => ({ hreflang: entry.code, href: localizedHref(entry.code, path) })),
16 { hreflang: "x-default", href: localizedHref(DEFAULT_LOCALE, path) },
17 ]
18 .map(
19 (entry) =>
20 ` <xhtml:link rel="alternate" hreflang="${entry.hreflang}" href="${absoluteUrl(entry.href)}"/>`,
21 )
22 .join("\n");
23​
24export const GET: APIRoute = () => {
25 const urls = STATIC_PAGES.flatMap((page) => {
26 const path = page.path;
27 if (!isLocalizedPath(path)) {
28 return [` <url><loc>${absoluteUrl(path)}</loc><priority>${page.priority}</priority></url>`];
29 }
30 const alternates = alternateLinks(path);
31 return LOCALES.map(
32 (entry) =>
33 ` <url>\n <loc>${absoluteUrl(localizedHref(entry.code, path))}</loc>\n <priority>${page.priority}</priority>\n${alternates}\n </url>`,
34 );
35 });
36 const body = `<?xml version="1.0" encoding="UTF-8"?>
37<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
38${urls.join("\n")}
39</urlset>
40`;
41 return new Response(body, { headers: { "Content-Type": "application/xml; charset=utf-8" } });
42};