Skip to content

Commit 2379803

Browse files
authored
Merge pull request #16 from Weaverse/fix/blog-routing-and-studio
Fix merchant blog resolution and Studio routing
2 parents ceb90c8 + 10b964c commit 2379803

28 files changed

Lines changed: 1320 additions & 109 deletions

‎app/routes.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ export default hydrogenRoutes([
5151
"routes/($locale).api.review.$productHandle.ts",
5252
),
5353
]),
54+
route("blog/:blogHandle", "routes/($locale).blog.$blogHandle.tsx"),
5455
...prefix("blogs", [
5556
index("routes/($locale).blogs._index.tsx"),
5657
route(":articleHandle", "routes/($locale).blogs.$articleHandle.tsx"),

‎app/routes/($locale).api.predictive-search.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import type {
1313
NormalizedPredictiveSearch,
1414
NormalizedPredictiveSearchResults,
1515
} from "~/types/predictive-search";
16+
import { articlePath } from "~/utils/blog-path";
1617
import {
1718
COMBINED_LISTINGS_CONFIGS,
1819
isCombinedListing,
@@ -311,7 +312,7 @@ function normalizePredictiveSearchResults(
311312
id: article.id,
312313
image: article.image,
313314
title: article.title,
314-
url: `${localePrefix}/blogs/${article.handle}${createSearchParams(article)}`,
315+
url: `${localePrefix}${articlePath(article.handle)}${createSearchParams(article, new URLSearchParams({ blog: article.blog.handle }))}`,
315316
})),
316317
...predictiveSearch.pages.map((page) => ({
317318
__typename: page.__typename,
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import type { LoaderFunctionArgs } from "react-router";
2+
import invariant from "tiny-invariant";
3+
import { loader as loadBlog } from "./($locale).blogs._index";
4+
5+
export {
6+
default,
7+
headers,
8+
meta,
9+
shouldRevalidate,
10+
} from "./($locale).blogs._index";
11+
12+
/** Studio needs a whole path segment for each selected blog's identity. */
13+
export function loader(args: LoaderFunctionArgs) {
14+
invariant(args.params.blogHandle, "Missing blog handle");
15+
return loadBlog(args);
16+
}

‎app/routes/($locale).blogs.$articleHandle.tsx‎

Lines changed: 59 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import type { SeoConfig } from "@shopify/hydrogen";
2-
import type { RouteLoaderArgs } from "@weaverse/hydrogen";
3-
import type { MetaFunction } from "react-router";
2+
import type { LoaderFunctionArgs, MetaFunction } from "react-router";
43
import { redirect } from "react-router";
54
import type { ArticleQuery } from "storefront-api.generated";
65
import invariant from "tiny-invariant";
6+
import { loadArticlePage } from "~/utils/article-page.server";
7+
import { resolveArticleBlog } from "~/utils/blog.server";
8+
import { articlePath, blogPath, blogSeoMeta } from "~/utils/blog-path";
79
import { routeHeaders } from "~/utils/cache";
8-
import { DEFAULT_BLOG_HANDLE } from "~/utils/const";
9-
import { redirectIfHandleIsLocalized } from "~/utils/redirect";
1010
import { skipPageRevalidationForStorefrontActions } from "~/utils/revalidation";
1111
import { seoPayload } from "~/utils/seo.server";
1212
import { localizedSeoMeta } from "~/utils/seo-translation";
@@ -15,41 +15,65 @@ import { WeaverseContent } from "~/weaverse";
1515
export const headers = routeHeaders;
1616
export const shouldRevalidate = skipPageRevalidationForStorefrontActions;
1717

18-
export async function loader(args: RouteLoaderArgs) {
18+
export async function loader(args: LoaderFunctionArgs) {
1919
const { request, params, context } = args;
2020
const { storefront } = context.weaverse;
2121
const { language, country } = storefront.i18n;
2222

2323
invariant(params.articleHandle, "Missing article handle");
2424

2525
const { articleHandle } = params;
26-
if (articleHandle === DEFAULT_BLOG_HANDLE) {
27-
const localePrefix = params.locale ? `/${params.locale}` : "";
28-
return redirect(`${localePrefix}/blogs`, 301);
26+
const url = new URL(request.url);
27+
const requestedBlog = params.blogHandle ?? url.searchParams.get("blog");
28+
const blogHandle = await resolveArticleBlog(
29+
storefront,
30+
articleHandle,
31+
requestedBlog,
32+
);
33+
if (!blogHandle) {
34+
// Shopify's /blogs/:blogHandle listing aliases share the short article path.
35+
const { blog: listing } = await storefront.query(BLOG_ALIAS_QUERY, {
36+
variables: { handle: articleHandle, language },
37+
});
38+
if (!requestedBlog && listing) {
39+
const destination = new URL(blogPath(listing.handle), url);
40+
url.searchParams.set("blog", listing.handle);
41+
return redirect(
42+
`${params.locale ? `/${params.locale}` : ""}${destination.pathname}?${url.searchParams}`,
43+
301,
44+
);
45+
}
46+
throw new Response(null, { status: 404 });
2947
}
3048

3149
const [{ blog }, weaverseData] = await Promise.all([
3250
storefront.query<ArticleQuery>(ARTICLE_QUERY, {
3351
variables: {
34-
blogHandle: DEFAULT_BLOG_HANDLE,
52+
blogHandle,
3553
articleHandle,
3654
language,
3755
},
3856
}),
39-
context.weaverse.loadPage({
40-
type: "ARTICLE",
41-
handle: articleHandle,
57+
loadArticlePage(context, {
58+
blogHandle,
59+
articleHandle,
60+
locale: params.locale,
4261
}),
4362
]);
4463

4564
if (!blog?.articleByHandle) {
4665
throw new Response(null, { status: 404 });
4766
}
4867

49-
redirectIfHandleIsLocalized(request, {
50-
handle: articleHandle,
51-
data: blog.articleByHandle,
52-
});
68+
if (articleHandle !== blog.articleByHandle.handle) {
69+
// Replace the article segment only: its text may also occur in the locale
70+
// or parent blog. Keep Studio's full path and the request's query intact.
71+
const segments = url.pathname.split("/");
72+
const articleIndex = segments.length - (url.pathname.endsWith("/") ? 2 : 1);
73+
segments[articleIndex] = encodeURIComponent(blog.articleByHandle.handle);
74+
url.pathname = segments.join("/");
75+
throw redirect(url.toString());
76+
}
5377

5478
const article = blog.articleByHandle;
5579
const relatedArticles = blog.articles.nodes.filter(
@@ -62,12 +86,18 @@ export async function loader(args: RouteLoaderArgs) {
6286
day: "numeric",
6387
}).format(new Date(article.publishedAt));
6488

65-
const seo = seoPayload.article({ article, url: request.url });
89+
// Include the parent in canonical/share URLs, including legacy short requests.
90+
const articleUrl = new URL(
91+
articlePath(article.handle, blog.handle),
92+
request.url,
93+
);
94+
articleUrl.pathname = `${params.locale ? `/${params.locale}` : ""}${articleUrl.pathname}`;
95+
const seo = seoPayload.article({ article, url: articleUrl.toString() });
6696

6797
return {
6898
article,
6999
blog: {
70-
handle: DEFAULT_BLOG_HANDLE,
100+
handle: blog.handle,
71101
},
72102
relatedArticles,
73103
formattedDate,
@@ -77,7 +107,10 @@ export async function loader(args: RouteLoaderArgs) {
77107
}
78108

79109
export const meta: MetaFunction<typeof loader> = ({ data, matches }) => {
80-
return localizedSeoMeta(matches, data?.seo as SeoConfig);
110+
return blogSeoMeta(
111+
localizedSeoMeta(matches, data?.seo as SeoConfig),
112+
data?.seo?.url,
113+
);
81114
};
82115

83116
export default function Article() {
@@ -122,6 +155,7 @@ const ARTICLE_QUERY = `#graphql
122155
}
123156
}
124157
fragment Article on Article {
158+
blog { handle }
125159
tags
126160
author: authorV2 {
127161
name
@@ -142,3 +176,9 @@ const ARTICLE_QUERY = `#graphql
142176
title
143177
}
144178
` as const;
179+
180+
const BLOG_ALIAS_QUERY = `#graphql
181+
query MerchantBlogAlias($handle: String!, $language: LanguageCode) @inContext(language: $language) {
182+
blog(handle: $handle) { handle }
183+
}
184+
` as const;
Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
1-
import type { RouteLoaderArgs } from "@weaverse/hydrogen";
2-
import { redirect } from "react-router";
1+
import type { LoaderFunctionArgs } from "react-router";
32
import invariant from "tiny-invariant";
4-
import { routeHeaders } from "~/utils/cache";
5-
import { skipPageRevalidationForStorefrontActions } from "~/utils/revalidation";
3+
import { loader as loadArticle } from "./($locale).blogs.$articleHandle";
64

7-
export const headers = routeHeaders;
8-
export const shouldRevalidate = skipPageRevalidationForStorefrontActions;
5+
export {
6+
default,
7+
headers,
8+
meta,
9+
shouldRevalidate,
10+
} from "./($locale).blogs.$articleHandle";
911

10-
export async function loader(args: RouteLoaderArgs) {
11-
const { params } = args;
12-
invariant(params.articleHandle, "Missing article handle");
13-
const localePrefix = params.locale ? `/${params.locale}` : "";
14-
return redirect(`${localePrefix}/blogs/${params.articleHandle}`, 301);
12+
/** Shopify/Studio URLs carry the parent explicitly and load without a redirect. */
13+
export function loader(args: LoaderFunctionArgs) {
14+
invariant(args.params.blogHandle, "Missing blog handle");
15+
return loadArticle(args);
1516
}

‎app/routes/($locale).blogs.$blogHandle._index.tsx‎

Lines changed: 0 additions & 10 deletions
This file was deleted.

‎app/routes/($locale).blogs._index.tsx‎

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@ import { flattenConnection } from "@shopify/hydrogen";
33
import type { MetaFunction } from "react-router";
44
import { data, type LoaderFunctionArgs } from "react-router";
55
import type { BlogsIndexQuery } from "storefront-api.generated";
6+
import { resolveListingBlog } from "~/utils/blog.server";
7+
import { blogPath, blogSeoMeta } from "~/utils/blog-path";
68
import { routeHeaders } from "~/utils/cache";
7-
import { DEFAULT_BLOG_HANDLE, PAGINATION_SIZE } from "~/utils/const";
9+
import { PAGINATION_SIZE } from "~/utils/const";
810
import { skipPageRevalidationForStorefrontActions } from "~/utils/revalidation";
911
import { seoPayload } from "~/utils/seo.server";
1012
import { localizedSeoMeta } from "~/utils/seo-translation";
@@ -13,12 +15,23 @@ import { WeaverseContent } from "~/weaverse";
1315
export const headers = routeHeaders;
1416
export const shouldRevalidate = skipPageRevalidationForStorefrontActions;
1517

16-
export const loader = async ({ request, context }: LoaderFunctionArgs) => {
18+
export const loader = async ({
19+
request,
20+
context,
21+
params,
22+
}: LoaderFunctionArgs) => {
1723
const storefront = context.storefront;
1824
const { language, country } = storefront.i18n;
25+
const blogHandle = await resolveListingBlog(
26+
storefront,
27+
params.blogHandle ?? new URL(request.url).searchParams.get("blog"),
28+
);
29+
if (!blogHandle) {
30+
throw new Response("Not found", { status: 404 });
31+
}
1932
const { blog } = await storefront.query<BlogsIndexQuery>(BLOGS_INDEX_QUERY, {
2033
variables: {
21-
blogHandle: DEFAULT_BLOG_HANDLE,
34+
blogHandle,
2235
pageBy: PAGINATION_SIZE,
2336
language,
2437
},
@@ -44,7 +57,13 @@ export const loader = async ({ request, context }: LoaderFunctionArgs) => {
4457
}).format(new Date(publishedAt)),
4558
};
4659
});
47-
const seo = seoPayload.blog({ blog, url: request.url });
60+
const canonical = new URL(request.url);
61+
if (params.blogHandle) {
62+
const path = new URL(blogPath(blog.handle), request.url);
63+
canonical.pathname = `${params.locale ? `/${params.locale}` : ""}${path.pathname}`;
64+
canonical.search = path.search;
65+
}
66+
const seo = seoPayload.blog({ blog, url: canonical.toString() });
4867

4968
return data({ blog, articles, seo, weaverseData });
5069
};
@@ -53,7 +72,10 @@ export const meta: MetaFunction<typeof loader> = ({
5372
data: loaderData,
5473
matches,
5574
}) => {
56-
return localizedSeoMeta(matches, loaderData?.seo as SeoConfig);
75+
return blogSeoMeta(
76+
localizedSeoMeta(matches, loaderData?.seo as SeoConfig),
77+
loaderData?.seo?.url,
78+
);
5779
};
5880

5981
export default function BlogsIndex() {
@@ -85,6 +107,7 @@ const BLOGS_INDEX_QUERY = `#graphql
85107
}
86108
87109
fragment BlogArticle on Article {
110+
blog { handle }
88111
author: authorV2 {
89112
name
90113
}

‎app/routes/($locale).sitemap.$type.$page[.xml].tsx‎

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,49 @@
1-
import { getSitemap } from "@shopify/hydrogen";
1+
import { getSitemap, type Storefront } from "@shopify/hydrogen";
22
import type { LoaderFunctionArgs } from "react-router";
3+
import { articlePath, blogPath } from "~/utils/blog-path";
4+
import { qualifyArticleSitemapItems } from "~/utils/blog-sitemap.server";
35
import { localeCode } from "~/utils/locale";
46
import { canonicalStorefrontPathname } from "~/utils/storefront-path";
57

8+
type SitemapQueryData = {
9+
sitemap?: {
10+
resources?: { items: Array<{ handle: string; updatedAt: string }> };
11+
};
12+
};
13+
614
export async function loader({
715
request,
816
params,
917
context: { storefront, localization },
1018
}: LoaderFunctionArgs) {
19+
const storefrontClient: Storefront = storefront;
20+
const sitemapStorefront = {
21+
...storefront,
22+
query: (async (query, options) => {
23+
const result = await storefrontClient.query<SitemapQueryData>(
24+
query,
25+
options,
26+
);
27+
if (params.type === "articles" && result?.sitemap?.resources?.items) {
28+
return {
29+
...result,
30+
sitemap: {
31+
...result.sitemap,
32+
resources: {
33+
...result.sitemap.resources,
34+
items: await qualifyArticleSitemapItems(
35+
storefrontClient,
36+
result.sitemap.resources.items,
37+
),
38+
},
39+
},
40+
};
41+
}
42+
return result;
43+
}) as Storefront["query"],
44+
};
1145
const response = await getSitemap({
12-
storefront,
46+
storefront: sitemapStorefront,
1347
request,
1448
params,
1549
locales: localization.availableLocales.map((locale) =>
@@ -20,6 +54,13 @@ export async function loader({
2054
localization.availableLocales.find(
2155
(candidate) => localeCode(candidate) === locale?.toLowerCase(),
2256
)?.pathPrefix ?? "";
57+
if (type === "blogs") {
58+
return `${baseUrl}${prefix}${blogPath(handle)}`;
59+
}
60+
if (type === "articles") {
61+
const [blogHandle, ...articleHandle] = handle.split("/");
62+
return `${baseUrl}${prefix}${articlePath(articleHandle.join("/"), blogHandle)}`;
63+
}
2364
const pathname = canonicalStorefrontPathname(
2465
`${prefix}/${type}/${handle}`,
2566
);
@@ -29,5 +70,17 @@ export async function loader({
2970

3071
response.headers.set("Cache-Control", `max-age=${60 * 60 * 24}`);
3172

73+
if (params.type === "articles") {
74+
// Hydrogen always emits lastmod, even when the source cannot identify a
75+
// duplicate handle's timestamp. Omit that optional tag rather than invent it.
76+
const xml = (await response.text()).replace(
77+
/\s*<lastmod>undefined<\/lastmod>/g,
78+
"",
79+
);
80+
return new Response(xml, {
81+
status: response.status,
82+
headers: response.headers,
83+
});
84+
}
3285
return response;
3386
}

0 commit comments

Comments
 (0)