From c8e2bb3cfbf4d6baf12bb4ab5f0cba270a86e06a Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Thu, 22 May 2025 14:33:19 +0000 Subject: [PATCH] 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. --- lib/shopify/index.ts | 46 +++++++++++++++++++++++++++----------------- 1 file changed, 28 insertions(+), 18 deletions(-) diff --git a/lib/shopify/index.ts b/lib/shopify/index.ts index b90893172..0da7095c2 100644 --- a/lib/shopify/index.ts +++ b/lib/shopify/index.ts @@ -364,26 +364,36 @@ export async function getCollections(): Promise { } export async function getMenu(handle: string): Promise { - 'use cache'; - cacheTag(TAGS.collections); - cacheLife('days'); + 'use cache'; // Next.js specific caching directive + cacheTag(TAGS.collections); // Next.js specific cache tagging + cacheLife('days'); // Next.js specific cache lifetime - const res = await shopifyFetch({ - query: getMenuQuery, - variables: { - handle - } - }); + try { + const res = await shopifyFetch({ + query: getMenuQuery, // getMenuQuery is imported from ./queries/menu + variables: { + handle + } + }); - return ( - res.body?.data?.menu?.items.map((item: { title: string; url: string }) => ({ - title: item.title, - path: item.url - .replace(domain, '') - .replace('/collections', '/search') - .replace('/pages', '') - })) || [] - ); + // If res.body.data.menu is null or undefined (e.g., menu not found but no explicit API error), + // optional chaining will result in undefined, and the `|| []` will correctly return an empty array. + return ( + res.body?.data?.menu?.items.map((item: { title: string; url: string }) => ({ + title: item.title, + path: item.url + .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 {