how to make c.get("jwtPayload") type safe in hono

how to add type to jwt payload in hono js
Solution:
```ts type Variables = { jwtPayload: string } ...
Jump to solution
12 Replies
Solution
Neto
Neto4mo ago
type Variables = {
jwtPayload: string
}

const app = new Hono<{ Variables: Variables }>()

app.use(async (c, next) => {
c.set('jwtPayload', 'something')
await next()
})

app.get('/', (c) => {
const message = c.get('jwtPayload')
return c.text(`The message is "${message}"`)
})
type Variables = {
jwtPayload: string
}

const app = new Hono<{ Variables: Variables }>()

app.use(async (c, next) => {
c.set('jwtPayload', 'something')
await next()
})

app.get('/', (c) => {
const message = c.get('jwtPayload')
return c.text(`The message is "${message}"`)
})
barry
barry4mo ago
Also highly recommend steering clear of the JWT approach Sessions are the way and have always been, JWT's aren't meant for the web
DGCP3
DGCP3OP4mo ago
I'm using jwt with Refresh token tho i have multiple instance of hono that get combined at index , so do i have to pass Variable to every hono instance
Neto
Neto4mo ago
create a function to generate with types
type Variables = {
jwtPayload: string
}


export function baseHono() {
return new Hono<{ Variables: Variables }>()
}

export function protectedHono(){
return baseHono().use(...)
}
type Variables = {
jwtPayload: string
}


export function baseHono() {
return new Hono<{ Variables: Variables }>()
}

export function protectedHono(){
return baseHono().use(...)
}
where you would use new Hono you use baseHono()
DGCP3
DGCP3OP4mo ago
ok, perfect. thank you.
DGCP3
DGCP3OP4mo ago
one more thing i could add protection middleware and call it protectedHono right
Neto
Neto4mo ago
you can change for whatever you want from there idk the exact syntax but you get the point i edited the message for clarity sake
barry
barry4mo ago
Doesn't change anything
Neto
Neto4mo ago
this isnt the point of the question
barry
barry4mo ago
Right, it's advice
Neto
Neto4mo ago
My point is the same
Want results from more Discord servers?
Add your server