Techletter #98 | November 9, 2024
Building the UI is something you cannot ignore if you want to make your software usable by others.
Using React is heavy. It would be a great choice if your app is huge, and consists of thousands of components. But, for few simple UI’s you don’t have to go with the React. You can use EJS or Pug. I preferred EJS because I did build a simple application during my college time with it. And another reason is that the documentation is really good.
What is EJS?
EJS is a powerful template engine primarily used in Node.js applications to generate dynamic HTML content. According to the official documentation
What is the “E” for? “Embedded?” Could be. How about “Effective,” “Elegant,” or just “Easy”? EJS is a simple templating language that lets you generate HTML markup with plain JavaScript. No religiousness about how to organize things. No reinvention of iteration and control-flow. It’s just plain JavaScript.
EJS is particularly suited for
- Server-Side Rendering (SSR): It generates HTML on the server side, which can improve SEO by making content accessible to search engines before it reaches the client.
- Traditional Multi-Page Applications (MPAs): Unlike client-side frameworks like React or Angular, which focus on building single-page applications (SPAs), EJS is ideal for applications where each page load requires a new HTML response from the server.
To keep it simple, I personally felt EJS is easy to setup as I work mostly in the backend. Setting up the React codebase will need extra work to maintain it separately.
Now let’s see how you can start using EJS in your application
I assume you are already familiar with setting up a node application. So skipping the repetitive things.
If you want to make use of Bootstrap or CSS or JS files first you need to tell the express where to look for static files. I keep all the static files in the public directory. So, You can achieve this via
app.use(express.static('public'));
I keep all the EJS content within the views directory at the root of the project. I keep all reusable content within views/partials directory.
For your node & express app to consider using the EJS. You should install EJS via npm/yarn/pnpm. Once it is installed, you need to set the view engine.
app.set('views', './views');
app.set('view engine', 'ejs')
How you can serve the content?
app.get('YOUR_API_ENDPOINT', (req, res) => {
res.render('YOUR_VIEW_COMPONENT');
});