title: Pass value from middleware to view in Koa 2
body: <p>I am trying to get var value from my Koa 2 middleware to display in my pug template (or other).
  For example in koa-sessions I have:</p>
  
  <pre><code>app.use(ctx =&gt; {
    // ignore favicon
    if (ctx.path === '/favicon.ico') return;
  
    let n = ctx.session.views || 0;
    ctx.session.views = ++n; // how can I use this?
    ctx.body = n + ' views'; // works, but in body directly
    ctx.state.views = n + ' views'; // not working
  });
  </code></pre>
  
  <p>Another example, with response time:</p>
  
  <pre><code>app.use(async (ctx, next) =&gt; {
    const start = Date.now();
    ctx.state.start = start
    await next();
    const ms = Date.now() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); // this shows response
    ctx.state.ms = await ms&gt;0 // I have no idea what I'm doing :)
  });
  </code></pre>
  
  <p>As per original instruction this works, but instead of using body/console, I would like to use it as template variable, so in my router/controller I would have:</p>
  
  <pre><code>...
  return ctx.render("posts/index", {
    title: 'Posts',
    posts: posts,
    ms: ctx.state.ms,
    views: ctx.session.views // or views: ctx.state.views
  });
  </code></pre>
  
  <p>None of this works. Is it related to async/await, so it does not get the value in time or it is some syntactic issue? Please be gentle as I am new in this. :)</p>