Skip to content

fix(middleware): Will now properly send the user to 404 #362

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
17 changes: 14 additions & 3 deletions src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@ async function getRegionMap() {
},
}).then((res) => res.json())

if (!regions) {
notFound()
if (!Array.isArray(regions) || regions.length <= 0) {
// It is not possible to use notfound() in middleware
throw new Error("Regions not found")
}

// Create a map of country codes to regions.
Expand Down Expand Up @@ -70,6 +71,10 @@ async function getCountryCode(
countryCode = regionMap.keys().next().value
}

if (!countryCode) {
throw new Error("No country code found")
}

return countryCode
} catch (error) {
if (process.env.NODE_ENV === "development") {
Expand All @@ -91,7 +96,13 @@ export async function middleware(request: NextRequest) {
const onboardingCookie = request.cookies.get("_medusa_onboarding")
const cartIdCookie = request.cookies.get("_medusa_cart_id")

const regionMap = await getRegionMap()
let regionMap: Awaited<ReturnType<typeof getRegionMap>>
try {
regionMap = await getRegionMap()
} catch (error) {
// If no region map is found, we can't continue - send the user to 404
return NextResponse.error()
}

const countryCode = regionMap && (await getCountryCode(request, regionMap))

Expand Down