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:
import { createMiddleware } from "hono/factory";
import { getCookie } from "hono/cookie";
import { verify } from "hono/jwt";

export const authMiddleware = createMiddleware(async (c, next) => {
const token = getCookie(c, "dekada_access");
if (!token) {
return c.json({ success: false, message: "Unauthorized" }, 401);
}

const payload = await verify(token, Bun.env.ACCESS_TOKEN_SECRET!);
if (!payload) {
return c.json({ success: false, message: "Unauthorized" }, 401);
}

await next();
});
import { createMiddleware } from "hono/factory";
import { getCookie } from "hono/cookie";
import { verify } from "hono/jwt";

export const authMiddleware = createMiddleware(async (c, next) => {
const token = getCookie(c, "dekada_access");
if (!token) {
return c.json({ success: false, message: "Unauthorized" }, 401);
}

const payload = await verify(token, Bun.env.ACCESS_TOKEN_SECRET!);
if (!payload) {
return c.json({ success: false, message: "Unauthorized" }, 401);
}

await next();
});
4 Replies
Nico
Nico6mo ago
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.
Nico
Nico6mo ago
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
Nico
Nico6mo ago
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 set
kapitalist (Назар)
Tha'ts a huge thanks!
Want results from more Discord servers?
Add your server