JavaDad
JavaDad
Explore posts from servers
HHono
Created by JavaDad on 4/10/2024 in #help
Typing Middleware JWT and others
Currently I am trying to type the c.get('jwtPayload') that is documented here. I have tried using the method described here in a global.d.ts file but this does not seem to take any affect, the jwtPayload get result is still typed as any. Currently I have removed the global.d.ts file and set types on the Hono instance instead so its more explicit. This is still not working for the jwtPayload (and other values I use in middelware like the oauth middleware):
// controller.ts
const app = new Hono<{ Bindings: Bindings; Variables: Variables }>();

app.use("/*", async (c, next) => {
const jwtMiddleware = jwt({
secret: c.env.JWT_SECRET,
});
return jwtMiddleware(c, next);
});

app.use("/*", async (c, next) => {
const jwtPayload = c.get("jwtPayload") as JWTPayload; // without cast is any
if (jwtPayload.role < Role.MANAGER) {
throw error(401, "Unauthorized");
}
});

app.get("/:id", async ({ get, env, req, json }) => {
const { id } = get("jwtPayload") as JWTPayload; // without cast is any
// More code below
// ...
});

// ===========================================

// auth.ts
app.post("/auth", async(c) => {
// Verification of google oauth omitted
// ...

// Once user is authed
const newUserToken = await sign({
id: user.id,
email: user.email,
name: user.name,
profilePicture: user.profilePicture,
role: user.role,
},
env.JWT_SECRET,
);

// Code that returns JWT to client to be included in Authorization header on subsequent requests
// ...
});
// controller.ts
const app = new Hono<{ Bindings: Bindings; Variables: Variables }>();

app.use("/*", async (c, next) => {
const jwtMiddleware = jwt({
secret: c.env.JWT_SECRET,
});
return jwtMiddleware(c, next);
});

app.use("/*", async (c, next) => {
const jwtPayload = c.get("jwtPayload") as JWTPayload; // without cast is any
if (jwtPayload.role < Role.MANAGER) {
throw error(401, "Unauthorized");
}
});

app.get("/:id", async ({ get, env, req, json }) => {
const { id } = get("jwtPayload") as JWTPayload; // without cast is any
// More code below
// ...
});

// ===========================================

// auth.ts
app.post("/auth", async(c) => {
// Verification of google oauth omitted
// ...

// Once user is authed
const newUserToken = await sign({
id: user.id,
email: user.email,
name: user.name,
profilePicture: user.profilePicture,
role: user.role,
},
env.JWT_SECRET,
);

// Code that returns JWT to client to be included in Authorization header on subsequent requests
// ...
});
23 replies