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
Neto6mo 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
barry6mo 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
DGCP3OP6mo 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
Neto6mo 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
DGCP3OP6mo ago
ok, perfect. thank you.
DGCP3
DGCP3OP6mo ago
one more thing i could add protection middleware and call it protectedHono right
Neto
Neto6mo 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
barry6mo ago
Doesn't change anything
Neto
Neto6mo ago
this isnt the point of the question
barry
barry6mo ago
Right, it's advice
Neto
Neto6mo ago
My point is the same
Want results from more Discord servers?
Add your server