Introduction To React Server-Side Rendering (SSR)

In this blog post, we have discussed what is React server-side rendering, what’s the difference between client-side rendering and server-side rendering and shared some code snippets for the server-side rendered React applications.

Client-Side Rendering (CSR)

  • The client sends a request to the server (API)
  • The server receives the request, query the requested data and sends the data back to the client
  • The client receives the data, renders the HTML and display it to the user

Server-Side Rendering (SSR)

  • The client sends a request to the server
  • The server receives the request, query the required data, renders the HTML and sends back the rendered HTML page
  • The client receives the rendered HTML page from the server and displays it to the user

Benefits of Server-Side Rendering

  • Improves the performance of the application
  • Improves search engine optimization (SEO) of the application

Using Next.js Library

Next.js is a JavaScript library that allows us to quickly set-up server-side rendered React applications. It provides some greater features like page-based routing, server-side page rendering, automatic code-splitting, client-side routing, API routes and many more…

Steps to Create Server-Side Rendered React Application using Next.js

  • CD into the folder, where you want to create the application by using Command Prompt
  • Run the command: npm init
  • Answer the asked questions and hit Enter
  • Install the required dependencies by running the command: npm install –save next react react-dom
  • Open the application folder in your favorite code editor like VSCode
  • Open package.json file and edit the scripts object with following code (see Code Snippet 1)
  • Create a new folder inside the application folder and name it ‘pages’
  • Inside pages folder, create a new file and name it as index.js and following code (see Code Snippet 2)
  • For static files like images, create a new folder called static
  • Run the command: npm run dev
  • Your application is available at http://localhost:3000/
  • Congratulations! Your first SSR application is up and running

Code Snippet 1:

"scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"

Code Snippet 2:

export default () => (
    <p1>Hello World</p1>

To add CSS support, do the following steps:

  • Run the command: npm install –save @zeit/next-css
  • Create a new file and name it as next.config.js

That’s it. In this post, we have created a very simple Hello World Server-Side rendered React application using Next.js.

Leave a Comment

Your email address will not be published. Required fields are marked *