next.js middleware, NextResponse.redirect() not working when using map or foreach, but it works when using for loops

Viewed 976

//this won't work

rules.filter(rule => rule.type === 'redirect' && new RegExp(rule.rule).exec(pathname.slice(1)))
    .map(rule => { 
        console.log('match');
        const url = req.nextUrl.clone()
        url.pathname = rule.destination
        return NextResponse.redirect(url)
    })

//this does work

for (let rule of rules) { 
        const regex: RegExp = new RegExp(rule.rule)
        if(regex.exec(pathname.slice(1)) && rule.type === 'redirect') {
            console.log('match');
            const url = req.nextUrl.clone()
            url.pathname = rule.destination
            return NextResponse.redirect(url)
          }
        }

the middleware is already running well with de for loop

1 Answers

Reddit gave me the solution, I leave it here

A return statement inside map simply adds to the map output array.

A return statement in a for loop exits the function.

Next.js will redirect if a middleware returns NextResponse.redirect(), as you would if you used a for loop and return statement.

 let result
    rules.filter(rule => rule.type === 'redirect' && new RegExp(rule.rule).exec(pathname.slice(1)))
    .map(rule => {
    console.log('match');
    url.pathname = rule.destination
    result = NextResponse.redirect(url)
    })

return result
Related