learnhouse/apps/web/middleware.js

49 lines
No EOL
1.6 KiB
JavaScript

import { NextResponse } from 'next/server';
// This middleware runs on every request
export function middleware(request) {
// Get the current hostname from the request headers
const currentHostname = request.headers.get('host');
// Get the referrer URL if it exists
const referer = request.headers.get('referer');
// If there is a referrer, check if it's from a different domain
if (referer) {
try {
const refererUrl = new URL(referer);
const refererHostname = refererUrl.hostname;
// If the referrer hostname doesn't match the current hostname
if (refererHostname !== currentHostname) {
console.log(`Cross-domain request detected: ${refererHostname} -> ${currentHostname}`);
// For path segments that might include another domain
const url = request.nextUrl.clone();
const path = url.pathname;
// Check if the path includes another domain name (simple check for static files)
if (path.includes('/next/static/') || path.includes('/api/')) {
// Ensure all paths use the current hostname
// This prevents asset URL problems when different hostnames appear in the path
const localPath = path.replace(/https?:\/\/[^\/]+/, '');
url.pathname = localPath;
return NextResponse.rewrite(url);
}
}
} catch (e) {
console.error('Error processing referer in middleware:', e);
}
}
// Continue with the request as normal
return NextResponse.next();
}
// Configure which paths this middleware will run on
export const config = {
matcher: [
// Apply to all paths
'/:path*',
],
};