View engines

Setup

Templating and Server-Side Rendering (SSR) are techniques used to generate HTML on the server before sending it to the client's browser. While modern MERN stack development often relies on Client-Side Rendering (CSR) where React handles the UI, SSR remains vital for SEO, performance, and specific administrative tasks.

1. The Theory: How SSR Works


Theory: In a standard SSR flow, the server receives a request, fetches the necessary data from the database, injects that data into a template, and sends a fully-formed HTML file back to the browser.

  • SEO Friendly: Search engine crawlers can easily read the content because it is already present in the HTML.

  • Faster Initial Load: The user sees the page content immediately without waiting for large JavaScript bundles to execute.

  • Reduced Client Load: The "heavy lifting" of data processing and HTML construction happens on the server.


2. Templating Engines


Theory: A templating engine allows you to write standard HTML mixed with special syntax to inject dynamic data or perform logic (like loops and if-statements).

Popular Engines in Express:

  • EJS (Embedded JavaScript): Uses standard JavaScript syntax inside <% %> tags. It is the most popular due to its low learning curve.

  • Pug (formerly Jade): Uses a whitespace-sensitive, shorthand syntax that looks very different from HTML.

  • Handlebars (HBS): Focuses on keeping logic out of the template, using {{mustache}} tags for data binding.


Basic EJS Implementation:


// Set the view engine in Express
app.set('view engine', 'ejs');

app.get('/profile', (req, res) => {
  const userData = { name: 'Tharun', role: 'Developer' };
  // Renders the 'profile.ejs' file from the 'views' folder
  res.render('profile', { user: userData });[cite: 1]
});

Inside views/profile.ejs:

<h1>Welcome, <%= user.name %></h1>
<p>Your role is: <%= user.role %></p>


3. SSR in Modern Frameworks (React/Next.js)


Theory: For full-stack developers, "SSR" often refers to using frameworks like Next.js. Next.js allows you to build your UI in React but renders the initial page on the server.

  • Hydration: The server sends the HTML (SSR), and then React "wakes up" in the browser to handle interactivity. This process is called Hydration.

  • Static Site Generation (SSG): A variation where the HTML is generated once at build time, making it incredibly fast