Htmx & express: beginner question

Hello,

I have a quick question regarding code organization. Currently, I’m using my main page index.html file, which contains only HTML code for the navigation bar. I’m using htmx to dynamically render content based on the selected navigation element on the server side (using express) . As a result, most of my HTML structure, apart from the navigation bar itself, resides in my server.js file.

However, I’m unsure if this approach is the most effective. My index.html file appears quite empty, while my server.js file feels overloaded with code, as it handles not only rendering HTML but also includes additional functionality. As someone new to web development, I’m curious about the typical structure for organizing code in a small web application and how different files can interact with each other.

Any insights or guidance on best practices would be greatly appreciated

Hi,

Instead of embedding HTML directly in your server.js, consider using template engines like Handlebars, EJS, or Pug. This allows you to keep HTML structure in separate files (like templates or views), making them easier to manage and update.

You can also break down your server.js into smaller modules. For instance, routing can be in separate files, and middleware functions can also be modularized.

I wrote a couple of tutorials on creating an app using Express. Maybe these can help.

And more recently:

Happy to discuss if you have any concrete questions.

5 Likes

Or you consider to totally separate frontend and backend and use nodeJS only for backend, while you use another Webserver for the frontend serving your html, css and vanilla js scripts.

1 Like