hono
hono copied to clipboard
set method not working when passing a key and value
What version of Hono are you using?
4.2.1
What runtime/platform is your app running on?
bun
What steps can reproduce the bug?
app.use(async (c, next) => { c.set('message', 'Hono is cool!!') await next() }) app.get("/", (c) => { const message = c.get("message") return c.text(
${message}) })
What is the expected behavior?
It must work fine when passing the key "message" and the value "honor is cool!"
What do you see instead?
underneath the key, I encountered an error: "No overload matches this call. Overload 1 of 2, '(key: never, value: never): void', gave the following error".
Additional information
No response
Hi @hariyebk
It's not a bug. Try to pass the generics to new Hono
:
type Variables = {
message: string
}
const app = new Hono<{
Variables: Variables
}>()
I am having the same issue, Getting Undefined.
import { Hono } from 'hono';
type Variables = string;
export const blogRouter = new Hono<{
Bindings: {
DATABASE_URL: string,
SECRET_URL: string,
},
Variables: {
hello: Variables,
}
}>();
// Setting the variable in a POST request
blogRouter.post('/set', async (c, next) => {
console.log('Hi');
console.log('Setting value...');
c.set('hello', '12343'); // Setting the value as a string
console.log('Value set to:', '12343');
await next();
return c.text('It has come inside');
});
// Retrieving the variable in a GET request
blogRouter.get('/get', async (c) => {
const body = c.get('hello');
console.log('Retrieved value:', body);
return c.text(`The value is: ${body}`);
});
First sent an string, and it was an success.
When getting the hello back, it is coming as undefined
anything that I am doing wrong in here ?, It would be helpful to know.
Hi @SHAIKARSHADA
Variables are kept within the same request. Variables should be .set
and .get
in handlers and middleware that are processed in the same request.
Hey, buddy can't understand 😂 can you help with the code explanation, in your free time.
Hi @SHAIKARSHADA
@EdamAme-x is right. The value of c.set
/c.get
changes with each request. And, c.set('hello', '12345')
does not execute if GET /get
because the routing path is POST /set
.
// This middleware for `POST /set`
blogRouter.post('/set', async (c, next) => {
c.set('hello', '12343') // It's for `POST /set`. It does not effect on `GET /get`
await next()
return c.text('It has come inside')
})