Redirection is a must-have feature for any web application. In this post, we will learn how to setup Koa JS Redirect URL.

But why is redirection so important?

What if your application client requests for a malformed URL? Also, what if there are some errors on your server and we want to show some error page to the users while we fix the errors?

In the above cases, redirection is the best solution. Moreover, redirection can also be used to keep people out of your website’s restricted areas.

If you are new to KoaJS, I suggest you begin with the post about getting started with KoaJS.

1 – Creating a Koa JS Redirect functionality

Let us look at an example where we implement the redirect functionality.

const koa = require('koa');
const Router = require('koa-router');

const app = new koa();
const router = new Router();

router.get('/greeting', (ctx, next) => {
  ctx.status = 200;
  ctx.body = "Request has been received";
});

router.get('/not-found', (ctx, next) => {
  ctx.status = 404;
  ctx.body = "Sorry, this page is not present";
})

function handle404error(ctx, next) {
  if (404 != ctx.status) return;
  ctx.redirect('/not-found');
}

app.use(router.routes())
app.use(handle404error);

app.listen(3000, function(){
   console.log('Server running on https://localhost:3000')
});

Here, we implement an endpoint /greeting using the koa-router. Basically, this is just an ordinary endpoint that returns a status code of 200 and a message.

Next, we have another endpoint /not-found. In the callback for this endpoint, we return a status code of 404 with another message. This is basically our error page.

Now, to make this error page work for us, we create another method handle404error(). This is nothing but a middleware function. It takes the KoaJS context as input and checks whether the status code is not 404. If the status code is 404, it calls the redirect() method to the /not-found endpoint. Note that the redirect() method is available as part of the context (or ctx) object.

Once we have setup the methods and routes, we attach them to the application instance using app.use(). Finally, we start the server on port 3000.

Now, if we start the application and trigger the /greeting message, we get a status code of 200 and the request acknowledgement. On the other hand, if we trigger any other endpoint such /test, we instead get redirected to the /not-found message. In other words, the redirection using Koa JS redirect URL works as expected.

Conclusion

With this, we have successfully implemented redirection in our KoaJS application. We made use of the redirect() function available as part of the context object.

If you have any comments or queries about this post, please feel free to mention them in the comments section below.

Categories: BlogKoaJS

0 Comments

Leave a Reply

Your email address will not be published.