Create Dynamic, Server-rendered Web Pages with React and Express.js

When building web applications, there are always many decisions to make about the technology stack. One of the most important questions is how to structure the front-end of the application. Many developers choose to use React, which is a popular front-end library for building user interfaces. However, using React alone may limit the application, as it only renders pages on the client-side and doesn't handle server-side rendering and routing. In this article, we will discuss how to use React along with a server-side platform like Express.js to create dynamic, server-rendered web pages.

What is Server-side Rendering?

Server-side rendering is a technique where the server generates HTML for pages, and the browser simply displays the HTML. This approach improves applications' performance and accessibility since the pages load faster and can be cached more efficiently by search engines and browsers. Server-side rendering also provides a better user experience by loading pages instantly and reducing the time it takes to interact with the website.

What is Express.js?

Express.js, often referred to as Express, is a fast and powerful web application framework built on top of Node.js. With Express, you can create HTTP servers, handle requests and responses, and build APIs. Express supports various middleware, which helps to enhance the framework with custom functionality, adding features like body parsing, cookie parsing, and sessions. Express is also compatible with many templating engines, making it easy to render dynamic pages efficiently.

Getting Started with React and Express.js

Before we get started with coding, make sure you have Node.js installed on your machine. You can download Node.js from the official website (https://nodejs.org/).

To begin, create a new directory called "server" and navigate to that folder in the terminal. In your terminal, enter the following command to initialize a new Node.js project:

npm init -y

This command creates a package.json file that tracks project dependencies and other metadata. Now, let's install the required packages. We'll use the following command to install Express.js and other packages:

npm install express react react-dom react-router-dom react-scripts

The react-scripts package is for configuring and building the React application. The react-router-dom package is for client-side routing in the React app.

Creating the Express.js Server

Create a new file in the "server" directory called "index.js". This file will be the entry point for our Express.js server.

Now, we'll configure the server to serve static files, like HTML files, CSS files, and JavaScript files. To do this, add the following code to your "index.js" file:

const express = require('express'); const app = express(); const path = require('path'); //serve static files from the public directory app.use(express.static('public')); //define a route to serve the index.html file app.get('*', (req, res) => { res.sendFile(path.resolve(__dirname, 'public', 'index.html')); }); //start the server const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Server listening on port ${port}`); });

In this code, we've imported the required packages and defined a route to serve static files from the "public" directory. We've also defined a route that serves "index.html" for any request. Finally, we've started the server on port 3000.

Creating the React App

Next, create a new directory called "public" in the root of the project. This directory will contain the static files that the server serves to the client. Create an index.html file in the "public" directory:

React App

In this code, we've created a basic HTML file with a div that has an ID of "root". We've also included a script tag that references the "bundle.js" file, which will be generated by React.

Now, create a new file in the root of the project called "App.js". This file will contain the main React component for the application:

import React from 'react'; import { Switch, Route } from 'react-router-dom'; import Home from './Home'; function App() { return ( ); } export default App;

In this code, we've imported React, Switch, and Route from React Router. We've also imported a component called "Home" from a file called "Home.js". Finally, we've created a function component that renders a Switch component with a single Route component. The Route component is set up to render the Home component when the URL matches "/".

Now, create a new file in the root directory called "Home.js". This file will contain the Home component:

import React from 'react'; function Home() { return (

Welcome to my website!

This is the home page.

); } export default Home;

In this code, we've created a function component that renders a div with an h1 tag and a paragraph tag.

Now, create a new file in the root called "index.js". This file will be the entry point for the React app:

import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter } from 'react-router-dom'; import App from './App'; ReactDOM.render( , document.getElementById('root') );

In this code, we've imported React, ReactDOM, BrowserRouter, and App from the respective files. We've also used ReactDOM.render() to render the App component inside a BrowserRouter component and mount it to the div with an ID of "root".

Building and Running the App

Now that we've created all the necessary files, we can build and run the app. To do this, open two terminals. In one terminal, navigate to the "server" directory and run the following command:

node index.js

This starts the Express.js server. In the other terminal, navigate to the root directory and run the following command:

npm start

This command starts the create-react-app development server, which compiles the React app and serves it on port 3000.

You can now view the app in your browser by navigating to http://localhost:3000. You'll see the home page with the message "Welcome to my website!".

Conclusion

We've shown how React and Express.js can be combined to create dynamic, server-rendered web pages. This technique improves applications' performance and accessibility and provides users with a better experience. With a little effort, developers can build efficient, powerful web applications that leverage the strengths of both technologies.

Try experimenting with this code and building more advanced applications with React and Express.js. There are many possibilities with these frameworks, and with some creativity, developers can create amazing web applications.