Build and Deploy a Web Application With React and Node.js + Express
To go through the steps of connecting and running together a Node.js server with a React application, we will build a simple web application to search for artworks on the Art Institute of Chicago’s API. We will set up a basic login page, save a token on the browser to keep the user signed in, and search for artworks by a keyword on AIC’s database. A log out button on the homepage will remove the token from local storage and redirect the user to the login page.
Some knowledge and experience with Node.js, Express and React is required.
First, we will start by building the back end of the application. Download and install the latest version of Node.js. Create a new folder for this project and open a terminal window inside it. Run npm init to quickly create a package.json file, where we will list all the dependencies and their versions, as well as other metadata. This makes the project reproducible and eases collaboration between developers.
Pro tip: install nodemon globally to automatically restart the server on each file change.
We will also install some packages before starting to write code. Express is a framework built on top of Node.js, that simplifies its API and allows us to smoothly add middleware, routing and request handlers. Cors will deal with Cross-Origin Resource Sharing configuration. Dotenv enables us to separate secrets (like port numbers, credentials or tokens) from source code, storing this information in a .env file that should not be committed on git. Express-validator is a wrapper for validator.js that facilitates input sanitization and validation.
The entry point file to the back end of the application (set by property main in the package.json file) will initialize a server and listen for connections on the specified port. We should also add all middleware functions and bind routes to controllers when the server is launched.
Entry point filemodels/server.jsroutes/auth.js
We will sanitize and validate input data through middleware functions on the request handler and, if no errors occur, send this values to the corresponding controller function. To keep this guide simple, the login controller will only allow the user to log in if the password entered is “1234”. Ideally, this information would be matched to a database entry.
This should be enough to log in and redirect the user to the homepage. We will check if there’s a token saved on the browser each time the application loads.
Since AIC’s API requires no authorization protocol to request data, the controller will receive a keyword from the front end as a URL parameter and execute a request to the API for artworks that match the search term/s. To communicate with the API, we will install cross-fetch library and execute a GET request with the appropriate parameters.
The API response will be parsed as a JSON object, sent to the front end and turned into rendered UI components on the browser.
We will group all front end (React) code into a new folder at root level. It will pick up the same .gitignore rules we defined for the Node server (if you haven’t yet, git init will create a new Git repository). Go into the folder created and start a React project with Create React App.
Since each part of the application will be running on separate ports on development, we need to proxy API requests coming from the front end. To do this, if the back end server runs on port 8080, add this line in the client’s package.json: “proxy”: “http://localhost:8080”
Now, all unknown requests to relative paths from the front end will be sent to the back end server running on port 8080. Note that this is only valid in development and will have no effect in production.
Let’s install Bootstrap and use its components for React to build a basic UI to interact with the back end. On the entry point component to the application, we will check for a token on local storage to know if the user has already signed in. On log out, we will remove the token from the browser’s storage.
To trigger an AIC search for artworks we will execute requests to the back end using relative paths. As the application scales, keep all API functions in a folder separated from UI components.
We can now perform an API request to the Node.js server from a React UI component. For example, to look for artworks based on a keyword:
Developing and running the front and back end at the same time gets easier if we use npm’s package concurrently: we can run multiple commands concurrently and automatically reload both servers with every change.
Go to the root package.json file and add the following scripts. Make sure to set the value of the --prefix option to the right folder in your file structure.
Now we can run both applications with a single command: npm run dev
Before deploying the application to a hosting service, we need to build the client application and tell the back end how to load it.
We will also add a new request handler on the Server class to catch all requests that do not match any route and send back React’s index.html file.
The application is now production ready. If you choose to deploy your application to Heroku, start by signing up, going to the dashboard and creating a new app. You can then install Heroku CLI to manage your application from the terminal or link your GitHub repository for automatic deploys. Whichever method you choose to deploy make sure Node’s package.json file is at the root of the directory structure.
When you’re ready to deploy your application, make sure all your changes are committed and push them to the deployment branch.