How do I use HTML as the view engine in Express?
Up and running quickly with Express.js? I got you. You don't need a fancy template engine; just tell Express to serve your HTML files from a 'public' folder like this:
Just toss your .html
files into the 'public' directory and Express takes care of the rest—serving the files when asked nicely by an HTTP request.
The route-specific touch
You might want to serve certain pages only on specific routes, or inject some dynamic content on-the-fly. In those scenarios, res.sendFile is your ally:
This serves up delicious index.html anytime someone requests the root path (like visiting http://localhost:3000/ in the browser).
Making your HTML feel alive
Static files are great, but sometimes you want your HTML to feel a little more alive, respond to the viewer's actions, and maybe even remember their favorite color. Here are a few tools for the job:
- AngularJS is a client-side JavaScript framework that can turn your static HTML into an interactive experience.
- JavaScript itself can dynamically modify the DOM after a page has loaded, no extra libraries required.
- If you want to roll with server-side dynamic content, you could combine Express with libraries like consolidate and swig to create a custom rendering engine:
Scaling your views with EJS
Want to stick with .html
file extension but still need some frosting on your cake? There's EJS:
Now, your HTML can also include snippets of JavaScript for server-side rendering—like a superhero with regular clothes but superpowers underneath.
Cases for a view engine
Static HTML pages are enough for smaller apps. Still, for larger apps where:
- Template inheritance or partials would help to reuse bits of HTML, or
- It requires passing server-side variables to your HTML, or
- SEO matters, and client-side JavaScript for dynamic content isn't enough,
You might want to consider using a template engine.
Ensuring smooth operation
Here are some practices to avoid interruptions to serving HTML files:
- Don't set 'html' as a view engine to avoid the "Cannot find module 'html' error".
- Serve files securely by sanitizing file paths and prevent directory traversal attacks.
- Sending the proper MIME types is crucial or else browsers might not interpret your served files correctly.
Was this article helpful?