Build a MERN Stack Chat App with Node JS and Express JS API
Table of Contents
- Introduction
- Setting Up the Node.js Server
- Initializing the Node.js App
- Installing Express.js
- Creating the Server
- Running the Server
- Adding a Custom Script
- Creating the First Express.js API
- Making a GET Request to the Root Route
- Serving Data Related to Chats
- Getting a Single Chat Data
- Using Environment Variables
- Testing APIs with Postman
- Conclusion
Setting Up a Node.js Server and Creating APIs with Express.js
In this tutorial, we will learn how to set up a Node.js server and Create our first API using Express.js. We will start by initializing a new Node.js app and installing the Express.js Package. Then, we will create a server using Express.js and run it on a specific port. After that, we will dive into creating our first API endpoints. We will make a GET request to the root route and serve some sample data related to chats. We will also learn how to get a single chat's data Based on its ID. Furthermore, we will utilize environment variables to configure the server's port. Finally, we will test our APIs using Postman.
Introduction
Welcome to the Chatham Tutorial Series on MERN stack development! In this video, we will embark on creating our very first Node.js server and API using Express.js. Node.js is a powerful JavaScript runtime that allows us to build server-side applications, while Express.js is a lightweight web application framework that simplifies the development of backend applications with Node.js. By the end of this tutorial, You will have a solid understanding of setting up a Node.js server, creating APIs, and serving data from the backend.
Setting Up the Node.js Server
Initializing the Node.js App
First, let's start by initializing a new Node.js app. Open your preferred text editor or IDE, such as VS Code, and navigate to the folder where you want to start your project. In the terminal, Type npm init
and press enter. This command initializes a new Node.js app and Prompts you to enter the package name, version, entry point, and other information. Feel free to provide the appropriate details or simply press enter to use the default values.
Installing Express.js
To create our server and APIs, we need to install the Express.js package. Express.js is a web application framework that enables fast and flexible development of backend applications with Node.js. In your terminal, type npm install express
and press enter. This command installs the Express.js package and adds it as a dependency in your project's package.json
file.
Creating the Server
Now that we have installed Express.js, let's create our first server. Within your project's folder, create a new directory called "backend". This directory will contain all of our server-side code. Inside the "backend" directory, create a new file called "server.js". In this file, import the Express.js module by adding the following line of code:
const express = require('express');
Next, create an instance of the Express object by assigning the imported module to a variable named app
:
const app = express();
With the help of the app
variable, we can now start our server on a specific port. For example, let's start the server on port 5000:
app.listen(5000);
To verify that our server is running, let's log a message to the console. Add the following line of code:
console.log('Server started on port 5000');
Save the file and go to your terminal. To run the server, type node backend/server.js
and press enter. You should see the message "Server started on port 5000" in the console, indicating that your server is running successfully.
Running the Server
It can be tedious to run the server manually every time we make changes to our code. To automate this process, we can use a package called nodemon. Nodemon automatically detects changes in our server code and restarts the server for us. To install nodemon, go to your terminal and type npm install nodemon
. Once nodemon is installed, open your "package.json" file and update the "scripts" section as follows:
"scripts": {
"start": "nodemon backend/server.js"
},
Now, instead of running node backend/server.js
, we can simply run npm start
to start the server. Nodemon will watch for changes in our server code and restart the server automatically.
Adding a Custom Script
Let's add a custom script to our "package.json" file, so we don't have to run the server manually using npm start
every time. Open the "package.json" file and remove the default "test" script. Add a new script called "start" with the following command:
"scripts": {
"start": "node backend/server.js"
},
This script tells Node.js to run the "server.js" file located within the "backend" directory. Now, in your terminal, type npm start
and press enter. You will Notice that it does the same thing as before, starting the server on port 5000.
Creating the First Express.js API
Now that our server is up and running, let's move on to creating our first Express.js API endpoints. An API (Application Programming Interface) allows different software applications to communicate and exchange data. In our case, we will be creating APIs to serve data related to chats.
Making a GET Request to the Root Route
To create a basic API endpoint, let's make a GET request to the root route ("/"). This means that whenever we visit the root route of our server, it will trigger some actions. Add the following code below the server initialization code:
app.get('/', (request, response) => {
response.send('API is running');
});
In this code, we use the app.get()
method of the Express object to define a route handler for a GET request to the root route. The route handler is a callback function that takes two parameters: request
and response
. Inside the callback function, we use the response.send()
method to send a response to the client. For now, We Are sending the response "API is running".
Save the file and restart the server using npm start
. Open your browser and go to "http://localhost:5000". You should see the message "API is running" displayed in your browser. This confirms that our server and API are working correctly.
Serving Data Related to Chats
Now, let's serve some sample data related to chats through a new API endpoint. For this demonstration, we will use dummy data stored in a separate file called "data.js". Create a new folder inside the "backend" directory called "data". Inside the "data" directory, create a file named "data.js".
In the "data.js" file, let's define an array of chat data as follows:
const chats = [
{
id: 1,
name: 'Chat 1',
participants: ['user1', 'user2'],
isGroupChat: false
},
{
id: 2,
name: 'Group Chat 1',
participants: ['user1', 'user2', 'user3'],
isGroupChat: true
},
// Add more chat objects as required
];
module.exports = { chats };
In this code, we define an array called "chats" that contains chat objects. Each chat object has properties such as an ID, name, participants, and whether it is a group chat or not. The module.exports
statement allows us to export the "chats" array from the file so that we can import it in our API.
Now, let's modify the previous API endpoint ("/") to serve the chat data. Replace the existing route handler code with the following code:
app.get('/', (request, response) => {
response.send(chats);
});
In this updated code, we replace the response message with the "chats" array. When the client makes a GET request to the root route, the server will send the chat data as the response.
Save the file, restart the server, and refresh your browser. You should now see the chat data displayed in your browser. This demonstrates how we can serve data from the backend to the client through our API endpoints.
Getting a Single Chat's Data
In addition to serving all chat data, we may also want to retrieve the data of a specific chat based on its ID. Let's create a new API endpoint to handle this Scenario. Add the following code after the previous API endpoint:
app.get('/api/chat/:id', (request, response) => {
const chatId = request.params.id;
const singleChat = chats.find(chat => chat.id == chatId);
response.send(singleChat);
});
In this code, we define a new endpoint ("/api/chat/:id") that accepts a route parameter called "id". The route parameter allows us to capture the ID value provided in the URL. Inside the endpoint's callback function, we retrieve the ID value using request.params.id
. We then use the Array.find()
method to search for the chat object with a matching ID in the "chats" array. If a match is found, we send the single chat object as the response.
Save the file, restart the server, and test the new API endpoint. Go to "http://localhost:5000/api/chat/1" in your browser. You should see the data of the chat with the ID of 1 displayed in your browser. This demonstrates how we can retrieve specific data by providing a parameter in the URL.
Using Environment Variables
To avoid exposing the server's port number (5000) to the public, we can make use of environment variables. Environment variables allow us to store sensitive or configurable data outside of our code. Let's create a .env
file to store the server's port number. In the root folder of your project, create a new file called .env
. Inside this file, define a variable called "PORT" and set it to the desired port number (e.g., 5000):
PORT=5000
To access this environment variable in our server code, we need to install the dotenv
package. In your terminal, type npm install dotenv
and press enter. This package will load the variables from our .env
file into the server's environment.
To use the dotenv
package, import it at the top of the "server.js" file by adding the following line of code:
require('dotenv').config();
Next, modify the server initialization code to use the environment variable for the port number:
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
In this code, we use the process.env.PORT
syntax to access the value of the "PORT" environment variable. If the variable is defined, it will use that value as the port number. Otherwise, it will default to 5000.
Save the file, restart the server, and verify that the server is running on the specified port, as indicated by the console message.
Testing APIs with Postman
Instead of using a browser to test our APIs, we can make use of a tool called Postman. Postman allows us to send various types of HTTP requests and inspect the responses. To use Postman, download and install it from the official Website.
Once you have Postman installed, open the application and click on the plus icon to create a new request. Select the desired request type (e.g., GET), enter the request URL (e.g., "http://localhost:5000/api/chat"), and click the "Send" button. You should see the response data displayed in the Postman application.
Postman is a powerful tool that allows us to easily test and debug our APIs. It provides features for organizing requests, saving response data, and creating automated test scripts. We will explore more about Postman in future tutorials.
Conclusion
In this tutorial, we learned how to set up a Node.js server and create APIs using Express.js. We initialized a new Node.js app, installed Express.js as a dependency, and created a server that runs on a specific port. We then created our first API endpoints, made a GET request to the root route, served chat data, and retrieved data for a specific chat based on its ID. We also learned how to use environment variables to configure the server's port and tested our APIs using Postman.
By following this tutorial, you now have a strong foundation in creating a Node.js server and developing APIs with Express.js. You can now confidently start building more complex backend applications and implement additional routes and functionality as needed.
In the next tutorial, we will dive into creating our first React.js application and integrate it with our backend to display the data served by our APIs. Stay tuned!