How can I initialize context variables in a Hono web application

252 views Asked by At

Re-Post of https://github.com/orgs/honojs/discussions/1889:

I have a Hono (https://hono.dev/) web application with a ttlCache variable in the context c:

import { serve } from "@hono/node-server"
import { Hono } from "hono"
import TTLCache from "@isaacs/ttlcache"

// How/where can I initialize ttlCache?
const app = new Hono<{ Variables: { ttlCache: TTLCache<string, string> } }>()

// In the route handlers, I will use ttlCache.
app.get("/", (c) => c.text("The TTLCache is " + c.var.ttlCache))

serve(app, (info) => {
  console.log(`Listening on http://localhost:${info.port}`)
})

Not surprising, when I run the app and load http://localhost:3000, I see the response "The TTLCache is undefined".

How can I initialize the ttlCache variable on startup, e.g. to the following value?

new TTLCache({ max: 10000, ttl: 1000 })

(The above is a minimal demo for the problem. In reality I will use ttlCache to store objects...)

1

There are 1 answers

0
Aditya Mathur On

You can initialize it as a global variable, then set the value to your ttlCache variable in the middleware. something like this -

const ttlCache = new TTLCache({ max: 10000, ttl: 1000 });

app.use(async (c, next) => {
  c.set('ttlCache', ttlCache)
  await next()
})

and then for accessing the value

app.get("/", (c) => c.text("The TTLCache is " + c.get("ttlCache")))

You can refer to the docs for more detail - https://hono.dev/api/context#set-get