Setting up a React and Node.js project.

This post is the lesson 1 of React online course from JS Mega Tools.

These days it is very easy create a complete web application with just JavaScript, without the need to learn any new language. In this course are going to create a travel accommodation search app with MERN stack, which stands for Mongo (a database), Express (a server side framework), React (a client side library, which you combine with other front-end tools, like Redux and React Router to create a client side framework) and Node.js (allows the execution of javascript on a server).

Mongo is a NoSQL database, that uses documents (kind of like javascript objects) to store data. Basically it gives you more freedom in how you structure your data. It is very popular with javascript developers.

React is a popular modern framework that allows you to quickly create scalable, fast and modern web applications, with ease and a minimum of bugs. It works well with Redux and Mobx for state management, but also can be used on its own for smaller applications.

Node.js allows you to run javascript on a server. It also provides you with tools that make the development of server side code easier.

Express.js is a framework for Node.js, it is built on top of Node.js api. In a nutshell, it provides you with a simpler way to write an app, than pure Node.js.

We are going to be going over every part, but we are going to concentrate more extensively on React (and its related tools).

Let’s create a root directory for our project. Let’s call it react-travel-accomodations.

mkdir react-travel-accomodations
cd react-travel-accomodations

In our root directory will need to initialize our project:

npm init
git init

npm init will create a package.json file for us. git init will make the project be tracked by git. Once we have ran those 2 commands, we need to create a directory for our front-end code – react code, lets call the directory react-ui. We will use create-react-app application. It is a recommended by React creators way to create applications with React. What it does is, as you’ve probably guessed it, creates a react app:). If you don’t have it on your computer, you can install it via npm

npm install -g create-react-app

Once it is installed, run the following command:

create-react-app react-ui

This going to create a react project with its own package.json in react-ui folder. create-react-app sets up a webpack development server so you don’t need a separate server, while you develop your project. But for api requests and for production, you are going to need a separate server, which will be located in our root folder.

The structure of react-ui folder is going to look like the following:

README.md
node_modules
package-lock.json
package.json
public
src

node_modules folder contains additional modules that are needed for our application to work. package.json is required for the project configuration and package-lock.json improves the installation of modules. public folder contains index.html and files that are needed by a browser, like favicon.ico and manifest.json. The contents of public folder are going to be copied to build folder, when you build your app for production. And finally we have src folder, which is where all the code, for the React front-end is going to be located. It has the following contents:

App.css
App.js
App.test.js
index.css
index.js
logo.svg
registerServiceWorker.js

index.js is the entry javascript file of the application, index.css is the global stylesheet of the application. App.js is the code for the main component of the application, App.css is its stylesheet, App.test.js is for unit tests. create-react-app doesn’t utilize css modules-like system, so you either have to eject from create-react-app (npm run eject), or make sure your css does not have conflicting rules. Because of no css modules built in for create-react-app, every css file can be considered global and influencing the entire application. registerServiceWorker.js file is for using Service Workers for the application, you don’t need to worry about it for this project.

Let’s leave react-ui for now and go back to the root directory to set up a server side for the production. We need to install Express first:

npm install —save express

then we need to create server.js file with the following contents:

const express = require('express');
const path = require('path');
const app = express();

const port = process.env.PORT || 5000;

app.use(express.static(path.resolve(__dirname, './react-ui/build')));

app.get('*', function(request, response) {
  response.sendFile(path.resolve(__dirname, './react-ui/build', 'index.html'));
});

app.listen(port, () => console.log('Example app listening on port 5000!'));

We import express and path modules through require function. Express framework is represented by express module and path module is a utility mode from Node.js. Then we initialize Express, putting it into app constant.

Let’s pick a port our app is going to run on. I chose Heroku as a hosting for this project. This is going to influence the next line of code in the following way. Node provides us with process.env object. Heroku adds a PORT property to that object. It will hold a port that Heroku provides for our application. If we are running the app locally the PORT variable will not be set and we can run the server on whatever port we want, in this case 5000. This line of code can be adjusted according to your hosting provider, and the second part of the || operator can be adjusted according to your local port preferences.

Now that we’ve defined a port for our application we are going to designate a directory for static assets (images, styles, client side javascript, etc.) of our application. We are going to use express.static function for that. It takes a path argument, which we are creating using Node’s path.resolve function, which resolves a path, from its arguments. In our case we use __dirname which holds a filesystem path to the current module (server.js) and ./react-ui/build, a directory to which create-react-app’s scripts copy static files during build. So we are telling express here: “Whenever you receive a request for something inside react-ui/build (like: http://example.com/react-ui/build/some_image.png“) send it as a file. This way you can put into that folder any file you want to be sent to a user and you don’t need to define a separate route for it.

One thing to note here is we pass the results of express.static call to app.use, app.use is used to add middleware to express. In our case the middleware is whatever is returned from express.static call. Middleware is a key concept of express, it is a function that receives a request object( represents a user’s http request) and a response object ( represents a server’s http response to the user). It can do something useful with the help of those objects and call the next middleware function. This way if you want to do something after a server received a user’s request, but before it sent a response, you can use middleware functions.

Next we are going to define a route for our home page. Like this:

app.get(‘*', function(request, response) {
  response.sendFile(path.resolve(__dirname, './react-ui/build', 'index.html'));
});

Here we tell Express, that whenever the server receives a GET http request for any page, the server should send the index.html file in response (static files will be sent correctly because we used express.static before the route definition). Why don’t we just send the index.html file in response to the root path (‘/‘)? Imagine the following scenario. A user received index.html in response to root path, then he or she, by doing some actions within the app navigates to /some_path (the navigation was handled within the app, and the user does not type it into a browser’s address bar). But if he decides to navigate to that path through a browser address bar, or refresh the page, close-reopen the browser, etc., the server will send a 404 response. If we send a index.html page in a response to any request, the app will be able to present a user with the proper content according to the path requested (With the help of React Router).

The final line of code sets up the server to listen for user requests on whatever port was chosen earlier.

Now you can run npm start command in the project root, then open another terminal window or terminal tab and change directory to react-ui and run npm start there.

Your application should be available at the address localhost:5000, because you’ve run npm start in project’s root directory, and that address is served by express server. Your application is also available at localhost:3000, because you’ve run npm start in react-ui directory, this address is served by webpack development server.

At this point you can create a first git commit in the project. Be sure to add a .gitignore file to the root directory so you don’t commit any extra files. You can look at an example .gitignore file in the source code for this lesson on github.

That is how you create a basic App with React in Node. In the next lesson we are going to set up Redux and React Router.

The github source for this lesson and the entire course is at the following address: https://github.com/jsmegatools/React-online-course.

1 thought on “Setting up a React and Node.js project.

Leave a Reply

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