From bc9b9401e4f3bb83200893af57f8bc6b022e94d1 Mon Sep 17 00:00:00 2001 From: Stivenjs Date: Wed, 4 Jun 2025 20:22:34 -0500 Subject: [PATCH 1/3] refactor(middleware): enhance subdomain handling and URL rewriting logic This commit updates the middleware to detect subdomains in both production and development environments. It implements URL rewriting to redirect users to the appropriate store page based on the detected subdomain, improving navigation and user experience. Additionally, the matcher configuration has been simplified to exclude specific paths, streamlining route handling. --- app/[store]/page.tsx | 14 ++++++++++++++ middleware.ts | 43 +++++++++++++++++++++++++++++++++++-------- 2 files changed, 49 insertions(+), 8 deletions(-) create mode 100644 app/[store]/page.tsx diff --git a/app/[store]/page.tsx b/app/[store]/page.tsx new file mode 100644 index 00000000..c915d28f --- /dev/null +++ b/app/[store]/page.tsx @@ -0,0 +1,14 @@ +'use client' + +import { useParams } from 'next/navigation' + +export default function StorePage() { + const params = useParams() + const store = params.store + + return ( +
+

Tienda: {store}

+
+ ) +} diff --git a/middleware.ts b/middleware.ts index aa816b53..b862de63 100644 --- a/middleware.ts +++ b/middleware.ts @@ -8,6 +8,40 @@ import { handleCollectionOwnershipMiddleware } from './middlewares/ownership/col export async function middleware(request: NextRequest) { const path = request.nextUrl.pathname + const hostname = request.headers.get('host') || '' + + // Configuración de dominios + const isProduction = process.env.NODE_ENV === 'production' + + // Detectar subdominios + let subdomain = '' + if (isProduction) { + // En producción: verificar si hay un subdominio (ej: tienda.fasttify.com) + const parts = hostname.split('.') + if (parts.length > 2 && hostname.endsWith('fasttify.com')) { + subdomain = parts[0] + } + } else { + // En desarrollo: usar el formato subdominio.localhost:3000 o localhost:3000 + if (hostname.includes('.localhost')) { + subdomain = hostname.split('.')[0] + } + } + + // Si hay un subdominio y estamos en la raíz, reescribir a la ruta de la tienda + if (subdomain && subdomain !== 'www' && path === '/') { + // Reescribir la URL para mostrar la página de la tienda + const url = request.nextUrl.clone() + url.pathname = `/${subdomain}` + return NextResponse.rewrite(url) + } + + // Si hay un subdominio y la ruta no empieza con el subdominio, agregar el prefijo + if (subdomain && subdomain !== 'www' && !path.startsWith(`/${subdomain}`)) { + const url = request.nextUrl.clone() + url.pathname = `/${subdomain}${path}` + return NextResponse.rewrite(url) + } // Verificar propiedad de productos específicos if ( @@ -45,12 +79,5 @@ export async function middleware(request: NextRequest) { } export const config = { - matcher: [ - '/subscription-success', - '/account-settings', - '/first-steps', - '/my-store', - '/login', - '/store/:path*', - ], + matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'], } From 742105b7d1400a2ab6af19c1fe64a0b59effd9f9 Mon Sep 17 00:00:00 2001 From: Steven Jaime <143671152+Stivenjs@users.noreply.github.com> Date: Wed, 4 Jun 2025 20:26:03 -0500 Subject: [PATCH 2/3] Potential fix for code scanning alert no. 6: Incomplete URL substring sanitization Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> --- middleware.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/middleware.ts b/middleware.ts index b862de63..244ced07 100644 --- a/middleware.ts +++ b/middleware.ts @@ -17,9 +17,11 @@ export async function middleware(request: NextRequest) { let subdomain = '' if (isProduction) { // En producción: verificar si hay un subdominio (ej: tienda.fasttify.com) - const parts = hostname.split('.') - if (parts.length > 2 && hostname.endsWith('fasttify.com')) { - subdomain = parts[0] + const allowedDomains = ['fasttify.com', 'www.fasttify.com']; + const parts = hostname.split('.'); + const domain = parts.slice(-2).join('.'); + if (parts.length > 2 && allowedDomains.includes(domain)) { + subdomain = parts[0]; } } else { // En desarrollo: usar el formato subdominio.localhost:3000 o localhost:3000 From 584f552b9d725babd84a0948761c85d8304a4e20 Mon Sep 17 00:00:00 2001 From: Stivenjs Date: Wed, 4 Jun 2025 20:42:58 -0500 Subject: [PATCH 3/3] refactor(middleware): improve subdomain extraction and URL rewriting logic This commit refactors the middleware to enhance the subdomain extraction process and streamline URL rewriting based on detected subdomains. It introduces a dedicated function for subdomain extraction, improving code clarity and maintainability. Additionally, it updates the URL rewriting logic to handle root paths and ensure proper redirection for valid hostnames, enhancing user navigation. --- app/[store]/page.tsx | 6 ++++- middleware.ts | 60 ++++++++++++++++++++++++++++---------------- 2 files changed, 43 insertions(+), 23 deletions(-) diff --git a/app/[store]/page.tsx b/app/[store]/page.tsx index c915d28f..ff34a94e 100644 --- a/app/[store]/page.tsx +++ b/app/[store]/page.tsx @@ -4,7 +4,11 @@ import { useParams } from 'next/navigation' export default function StorePage() { const params = useParams() - const store = params.store + const store = (params.store as string) || undefined + + if (!store) { + return
No se encontró la tienda
+ } return (
diff --git a/middleware.ts b/middleware.ts index b862de63..5a647796 100644 --- a/middleware.ts +++ b/middleware.ts @@ -13,33 +13,49 @@ export async function middleware(request: NextRequest) { // Configuración de dominios const isProduction = process.env.NODE_ENV === 'production' - // Detectar subdominios - let subdomain = '' - if (isProduction) { - // En producción: verificar si hay un subdominio (ej: tienda.fasttify.com) - const parts = hostname.split('.') - if (parts.length > 2 && hostname.endsWith('fasttify.com')) { - subdomain = parts[0] - } - } else { - // En desarrollo: usar el formato subdominio.localhost:3000 o localhost:3000 - if (hostname.includes('.localhost')) { - subdomain = hostname.split('.')[0] - } + const allowedDomains = isProduction ? ['fasttify.com'] : ['localhost'] + const isValidHostname = allowedDomains.some( + domain => hostname === domain || hostname.endsWith(`.${domain}`) + ) + + // Si el hostname es válido, redirigir a la landing + + if (isValidHostname) { + return NextResponse.redirect(new URL('/', request.url)) } - // Si hay un subdominio y estamos en la raíz, reescribir a la ruta de la tienda - if (subdomain && subdomain !== 'www' && path === '/') { - // Reescribir la URL para mostrar la página de la tienda - const url = request.nextUrl.clone() - url.pathname = `/${subdomain}` - return NextResponse.rewrite(url) + // Detectar subdominios + const extractSubdomain = (hostname: string, isProduction: boolean): string => { + const cleanHostname = hostname.split(':')[0] // Remove port if present + const parts = cleanHostname.split('.') + if (isProduction) { + // En producción: verificar si hay un subdominio (ej: tienda.fasttify.com) + if (parts.length > 2 && cleanHostname.endsWith('fasttify.com')) { + return parts[0] + } + } else { + // En desarrollo: usar el formato subdominio.localhost:3000 + if (parts.length > 1 && cleanHostname.endsWith('localhost')) { + return parts[0] + } + } + return '' } + const subdomain = extractSubdomain(hostname, isProduction) - // Si hay un subdominio y la ruta no empieza con el subdominio, agregar el prefijo - if (subdomain && subdomain !== 'www' && !path.startsWith(`/${subdomain}`)) { + // Reescribir URLs basadas en subdominios + if (subdomain && subdomain !== 'www') { const url = request.nextUrl.clone() - url.pathname = `/${subdomain}${path}` + if (path === '/') { + // Si estamos en la raíz, reescribir a la ruta de la tienda + url.pathname = `/${subdomain}` + } else if (!path.startsWith(`/${subdomain}`)) { + // Si la ruta no empieza con el subdominio, agregar el prefijo + url.pathname = `/${subdomain}${path}` + } else { + // La ruta ya tiene el prefijo correcto + return NextResponse.next() + } return NextResponse.rewrite(url) }