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
Neto7mo 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
barry7mo 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
DGCP3OP7mo 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
Neto7mo 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
DGCP3OP7mo ago
ok, perfect. thank you.
DGCP3
DGCP3OP7mo ago
one more thing i could add protection middleware and call it protectedHono right
Neto
Neto7mo 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
barry7mo ago
Doesn't change anything
Neto
Neto7mo ago
this isnt the point of the question
barry
barry7mo ago
Right, it's advice
Neto
Neto7mo ago
My point is the same

Did you find this page helpful?