Skip to content

app.context.state - reset on each request? #1172

@ConnorWiseman

Description

@ConnorWiseman

Good morning!

While tinkering with a side project, I attempted to set some global initial values in app.context.state only to discover in koa/application.js:176 that this particular property is reset every time a new context object is created.

Is this behavior intentional?

My use case was to count a number of database queries and total database response time spanning any number of middleware functions with initial values of 0. Eventually, I would like to pass that information (and more besides) back to some view, which is what ctx.state is recommended for. It would have been convenient to cram those into app.context.state, but it isn't currently possible.

Alternatives seem to include using another middleware function at the start of my middleware stack to pad each ctx object with the properties I'd like to add, or else adding any such properties elsewhere on app.context and building my response objects by hand when I need to.

I can't tell if my approach is an awkward one or if I'm just being lazy. Advice would be appreciated!

Sample code:

// "koa": "^2.5.0"
const Koa = require('koa');

let app = new Koa();

// property state does not yet exist
app.context.state = {};
app.context.state.external = true;

app.use((ctx, next) => {
  ctx.state.internal = true;
  next();
});

app.use((ctx) => {
  ctx.body = ctx.state;
});

app.listen(3000);

Expected response:

{
  "external": true,
  "internal": true
}

Actual response:

{
  "internal": true
}

Related resources:

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions