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();
});
Was this page helpful?