I am trying to serve static frontend only react apps through bun and using hono for framework. My code for server is :
import { Hono } from "hono";
import { cors } from "hono/cors";
import { serveStatic } from "hono/bun";
const app = new Hono();
// Config
app.use(
cors({
origin: ["http://localhost", "https://localhost"],
allowMethods: ["GET", "POST"],
exposeHeaders: ["Content-Type"],
maxAge: 300,
})
);
// Static paths
app.use("/assets/*", serveStatic({ root: "../dist/links/assets/" }));
app.use(
"/portfolio/assets/*",
serveStatic({ root: "../dist/portfolio/assets/" })
);
// Routes
app.get("/", serveStatic({ path: "../dist/links/index.html" }));
app.get(
"/portfolio",
serveStatic({
path: "../dist/portfolio/index.html",
}),
);
// Start server
try {
const server = Bun.serve({
fetch: app.fetch,
port: process.env.PORT || 3000,
});
console.log("Server started on port : ", server.port);
} catch (e) {
console.error("Error occured while starting the server : ", e);
}
My directory structure is like : enter image description here
I tried everything. Litterally every relative and absolute path possible. I used path.resolve(). It still wont serve the static files. Please help its frustrating. The docs are of no help at all.
My understanding is that the paths used for serving static files are relative to project root (i.e., wherever you're calling bun run ...
).
I copy/pasted your code into the index file of a simple project:
/src
- /index.ts
/dist
- /links
- /index.html
and updated the static file paths accordingly:
// serveStatic({ path: '../dist/links/index.html' })
app.get(
'/',
serveStatic({ path: './dist/links/index.html' }),
);
After updating the paths, I was able to visit the served pages without issue. I'm not entirely sure how this translates to your project setup, but static serving does work with bun@1.2.3
and hono@4.7.4
.