Forem

Cover image for ⚙️Server-side rendering without Next.js, Remix, Nuxt.js, etc. 🔥
Anthony Max Subscriber for HMPL.js

Posted on

⚙️Server-side rendering without Next.js, Remix, Nuxt.js, etc. 🔥

Hello everyone! Perhaps you want to implement server-side rendering in your project, but do not want to rework its established architecture? Then this article is especially for you. Today, I will try to tell you how to do this.

It is worth noting that this method is suitable for any web project architecture, be it WordPress, Vue.js, or any other.

🔧 How Server-Side Rendering Works

This list describes the Server-Side rendering process step by step:

  1. Request: When a user requests a web page (by entering a URL or clicking a link), the request is sent to the web server.

  2. Processing: The server processes the request. This often involves fetching data from a database, running business logic, and rendering the HTML based on this data. This can be done using server-side frameworks such as Node.js with Express, Django, Ruby on Rails, etc.

  3. Generating HTML: The server creates the complete HTML for the requested page. This can be done using templating engines (like EJS, Handlebars, or Pug) or directly with server-side languages that build the HTML structure.

  4. Response: The server sends the fully rendered HTML page back to the client's browser.

  5. Rendering in Browser: The browser receives the HTML and renders it immediately, displaying the content to the user.

In the diagram, it looks like this:

SSR

Now, let's see what this looks like in code.

💻 Code Example

Here’s a simple example using Node.js with Express and EJS as the templating engine for SSR:

1. Set up Node.js with Express

First, you need to create a new Node.js project and install Express and EJS:

npm install express ejs
Enter fullscreen mode Exit fullscreen mode

2. Create the Server

Create a file named server.js:

const express = require('express');
const app = express();
const PORT = 3000;

// Set EJS as the templating engine
app.set('view engine', 'ejs');

// Sample data
const data = {
    title: 'Server Side Rendering Example',
    content: 'This is an example of Server Side Rendering using Node.js and EJS.'
};

// Define a route
app.get('/', (req, res) => {
    // Render the HTML using EJS
    res.render('index', { data });
});

// Start the server
app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

3. Create the EJS Template
Create a folder named views, and inside it create a file named index.ejs:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><%= data.title %></title>
</head>
<body>
    <h1><%= data.title %></h1>
    <p><%= data.content %></p>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

4. Start the Server
Run the server:

node server.js
Enter fullscreen mode Exit fullscreen mode

Now, when you navigate to http://localhost:3000, the server will render the complete HTML page and send it to the browser.

🐜 Using HMPL

You can achieve server-side rendering by using this module. The connection is very simple and the usage is also:

<script src="https://unpkg.com/json5/dist/index.js"></script>
<script src="https://unpkg.com/hmpl-js/dist/hmpl.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

or

npm i hmpl-js
Enter fullscreen mode Exit fullscreen mode

Now, you can safely use the module in the project. Let's try to take some component from the server:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Example</title>
  </head>
  <body>
    <script>
      document.body.append(
        hmpl.compile(`<main>{{ src: "/api/header" }}</main>`)().response
      );
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Thanks to the extended markup of request objects, we can compile the string into a ready-made DOM node that can be easily rendered into the DOM.

Also, it would be great if you supported the project with your star! Thanks ❤️!

💎 Star HMPL ★

The result will be as follows:

header

This way, our components are rendered on the server, and we simply display them on the client.

✅ Conclusion

This method is great when you don't need to depend on the architecture of frameworks and libraries, but at the same time, because of this feature, since the page is requested from the client, search robots will not see the page. Therefore, this method is suitable when you don't need to think too much about SEO.

Thank you for reading!

thanks

Top comments (20)

Collapse
 
sadiqsalau profile image
Sadiq Salau

This has always been the way, and it's faster than calling thousands of functions to render a single tag.. It's funny how nextjs and other frameworks makes this look like a new feature..

And looking at the comments, I would say don't bash PHP if you aren't an artisan, do you remember jQuery? Don't be surprised some sites still use such tools..

Collapse
 
thomas_stpierre_47a127d profile image
Thomas St. Pierre

Agree, there is a stark difference between an engineer and a coder these days.

Collapse
 
stevepotter profile image
Stephen Potter

It’s wild to me how SSR is perceived as a new thing considering that’s how it was done for decades. Glad to see the pendulum swinging back a bit.

Collapse
 
anthonymax profile image
Anthony Max

Next.js changed everything back. Everyone got used to react, but without SEO optimization it was not really necessary for business. Now there is no such problem.

Collapse
 
gamerdev13 profile image
Martin Green

Good article. I would also compare it with php

Collapse
 
anthonymax profile image
Anthony Max

Thank you! The comparison with php is a bit incorrect, since it is a bit different

Collapse
 
thomas_stpierre_47a127d profile image
Thomas St. Pierre

No, it's spot on, PHP became one of the most used servers side languages of the internet.

It's also the devil and atrocious.

Collapse
 
john_coding profile image
John

Well, I don’t know, frameworks define the architecture of the application, but that’s also ok when you can do it on each site

Collapse
 
anthonymax profile image
Anthony Max

But how much code is needed?

Collapse
 
anthonymax profile image
Anthony Max

I think server-side rendering is the future, so this is a cool idea.

Collapse
 
priyanshdwivedi profile image
Priyansh Dwivedi

How can SSR be the future if it has been there since decades!

Did you mean back to the future? 😄

Collapse
 
anthonymax profile image
Anthony Max • Edited

Everything new is a well-forgotten old. People, when they made sites on wordpress in the 10s and saw Angular and Vue for the first time, were shocked, I'm sure, for them it was the future. I'm not talking about php, but it's obvious here.

Thread Thread
 
thomas_stpierre_47a127d profile image
Thomas St. Pierre

Uh bro, we were doing this with Visual Basic and DLLs in the 90s before Google even exists a company.

That's what so many of these comments are about.

Collapse
 
thatwaiguy profile image
ThatAdwaithGuy

Htmx + a static compiled Language (go or rust) is much, much better than this method. For more interactivity, Alpine.js. this stack is much better and just dominates your stack. THIS IS ALL IN MY OPINION

Collapse
 
anthonymax profile image
Anthony Max

htmx - depends on DOM. Try to use HTMX normally from js (spoiler - it's difficult, if not impossible). Regarding Alpine.js - it's not HTMX, it's a mix of some interactivity with html. Like jsx, only somehow different. It's not 100% server-oriented. Depends on the task, again.

Collapse
 
maksiks profile image
Maksiks

Just use Nuxt or any other framework in the title, you plug it in and you get SSR, and copy paste your code. If you want a quick little website the performance difference is going to absolutely neglegable and for blocking out search engines robots.txt exists. (Although since search engines are just indexing stuff and they typically wait for SSR websites, why would this block out SEO?)

Collapse
 
j-256 profile image
James

I don't entirely understand the SEO point either, to be honest. Isn't this post saying "hey have you considered doing things the way we did for decades"?

Collapse
 
cecheverria profile image
Carlos Echeverria

I've worked SSR all my life no matter the language; Spring boot, Node.js

SSR means simplicity, and avoid tech jargons from vendors overbuild frameworks (which are ok to try and innovate, I don't blame them).

You are mixing SSR with CSR, and is ok, but that will lose SEO as part of your initial rendering is done after page loads.

Rule of SSR:

  • First page rendering is 100% from server side as you mention using any template engine.
  • Avoid CSR rendering on first page load, as it will partially block SEO.
  • Avoid CSR rendering, implements http methods that will render pieces of your page from server side (plain vanilla hydration).

SSR disadvantage:

  • Some way you'll need to handle client controls state in server side (tradeoffs if you pursue SEO)

Simplistic approach that will live across any new hype on web development.

Collapse
 
arcahyadi profile image
arcahyadi

Blud bash php ☠️ if that me, i wouldn't do it, php is scary, that thing literally undead creatures

Collapse
 
insat_vipbio_6121e73013d9 profile image
Insat Vipbio

Good article. I would also compare it with php ..thehaircuts.net/