import { serve } from "bun";import { Hono } from "hono";import index from "./index.html"; // HTML templateimport API from "./api"; // Router API
const app = new Hono();
app.route("/api/", API); // Tất cả route API dưới /api/
const server = serve({ routes: { "/api/*": app.fetch, // Xử lý API trước "/*": index, // Phục vụ React app cho các path còn lại }, development: process.env.NODE_ENV !== "production" && { hmr: true, console: true, },});
console.log(`🚀 Server running at ${server.url}`);
const server = serve({ routes: { "/api/users": { async GET(req) { return Response.json({ users: [...] }); }, }, "/*": index, },});
import { Hono } from "hono";import { jsx } from "hono/jsx";
const app = new Hono();
app.get("/", (c) => { return c.html(<h1>Hello Hono!</h1>);});
├── index.ts # File server chính├── main.tsx # Entry React app├── index.html # Template HTML├── app/│ └── App.tsx # Component React chính├── api/│ ├── index.ts # Router API chính│ └── v1/│ └── index.ts # Các route API phiên bản 1
import { Hono } from "hono";import V1Routes from "./v1";
const API = new Hono();
API.route("/v1/", V1Routes);
export default API;
import { Hono } from "hono";
const V1Routes = new Hono();
V1Routes.get("/", (c) => c.json({ message: "Welcome to V1" }));
V1Routes.get("/books", (c) => c.json({ books: [ { id: 1, title: "The Great Gatsby", author: "F. Scott Fitzgerald" }, { id: 2, title: "To Kill a Mockingbird", author: "Harper Lee" }, { id: 3, title: "1984", author: "George Orwell" }, ], }));
V1Routes.get("/users", (c) => c.json({ users: [ { id: 1, name: "John Doe", email: "[email protected]" }, { id: 2, name: "Jane Smith", email: "[email protected]" }, ], }));
export default V1Routes;
app.route()
, đường dẫn cần có dấu gạch chéo /api/
để hoạt động chính xác:app.route("/api/", API); // ✅app.route("/api", API); // ❌ Không hoạt động đúng
react-router-dom
:bun add react-router-dom
App.tsx
:import { BrowserRouter, Routes, Route } from "react-router-dom";
function App() { return ( <BrowserRouter> <Routes> <Route path="/" element={<Home />} /> <Route path="/about" element={<About />} /> <Route path="/books" element={<Books />} /> <Route path="*" element={<NotFound />} /> </Routes> </BrowserRouter> );}
"/*": index
nên mọi đường dẫn frontend đều tải React app, React Router sẽ xử lý navigation.Tính Năng | Mô Tả |
---|---|
API endpoint | Tại /api/v1/books , /api/v1/users với Hono mạnh mẽ |
React frontend | Phục vụ từ / với đầy đủ client-side routing |
Hot Module Replacement (HMR) | Thay đổi code React ngay lập tức không cần refresh |
Single process | Chạy API và frontend trên cùng một server do Bun xử lý |
Type-safe | Hỗ trợ TypeScript đồng bộ cho cả frontend/backend |
Hệ sinh thái React đa dạng | Dùng Tailwind CSS, shadcn/ui và hàng ngàn thư viện React khác |
Middleware | Hono cung cấp middleware cho auth, CORS, logging, validation,... |