Introduction
React.js is a powerful library for building user interfaces, and it provides developers with two rendering approaches: Server-Side Rendering (SSR) and Client-Side Rendering (CSR). In this step-by-step guide, we'll walk you through the process of implementing both SSR and CSR in a React application.
Server-Side Rendering (SSR)
Step 1. Set Up a React Project
Start by creating a new React project if you haven't already. You can use the Create React App tool to quickly set up a project.
npx create-react-app my-ssr-app
cd my-ssr-app
Step 2. Install Dependencies
Install the required dependencies for SSR.
npm install express react-dom react-router-dom
Step 3. Create an Express Server
Create an Express server to handle SSR. Create a file named server.js in your project's root directory.
// server.js
const express = require('express');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const { StaticRouter } = require('react-router-dom');
const App = require('./src/App'); // Import your React app component
const app = express();
app.use(express.static('build')); // Serve client-side build files
app.get('*', (req, res) => {
const context = {};
const appMarkup = ReactDOMServer.renderToString(
<StaticRouter location={req.url} context={context}>
<App />
</StaticRouter>
);
if (context.url) {
// Handle redirects
res.redirect(301, context.url);
} else {
res.status(200).send(`
<!DOCTYPE html>
<html>
<head>
<title>SSR React App</title>
</head>
<body>
<div id="root">${appMarkup}</div>
<script src="/static/js/main.js"></script> <!-- Load client-side bundle -->
</body>
</html>
`);
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
Step 4. Modify Your React App
In your React app (located in the src directory), make sure to use React Router for routing and set up your components accordingly.
Step 5. Build and Start the Server
Build your React app and start the Express server.
npm run build
node server.js
Your SSR React app is now running at http://localhost:3000.
Client-Side Rendering (CSR)
Step 1. Set Up a React Project
If you haven't already set up a React project, you can do so using the Create React App tool. Open your terminal and run the following commands.
npx create-react-app my-csr-app
cd my-csr-app
This will create a new React project and navigate into its directory.
Step 2. Create Your React Components
In your project directory, navigate to the src folder and locate the App.js file. This is the main entry point for your React application.
Replace the content of App.js with your own React components, or you can create new components in the src directory. For example, you can create a simple component called HelloWorld.js.
// src/HelloWorld.js
import React from 'react';
function HelloWorld() {
return <h1>Hello, World!</h1>;
}
export default HelloWorld;
Step 3. Set Up Routing (Optional)
If your application requires multiple pages or views, you can set up routing using a library like react-router-dom. Install it as a dependency.
npm install react-router-dom
Then, in your App.js file or another appropriate component, set up your routes. Here's an example of how you might set up a basic router.
// src/App.js
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import HelloWorld from './HelloWorld';
function App() {
return (
<Router>
<Switch>
<Route exact path="/" component={HelloWorld} />
{/* Add more routes as needed */}
</Switch>
</Router>
);
}
export default App;
Step 4. Start the Development Server
With your components and routing in place, you can now start the development server by running.
npm start
This will launch your React application, and you can access it in your web browser at http://localhost:3000.
Step 5. Build and Deploy Your Application
Once you've developed your React application using CSR, you can build it for production deployment. Run the following command.
npm run build
This will generate an optimized build of your application in the build folder. You can deploy the contents of this folder to your web server or a hosting service of your choice.
Summary
You've now learned how to implement both Server-Side Rendering (SSR) and Client-Side Rendering (CSR) in a React.js application. SSR is suitable for improving SEO and initial page load times, while CSR is ideal for creating highly interactive applications. Depending on your project's requirements, you can choose the rendering approach that best fits your needs.