Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

JavaScript Essentials - Server-Side Rendering

Introduction to server-side rendering

Server-side rendering (SSR) is the process of rendering web pages on the server instead of the client. This technique can improve performance, SEO, and the initial load time of your application. This tutorial covers the basics of implementing server-side rendering in JavaScript applications.

Key Points:

  • SSR renders web pages on the server and sends the fully rendered page to the client.
  • SSR improves performance and SEO by providing a complete HTML document to the client.
  • SSR can be implemented using frameworks like Next.js or by setting up your own Node.js server.

Setting Up Server-Side Rendering with Next.js

Next.js is a popular React framework that supports server-side rendering out of the box. To get started, you need to create a new Next.js project.


// Create a new Next.js project
npx create-next-app my-ssr-app

// Navigate to the project directory
cd my-ssr-app

// Start the development server
npm run dev
                

Creating Pages in Next.js

Next.js uses a file-based routing system. Create a new file in the pages directory to define a new page.


// pages/index.js
import React from 'react';

const Home = () => {
    return (
        <div>
            <h1>Hello, Next.js!</h1>
        </div>
    );
};

export default Home;
                

Visit http://localhost:3000 to see your new page.

Fetching Data on the Server

Next.js provides a special function called getServerSideProps that allows you to fetch data on the server before rendering the page.


// pages/index.js
import React from 'react';

const Home = ({ data }) => {
    return (
        <div>
            <h1>Hello, Next.js!</h1>
            <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
    );
};

export async function getServerSideProps() {
    const res = await fetch('https://jsonplaceholder.typicode.com/posts');
    const data = await res.json();
    return { props: { data } };
}

export default Home;
                

Custom Server with Node.js

If you prefer to set up your own server, you can use Node.js with a framework like Express to implement server-side rendering. Here is an example of setting up a custom server.


// Install necessary packages
npm install express react react-dom @babel/core @babel/preset-env @babel/preset-react

// Create a Babel configuration file (.babelrc)
{
    "presets": ["@babel/preset-env", "@babel/preset-react"]
}

// server.js
const express = require('express');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const App = require('./src/App').default;

const app = express();

app.use(express.static('public'));

app.get('*', (req, res) => {
    const app = ReactDOMServer.renderToString(React.createElement(App));
    const html = `
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>SSR with Node.js</title>
        </head>
        <body>
            <div id="root">${app}</div>
            <script src="/bundle.js"></script>
        </body>
        </html>
    `;
    res.send(html);
});

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

// src/App.js
import React from 'react';

const App = () => {
    return <h1>Hello, SSR with Node.js!</h1>;
};

export default App;
                

Hydration

Hydration is the process of attaching event listeners and other interactive features to the server-rendered HTML on the client. In Next.js, this happens automatically. For custom setups, you need to ensure the client-side code is correctly rehydrated.


// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.hydrate(<App />, document.getElementById('root'));
                

Benefits and Drawbacks of SSR

Server-side rendering offers several benefits, including improved performance, better SEO, and faster initial load times. However, it also comes with drawbacks such as increased server load and complexity in setting up and maintaining the server.


// Benefits
1. Improved Performance
2. Better SEO
3. Faster Initial Load Times

// Drawbacks
1. Increased Server Load
2. Complexity in Setup
3. Maintenance Overhead
                

Summary

In this tutorial, you learned about server-side rendering (SSR) and how to implement it in JavaScript applications using Next.js and custom Node.js servers. SSR improves performance, SEO, and the initial load time of your application by rendering web pages on the server. Understanding the benefits and drawbacks of SSR can help you decide when and how to use it in your projects.