Fix: Prevent build failure from missing menu in _not-found

Resolves a prerendering error for the `/_not-found` page caused by
the Navbar's attempt to fetch a menu that might not exist in the
build environment (e.g., 'next-js-frontend-header-menu').

The `getMenu` function in `lib/shopify/index.ts` has been updated
to catch errors thrown by `shopifyFetch` (such as when the Shopify API
returns an error for a non-existent menu handle). If an error occurs
during menu fetching, it is now logged to the console, and `getMenu`
returns an empty array `[]`.

This allows pages using the Navbar (including `/_not-found`) to build
successfully even if the primary header menu is not found, instead of
failing the entire build process.
This commit is contained in:
google-labs-jules[bot] 2025-05-22 14:33:19 +00:00
parent 6498856d49
commit c8e2bb3cfb

View File

@ -364,26 +364,36 @@ export async function getCollections(): Promise<Collection[]> {
} }
export async function getMenu(handle: string): Promise<Menu[]> { export async function getMenu(handle: string): Promise<Menu[]> {
'use cache'; 'use cache'; // Next.js specific caching directive
cacheTag(TAGS.collections); cacheTag(TAGS.collections); // Next.js specific cache tagging
cacheLife('days'); cacheLife('days'); // Next.js specific cache lifetime
const res = await shopifyFetch<ShopifyMenuOperation>({ try {
query: getMenuQuery, const res = await shopifyFetch<ShopifyMenuOperation>({
variables: { query: getMenuQuery, // getMenuQuery is imported from ./queries/menu
handle variables: {
} handle
}); }
});
return ( // If res.body.data.menu is null or undefined (e.g., menu not found but no explicit API error),
res.body?.data?.menu?.items.map((item: { title: string; url: string }) => ({ // optional chaining will result in undefined, and the `|| []` will correctly return an empty array.
title: item.title, return (
path: item.url res.body?.data?.menu?.items.map((item: { title: string; url: string }) => ({
.replace(domain, '') title: item.title,
.replace('/collections', '/search') path: item.url
.replace('/pages', '') .replace(domain, '') // domain is defined at the top of lib/shopify/index.ts
})) || [] .replace('/collections', '/search')
); .replace('/pages', '')
})) || []
);
} catch (error: any) {
// Log the error for server-side observability.
// During a build process (like for _not-found), this helps identify issues without failing the build.
console.error(`Error fetching menu with handle '${handle}':`, error.message || error);
// Return an empty array to allow the page to render without menu data.
return [];
}
} }
export async function getPage(handle: string): Promise<Page> { export async function getPage(handle: string): Promise<Page> {