Deno nuggets: Using context state in Oak

Mayank C
Tech Tonic

--

This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.

Problem

How to use state to save variables for an HTTP transaction?

Solution

Oak comes with a context state that can be used to save variables that pertain to the HTTP transaction. The context state is like passing data to all places wherever the context object goes. The context state is a simple KV store. A use case will help to understand it better.

Let’s say we want to add a request timestamp & a unique request ID to the HTTP transaction. Both of these are useful in logging correlation. This kind of data can be added to the context state so that it is available everywhere the context is available. Here is an example:

import { Application } from "https://deno.land/x/oak/mod.ts";const app = new Application();app.use(async (ctx, next) => {
ctx.state.reqId = crypto.randomUUID();
ctx.state.reqTime = Date.now();
next();
});
app.use((ctx) => {
ctx.response.body = "Hello world!";
console.log("ReqId:", ctx.state.reqId, ", ReqTime:", ctx.state.reqTime);
});
await app.listen({ port: 8080 });

Here is a quick run:

> curl http://localhost:8080
Hello world!
> deno run --allow-net app.ts
ReqId: 497551b8-5d2e-45c8-8b39-245250d10cfa , ReqTime: 1659851762350

--

--