Skip to content

Commit

Permalink
Merge pull request #1737 from lumi-tip/development-lumi-8075
Browse files Browse the repository at this point in the history
refactor middleware for redirects
  • Loading branch information
tommygonzaleza authored Dec 12, 2024
2 parents a2c06ab + 15c76fd commit f66a682
Showing 1 changed file with 25 additions and 16 deletions.
41 changes: 25 additions & 16 deletions src/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,32 +17,41 @@ export const config = {
};

async function middleware(req) {
const url = await req.nextUrl.clone();
const url = req.nextUrl.clone();
const { href, origin } = url;
const fullPath = href.replace(origin, '');
let fullPath = href.replace(origin, '');

const localeMatch = fullPath.match(/^\/(es|en|us)(\/|$)/);
const localePrefix = localeMatch ? localeMatch[1] : null;

if (localePrefix) {
fullPath = fullPath.replace(`/${localePrefix}`, '');
}

const aliasAndLessonRedirects = [...aliasRedirects, ...redirectsFromApi];

const currentProject = aliasAndLessonRedirects.find((item) => {
const destinationIsNotEqualToSource = item?.source !== item?.destination;
const normalizedSource = item.source.endsWith('/') ? item.source.slice(0, -1) : item.source;
const normalizedPath = fullPath.endsWith('/') ? fullPath.slice(0, -1) : fullPath;

if (item?.source === fullPath && destinationIsNotEqualToSource) return true;
return false;
return (
normalizedSource === normalizedPath || normalizedSource === `/${localePrefix}${normalizedPath}`
) && item.source !== item.destination;
});

const conditionalResult = () => {
if (currentProject?.type === 'PROJECT-REROUTE' && currentProject?.source) {
return true;
// Evitar redirecciones infinitas
if (currentProject) {
const destinationUrl = `${origin}${currentProject.destination}`;
if (destinationUrl === href) {
log('Middleware: already on destination URL, skipping redirect.');
return NextResponse.next();
}
if (currentProject?.source) {
return true;
}
return false;
};

if (conditionalResult()) {
log(`Middleware: redirecting from ${fullPath}${currentProject?.destination}`);
return NextResponse.redirect(`${origin}${currentProject?.destination || ''}`);
log(`Middleware: redirecting from ${href}${currentProject.destination}`);
return NextResponse.redirect(destinationUrl, 301);
}

return NextResponse.next();
}

export default middleware;

0 comments on commit f66a682

Please sign in to comment.