Ensuring Type Safety and Handling Optional JWT Fields in Hono Middleware
Assume I have a middleware created with createMiddleware, which extracts JWT from a cookie and decodes it. After this simple logic, the payload 100% exists. As I've understood from the docs, to pass it further to a handler, I need to use .set('name', value). To add type-safety, I've read that Variables are made for that.
First Question:
Where do I need to pass these variables? In the root Hono instance of my project?
Second Question:
In my payload, there could be some values that can be null. For example, each user has an ID (which is always present), but not every user has an adminId. How do I achieve type safety in another middleware which checks if adminId is present, and if not, sends a 403 response? Furthermore, in the handler, how can I ensure that adminId will be a string and never undefined?
That's my basic decode middleware:
4 Replies
For your first question. You need to use type generics and pass it to every Hono instance that is going to use those variables. Alternatively you can ContextVariableMap
https://hono.dev/api/context#contextvariablemap
Context - Hono
Ultrafast web framework for Cloudflare Workers, Fastly Compute, Deno, Bun, Vercel, Node.js, and others. Fast, but not only fast.
Here is an example of that in a project
https://github.com/NicoPlyley/hono-auth/blob/main/src/app.d.ts
GitHub
hono-auth/src/app.d.ts at main · NicoPlyley/hono-auth
An example app with authentication using Hono, Drizzle, and D1. Running on CF Workers - NicoPlyley/hono-auth
For the second you can also do what I did and declare global types for your JWT and do this:
const jwt = decode as MyJWTType
replace decode with your decoding function and the Type with whatever the name of the type is you setTha'ts a huge thanks!