I am using Hono.js for Node.js to build an API. And for serving static file I am using serveStatic middleware.
user.use("/static/*", serveStatic({ root: "./" }));
user.get("/signin", serveStatic({ path: '../public/signin.html'}));
I also tried this -
user.get("/signin", serveStatic({ root: "./", rewriteRequestPath: (path) => path.replace(/^\/signin/, '/public')}));
The signin.html file in under public directory in the root dir. When I am sending a text or json using c.text or c.json, the expected output is shown. Which implies that routing is correct.
But using this code, the output is
<-- GET /user/signin
--> GET /user/signin 404 9ms
Any idea how to solve this ? How to serve files or send files as a response to any request ?
It would seem that by default the serveStatic middleware would match the path starting from the current directory (where the Hono app was started).
I have my Hono app setup like so:
export const app = new Hono()
.use('*', logger())
.get('/static/*', serveStatic({ root: './' })
.get('/', swaggerUI({ url: '/static/openapi.yaml' })
With the following directory structure:

Notice the static folder at the project root.
So that when a request hits up /static/file.json it'll return the file located at the same path.
Here's the end result (if you've got everything setup correctly):

If your directory structure looks like this:
./
├── src
| └── index.ts
|
├── static
| └── image.png
|
└── public
├── sigin.html
└── about.html
Then the code should be:
user.use("/static/*", serveStatic({ root: "./" }));
user.get("/signin", serveStatic({ path: './public/signin.html'}));
It search from the root directory even the index.ts is at the src/ directory. So you won't no need to go up one level serveStatic({ path: '../public/signin.html'}).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With