import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; /** * PRODUCTION STABILIZATION MIDDLEWARE * This middleware handles legacy asset routing for the KLZ showcase, * ensuring assets are correctly mapped regardless of Next.js config wrapper behavior. */ export function middleware(request: NextRequest) { const { pathname } = request.nextUrl; // 2. Legacy Showcase Asset Mapping // Handles: // - Global assets (/wp-content/*, /wp-includes/*, /assets/*) // - Showcase-specific resources (/case-studies/klz-cables/index.html, etc.) // Normalize pathname to ensure we're matching correctly const path = pathname; // Map Pattern 2: Showcase-prefixed assets (used for relative links within the showcase) const showcaseMatch = path.match(/^\/(?:case-studies|work|blog)\/([^\/]+)\/(.*)/); if (showcaseMatch) { const [, slug, remainingPath] = showcaseMatch; // Safety: Only rewrite if it looks like a static asset (has extension) // or belongs to known legacy folders. This prevents catching Next.js routes. if (remainingPath.match(/\.(?:html|php|js|css|png|jpg|jpeg|svg|gif|webp|woff2?|ttf|pdf|json|xml)$/) || remainingPath.includes('wp-content/') || remainingPath.includes('wp-includes/') || remainingPath.includes('assets/')) { // Normalize slug: klz-cables -> klz-cables.com (literal folder name) const directory = slug === 'klz-cables' ? 'klz-cables.com' : slug; // If the remaining path already starts with assets/directory, don't double it const targetPath = remainingPath.startsWith(`assets/${directory}/`) ? `/${remainingPath}` : `/${remainingPath}`; return NextResponse.rewrite(new URL(`/showcase/${directory}${targetPath}`, request.url)); } } return NextResponse.next(); } // Optimization: Only run middleware for legacy asset paths to minimize overhead export const config = { matcher: [ '/wp-content/:path*', '/wp-includes/:path*', '/assets/:path*', '/case-studies/:path*', '/work/:path*', '/blog/:path*', ], };