Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serve static files in Node.js using Hono.js?

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 ?

like image 720
wormhole Avatar asked Oct 24 '25 06:10

wormhole


2 Answers

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:

The directory structure printed by ls.

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):

Browser making a request

like image 186
Adophilus Avatar answered Oct 25 '25 20:10

Adophilus


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'}).

like image 44
Tun Tun Aung Avatar answered Oct 25 '25 21:10

Tun Tun Aung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!