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

Juanpprieto/stable sitemap #2589

Merged
merged 16 commits into from
Oct 21, 2024
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
23 changes: 23 additions & 0 deletions .changeset/funny-cows-perform.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
'skeleton': patch
'@shopify/hydrogen': patch
'@shopify/cli-hydrogen': patch
---

Stabilize `getSitemap`, `getSitemapIndex` and implement on skeleton

1. Update the `getSitemapIndex` at `/app/routes/[sitemap.xml].tsx`

```diff
- import {unstable__getSitemapIndex as getSitemapIndex} from '@shopify/hydrogen';
+ import {getSitemapIndex} from '@shopify/hydrogen';
```

2. Update the `getSitemap` at `/app/routes/sitemap.$type.$page[.xml].tsx`

```diff
- import {unstable__getSitemap as getSitemap} from '@shopify/hydrogen';
+ import {getSitemap} from '@shopify/hydrogen';
```

For a reference implementation please see the skeleton template sitemap routes
1 change: 0 additions & 1 deletion .github/workflows/deploy-examples.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ jobs:
{name: 'metaobjects', token: '1000014928'},
{name: 'third-party-queries-caching', token: '1000014929'},
{name: 'custom-cart-method', token: '1000014930'},
{name: 'sitemap', token: '1000022490'},
]
steps:
- uses: actions/checkout@v4
Expand Down
38 changes: 0 additions & 38 deletions examples/sitemap/README.md

This file was deleted.

16 changes: 0 additions & 16 deletions examples/sitemap/app/routes/[sitemap.xml].tsx

This file was deleted.

16 changes: 0 additions & 16 deletions examples/sitemap/package.json

This file was deleted.

16 changes: 0 additions & 16 deletions examples/sitemap/tsconfig.json

This file was deleted.

2 changes: 1 addition & 1 deletion packages/cli/src/lib/setups/routes/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ const ROUTE_MAP = {
account: 'account*',
search: ['search', 'api.predictive-search'],
robots: '[robots.txt]',
sitemap: '[sitemap.xml]',
sitemap: ['[sitemap.xml]', 'sitemap.$type.$page[.xml]'],
};

type RouteKey = keyof typeof ROUTE_MAP;
Expand Down
2 changes: 1 addition & 1 deletion packages/create-hydrogen/integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ describe('create-hydrogen', () => {
│ • Account (/account/*) │
│ • Search (/search) │
│ • Robots (/robots.txt) │
│ • Sitemap (/sitemap.xml)
│ • Sitemap (/sitemap.xml & /sitemap/:type/:page.xml)
│ │
│ Next steps │
│ │
Expand Down
5 changes: 1 addition & 4 deletions packages/hydrogen/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,4 @@ export {
type HydrogenContext,
} from './createHydrogenContext';

export {
getSitemapIndex as unstable__getSitemapIndex,
getSitemap as unstable__getSitemap,
} from './sitemap/sitemap';
export {getSitemapIndex, getSitemap} from './sitemap/sitemap';
2 changes: 1 addition & 1 deletion packages/hydrogen/src/sitemap/getSitemap.example.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type {LoaderFunctionArgs} from '@shopify/remix-oxygen';
import {unstable__getSitemap as getSitemap} from '@shopify/hydrogen';
import {getSitemap} from '@shopify/hydrogen';

export async function loader({
request,
Expand Down
2 changes: 1 addition & 1 deletion packages/hydrogen/src/sitemap/getSitemapIndex.example.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type {LoaderFunctionArgs} from '@shopify/remix-oxygen';
import {unstable__getSitemapIndex as getSitemapIndex} from '@shopify/hydrogen';
import {getSitemapIndex} from '@shopify/hydrogen';

export async function loader({
request,
Expand Down
21 changes: 14 additions & 7 deletions packages/hydrogen/src/sitemap/sitemap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,13 @@ export async function getSitemapIndex(
'A storefront client is required to generate a sitemap index',
);

const data = await storefront.query(SITEMAP_INDEX_QUERY, {
storefrontApiVersion: 'unstable',
});
const data = await storefront.query(SITEMAP_INDEX_QUERY);

if (!data) {
throw new Response('No data found', {status: 404});
console.warn(
'[h2:sitemap:warning] Sitemap index is available in API version 2024-10 and later',
);
throw new Response('Sitemap index not found.', {status: 404});
}

const baseUrl = new URL(request.url).origin;
Expand Down Expand Up @@ -166,9 +167,15 @@ export async function getSitemap(
variables: {
page: parseInt(params.page, 10),
},
storefrontApiVersion: 'unstable',
});

if (!data) {
console.warn(
'[h2:sitemap:warning] Sitemap is available in API version 2024-10 and later',
);
throw new Response('Sitemap not found.', {status: 404});
}

const baseUrl = new URL(request.url).origin;
let body: string = '';

Expand Down Expand Up @@ -336,7 +343,7 @@ const BLOG_SITEMAP_QUERY = `#graphql

const METAOBJECT_SITEMAP_QUERY = `#graphql
query SitemapMetaobjects($page: Int!) {
sitemap(type: METAOBJECT_PAGE) {
sitemap(type: METAOBJECT) {
resources(page: $page) {
items {
handle
Expand Down Expand Up @@ -377,7 +384,7 @@ query SitemapIndex {
count
}
}
metaObjects: sitemap(type: METAOBJECT_PAGE) {
metaObjects: sitemap(type: METAOBJECT) {
pagesCount {
count
}
Expand Down
172 changes: 6 additions & 166 deletions templates/skeleton/app/routes/[sitemap.xml].tsx
Original file line number Diff line number Diff line change
@@ -1,177 +1,17 @@
import {flattenConnection} from '@shopify/hydrogen';
import type {LoaderFunctionArgs} from '@shopify/remix-oxygen';
import type {SitemapQuery} from 'storefrontapi.generated';

/**
* the google limit is 50K, however, the storefront API
* allows querying only 250 resources per pagination page
*/
const MAX_URLS = 250;

type Entry = {
url: string;
lastMod?: string;
changeFreq?: string;
image?: {
url: string;
title?: string;
caption?: string;
};
};
import {getSitemapIndex} from '@shopify/hydrogen';

export async function loader({
request,
context: {storefront},
}: LoaderFunctionArgs) {
const data = await storefront.query(SITEMAP_QUERY, {
variables: {
urlLimits: MAX_URLS,
language: storefront.i18n.language,
},
});

if (!data) {
throw new Response('No data found', {status: 404});
}

const sitemap = generateSitemap({data, baseUrl: new URL(request.url).origin});

return new Response(sitemap, {
headers: {
'Content-Type': 'application/xml',

'Cache-Control': `max-age=${60 * 60 * 24}`,
},
const response = await getSitemapIndex({
storefront,
request,
});
}

function xmlEncode(string: string) {
return string.replace(/[&<>'"]/g, (char) => `&#${char.charCodeAt(0)};`);
}

function generateSitemap({
data,
baseUrl,
}: {
data: SitemapQuery;
baseUrl: string;
}) {
const products = flattenConnection(data.products)
.filter((product) => product.onlineStoreUrl)
.map((product) => {
const url = `${baseUrl}/products/${xmlEncode(product.handle)}`;

const productEntry: Entry = {
url,
lastMod: product.updatedAt,
changeFreq: 'daily',
};

if (product.featuredImage?.url) {
productEntry.image = {
url: xmlEncode(product.featuredImage.url),
};

if (product.title) {
productEntry.image.title = xmlEncode(product.title);
}

if (product.featuredImage.altText) {
productEntry.image.caption = xmlEncode(product.featuredImage.altText);
}
}

return productEntry;
});

const collections = flattenConnection(data.collections)
.filter((collection) => collection.onlineStoreUrl)
.map((collection) => {
const url = `${baseUrl}/collections/${collection.handle}`;

return {
url,
lastMod: collection.updatedAt,
changeFreq: 'daily',
};
});

const pages = flattenConnection(data.pages)
.filter((page) => page.onlineStoreUrl)
.map((page) => {
const url = `${baseUrl}/pages/${page.handle}`;

return {
url,
lastMod: page.updatedAt,
changeFreq: 'weekly',
};
});

const urls = [...products, ...collections, ...pages];

return `
<urlset
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
>
${urls.map(renderUrlTag).join('')}
</urlset>`;
}

function renderUrlTag({url, lastMod, changeFreq, image}: Entry) {
const imageTag = image
? `<image:image>
<image:loc>${image.url}</image:loc>
<image:title>${image.title ?? ''}</image:title>
<image:caption>${image.caption ?? ''}</image:caption>
</image:image>`.trim()
: '';
response.headers.set('Cache-Control', `max-age=${60 * 60 * 24}`);

return `
<url>
<loc>${url}</loc>
<lastmod>${lastMod}</lastmod>
<changefreq>${changeFreq}</changefreq>
${imageTag}
</url>
`.trim();
return response;
}

const SITEMAP_QUERY = `#graphql
query Sitemap($urlLimits: Int, $language: LanguageCode)
@inContext(language: $language) {
products(
first: $urlLimits
query: "published_status:'online_store:visible'"
) {
nodes {
updatedAt
handle
onlineStoreUrl
title
featuredImage {
url
altText
}
}
}
collections(
first: $urlLimits
query: "published_status:'online_store:visible'"
) {
nodes {
updatedAt
handle
onlineStoreUrl
}
}
pages(first: $urlLimits, query: "published_status:'published'") {
nodes {
updatedAt
handle
onlineStoreUrl
}
}
}
` as const;
Loading
Loading