Search code examples
httpskoa

Koajs: How to check current connection is over https or not?


I am using koajs, I have a router like the following and I want to detect if user is requesting via https, how can I achieve it?

router.get('/video', function(next){
  if(request is over https) {
      this.body = yield render('/video', {});
  } else {
      this.redirect('https://example.com/video');
  }
});


Solution

  • You can use secure which is attached to the context's request object. It's also aliased onto the ctx itself.

    Koa v1:

    router.get('/video', function *(next) {
      if (this.secure) {
        // The request is over https
      }
    })
    

    Koa v2:

    router.get('/video', async (ctx, next) => {
      if (ctx.secure) {
        // The request is over https
      }
    })
    

    ctx.secure is equivalent to checking that ctx.protocol === "https".

    This is all mentioned in the Koa website docs, I would definitely recommend checking there first whenever you have a Koa-related question.