H
Honoโ€ข7mo ago
rahmat

Custom jwt middleware

I want to check whether the user exists in the database based on the ID that I took from the sub payload using JWT middleware. Anyone can help me for the example code?
5 Replies
Nico
Nicoโ€ข7mo ago
It really depends on the database you are using. Here is an example of an JWT Auth middleware https://github.com/NicoPlyley/hono-auth/blob/main/src/middleware/protect.ts
GitHub
hono-auth/src/middleware/protect.ts at main ยท NicoPlyley/hono-auth
An example app with authentication using Hono, Drizzle, and D1. Running on CF Workers - NicoPlyley/hono-auth
rahmat
rahmatOPโ€ข7mo ago
thanks bro, but I mean can we create a middleware that extends with the built-in jwt middleware? So we can use c.get('jwtPayload') to get sub payload instead of write the code from line 11 to 26
Nico
Nicoโ€ข7mo ago
As far as extending it directly I don't think so. But you can write another middleware to just do the database check
import { Hono } from 'hono'
import {createMiddleware} from "hono/factory";

const app = new Hono()

const mw1 = createMiddleware(async(_, next) => {
console.log('MW1 Running');
await next();
})

const mw2 = createMiddleware(async(_, next) => {
console.log('MW2 Running');
await next();
})

const myCustomMiddleware = [mw1, mw2]

app.get('/', ...myCustomMiddleware, (c) => {
return c.text('Hello Hono!')
});

export default app
import { Hono } from 'hono'
import {createMiddleware} from "hono/factory";

const app = new Hono()

const mw1 = createMiddleware(async(_, next) => {
console.log('MW1 Running');
await next();
})

const mw2 = createMiddleware(async(_, next) => {
console.log('MW2 Running');
await next();
})

const myCustomMiddleware = [mw1, mw2]

app.get('/', ...myCustomMiddleware, (c) => {
return c.text('Hello Hono!')
});

export default app
You can do something like this to make it into one middleware as well. That way you don't have to define two each time
rahmat
rahmatOPโ€ข7mo ago
Why didn't I think of combining them into an array? ๐Ÿ˜๐Ÿ˜… thanks bro
Nico
Nicoโ€ข7mo ago
No problem!
Want results from more Discord servers?
Add your server