Hello You! Exercise
Welcome to your first coding challenge! 🚀
In the previous section, you set up a basic Hello World API with Hono.js that returns Hello Hono! when you visit the root endpoint. Now, let’s make it more interactive and personal.
Objective
Section titled “Objective”Modify your Hono.js application to accept a name query parameter and return a personalized greeting. For example:
- Visiting
http://localhost:8787/?name=Ehtishamshould return: Hello Ehtisham! - Visiting
http://localhost:8787/?name=Worldshould return: Hello World! - Visiting
http://localhost:8787/(without name) should return: Hello Hono! (as a fallback)
- Open your
src/index.ts(or the main file created by the Hono template). - Modify the route handler to read the
namequery parameter. - Use the parameter to customize the greeting, with a default fallback.
💡 Click to reveal hint (but try solving it first!)
Here’s how you can modify your code:
import { Hono } from "hono";
const app = new Hono();
app.get("/", (c) => { const name = c.req.query("name") || "Hono"; return c.text(`Hello ${name}!`);});
export default app;The key changes:
- Use
c.req.query('name')to get the query parameter - Provide a default value with
|| 'Hono' - Interpolate the name into the greeting string
Testing
Section titled “Testing”Once you’ve made the changes:
- Save the file
- Run
bun run dev(if not already running) - Test different URLs in your browser:
http://localhost:8787/http://localhost:8787/?name=YourNamehttp://localhost:8787/?name=Trainer
Next Steps
Section titled “Next Steps”Great job! You’ve just learned how to handle query parameters in Hono.js. This is the foundation for building more dynamic APIs. In the coming sections, we’ll explore more advanced routing and request handling.
Remember: Coding is about experimentation. Don’t be afraid to try different approaches and learn from the process!