State and Decorate

You can extend Elysia to fit your need. This is useful when you need to access extra values in a handler (e.g. a database connection).

In summary:

  • state: assign value to (a global state object of the Elysia instance)
  • decorate: assign value to Context

Context is a parameter in the callback of handler.


  .state("version", 1)
  .decorate("getDate", () =>
  .get("/version", ({ getDate, store: { version } }) => `${version} ${getDate()}`);
  • version is registered using state, and accessible via
  • getDate is registered using decorate, and accessible via Context.getDate.


By providing a function as a first parameters, the callback will accept current value, allowing us to remap the value to anything we like.

        a: "a",
        b: "b"
    // Exclude b state
    .state(({ b, }) => rest)
    .get('/version', ({
        store: { a }
    }) => a


You can type state and decorator explicitly using TypeScript with as:

    // Will type version as `number | null`
    .state('version', 1 as number | null)
    .get('/version', ({
        store: { version }
    }) => version

If the explicit type doesn't type null or undefined, make sure to set strict to true in tsconfig.json:

// tsconfig.json
  "compilerOptions": {
    "strict": true