How to redirect some URL conditionally in the koa 2

user3552178 picture user3552178 · Sep 12, 2017 · Viewed 10.5k times · Source

This is what i'm thinking, pseudo code.

const myRedirect = (routePath) => {
    newUrl = routePath;
    if (matches condition)
        newUrl = do_some_modification(routePath);       
    return next(newUrl); 
}

const myFunc = (routePath, myRedirect) => (newUrl, middleware) => {
    return (ctx, newUrl, next) => {
        return middleware(ctx, newUrl, next);
    }
};

How to modify it to make it work please ?

Answer

Valera picture Valera · Sep 18, 2017
const route = async function(ctx, next){
    if(shouldRedirect){
        ctx.redirect('/redirect-url'); // redirect to another page
        return;
    }

    ctx.someData = getSomeData(); // ctx.someData will be available in the next middleware
    await next(); // go to next middleware
}