From e44c8c234630c9cbf18e8f1c5c516bfc97b74c1f Mon Sep 17 00:00:00 2001 From: Harsh Date: Sat, 11 Oct 2025 22:38:14 +0530 Subject: [PATCH 1/2] Prevent breaking external links --- src/middleware.ts | 36 ++++++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/src/middleware.ts b/src/middleware.ts index de792d71e2..c959e3a064 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -39,13 +39,11 @@ export async function onRequest( currentLocale = pathSegments[0]; } - let modifiedHtml = html; - - // If we have a currentLocale, modify the HTML to ensure all links - // have the correct locale prefix - if (currentLocale) { - modifiedHtml = ensureCorrectLocalePrefixesInHtmlLinks(html, currentLocale); - } + // Process HTML links to normalize external URLs and add locale prefixes when applicable + const modifiedHtml = ensureCorrectLocalePrefixesInHtmlLinks( + html, + currentLocale, + ); // Return a new Response with the modified HTML return new Response(modifiedHtml, { @@ -56,7 +54,7 @@ export async function onRequest( export const ensureCorrectLocalePrefixesInHtmlLinks = ( html: string, - currentLocale: string, + currentLocale?: string, ) => { const $ = load(html); @@ -65,13 +63,23 @@ export const ensureCorrectLocalePrefixesInHtmlLinks = ( $("a").each(function () { let href = $(this).attr("href"); // Skip if href is undefined, an external link, or written with a dot slash - if ( - !href || - href.startsWith("http") || - href.startsWith("./") || - href.startsWith("#") - ) + if (!href || href.startsWith("./") || href.startsWith("#")) return; + + // Remove trailing slashes from external/absolute URLs (like Wikipedia) + // to prevent breaking external links + if (href.startsWith("http")) { + try { + const urlObj = new URL(href); + // Only remove trailing slash if the path is not just "/" + if (href.endsWith("/") && urlObj.pathname !== "/") { + href = href.slice(0, -1); + $(this).attr("href", href); + } + } catch (e) { + // If URL parsing fails, leave the href unchanged + } return; + } const startsWithLocale = nonDefaultSupportedLocales.some( (locale) => href && href.startsWith(`/${locale}/`), From e9c47c4fb46d45cfab38543d0350c973b1f1fd68 Mon Sep 17 00:00:00 2001 From: harsh kumar <135993950+hxrshxz@users.noreply.github.com> Date: Sat, 11 Oct 2025 23:05:34 +0530 Subject: [PATCH 2/2] Update src/middleware.ts Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/middleware.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/middleware.ts b/src/middleware.ts index c959e3a064..2036a1e165 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -76,7 +76,8 @@ export const ensureCorrectLocalePrefixesInHtmlLinks = ( $(this).attr("href", href); } } catch (e) { - // If URL parsing fails, leave the href unchanged + // If URL parsing fails, log the error and leave the href unchanged + console.error(`Failed to parse URL in tag href: "${href}". Error:`, e); } return; }