Health Tracker using MERN Stack
Last Updated :
23 Jul, 2025
In this step-by-step guide, we'll walk through the process of building a Health Tracker application using React for the frontend and Node for the backend. This application allows users to track their health metrics such as steps taken, calories burned, distance covered, and more.
Preview of final output: Let us have a look at how the final output will look like.
Final PreviewPrerequisite
Approach to create Health Tracker:
- Component Development:
- Develop key components, such as TrackerApp, TrackerList, and TrackerCard.
- These components represent the overall structure and appearance of the app.
- Implementing Context API:
- Set up a Context API (HealthContext) to manage the state of health data across components.
- Utilize useState and useEffect hooks for fetching initial data and updating the context.
- Styling Components:
- Enhance the visual appeal of the app by adding styles to components.
- Apply hover effects, adjust font sizes, and include subtle box shadows to make the TrackerCard visually appealing.
- Sorting TrackerList:
- Modify the TrackerList component to render health tracker cards based on the most recent date at the top.
- Sort the data array in descending order to display the latest entries first.
- Creating HealthForm Component:
- Develop a HealthForm component for users to input and update their health details.
- Include form fields for steps, calories burned, distance covered, weight, and other health metrics.
- Rendering Today's Data:
- Fetch today's health data from the context and pre-fill the form if available.
- Allow users to update their health metrics for the current day.
- Styling HealthForm:
- Apply styles to the HealthForm component to make it visually appealing.
- Create a form that appears on top of the screen with a blurred background when the user clicks a button.
Steps to Setup Backend with Node.js and Express:
Step 1: Creating express app:
npm init -y
Step 2: Installing the required packages
npm install express mongoose cors
Project Structure:
Backend The updated dependencies in package.json file for backend will look like:
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.2",
"mongoose": "^8.0.0",
}
Explanation:
- Create a file `server.js` in the `server` folder.
- Set up an Express server, configure MongoDB connection, and enable CORS.
- Define the Mongoose schema for health data, including date, steps, calories burned, distance covered, and weight.
//--------------------------------//
// Define MongoDB schema and model
//--------------------------------//
const healthDataSchema = new mongoose.Schema({
date: { type: Date, default: Date.now },
steps: Number,
caloriesBurned: Number,
distanceCovered: Number,
weight: Number,
});
const HealthData = mongoose.model('HealthData', healthDataSchema);
- Implement routes for CRUD operations, including fetching health data, updating metrics, and retrieving data for a specific day.
- If your application has many number of user than you can retrive data by making query but in this although we have cretaed a route but we will filter datewise data in frontend only using Javascript.
- Create a script to seed initial health data into the MongoDB database.
- Run this script to provide sample data for testing and development.
Example: Below is the code for the above explained approach:
JavaScript
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const PORT = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(cors())
// Connect to MongoDB (update the connection string)
mongoose
.connect('mongodb://localhost:27017/healthtracker',
{
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(
() => {
console.log('MongoDB connected successfully!');
})
.catch((error) => {
console.error('Error connecting to MongoDB:', error);
});
//--------------------------------//
// Define MongoDB schema and model
//--------------------------------//
const healthDataSchema =
new mongoose.Schema(
{
date: { type: Date, default: Date.now },
steps: Number,
caloriesBurned: Number,
distanceCovered: Number,
weight: Number,
});
const HealthData =
mongoose.model('HealthData', healthDataSchema);
//----------------------------//
// Seeding some initial data
//----------------------------//
const seedData = async () => {
try {
// Check if data already exists
const existingData =
await HealthData.find();
if (existingData.length === 0) {
const initialData = [
{
date: new Date('2022-01-01'),
steps: 5000,
caloriesBurned: 200,
distanceCovered: 2.5,
weight: 70,
},
{
date: new Date('2022-01-02'),
steps: 8000,
caloriesBurned: 300,
distanceCovered: 3.2,
weight: 69,
},
// Add more initial data as needed
];
await HealthData.insertMany(initialData);
console.log('Data seeded successfully.');
} else {
console.log('Data already exists. Skipping seed.');
}
} catch (error) {
console.error('Error seeding data:', error.message);
}
};
seedData();
//----------------------------//
// Routes
//----------------------------//
// Get all tracks
app.get('/tracks',
async (req, res) => {
try {
const allTracks = await HealthData.find();
res.json(allTracks);
} catch (error) {
console.error('Error fetching tracks:', error);
res.status(500)
.json(
{
error: 'Internal Server Error'
});
}
});
// Get tracks for a particular day
app.get('/tracks/:date', async (req, res) => {
const requestedDate = new Date(req.params.date);
try {
const tracksForDay =
await HealthData.find(
{
date: {
$gte: requestedDate,
$lt: new Date(
requestedDate.getTime()
+ 24 * 60 * 60 * 1000)
}
});
res.json(tracksForDay);
} catch (error) {
res.status(500)
.json({ error: 'Internal Server Error' });
}
});
// Update values for a particular day
app.put('/tracks/:date',
async (req, res) => {
const requestedDate =
new Date(req.params.date);
try {
const existingTrack =
await HealthData.findOne(
{
date:
{
$gte: requestedDate,
$lt: new Date(
requestedDate.getTime()
+ 24 * 60 * 60 * 1000
)
}
});
console.log('existing track', existingTrack);
if (existingTrack) {
// Update existing track
Object.assign(existingTrack, req.body);
await existingTrack.save();
res.json(existingTrack);
} else {
// Create new track for the day if it doesn't exist
const newTrack =
new HealthData(
{
date: requestedDate,
...req.body
});
await newTrack.save();
console.log(newTrack);
res.status(200).json(newTrack);
}
} catch (error) {
res.status(500)
.json(
{
error: 'Internal Server Error'
});
}
});
app.listen(PORT,
() => {
console.log(
`Server is running on port ${PORT}`
);
});
Steps to Setup Frontend with React
Step 1: Create React App:
npx create-react-app myapp
Step 2: Switch to the project directory:
cd myapp
Step 3: Installing the required packages:
npm install axios react-router-dom
Project Structure:
FrontendThe updated dependencies in package.json for frontend will look like:
"dependencies": {
"axios": "^1.5.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.17.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Explanation:
- Develop frontend components, including `TrackerApp`, `TrackerList`, and `TrackerCard`.
- Structure the components to represent the overall app layout and individual health tracker cards.
- Set up a Context API to manage the state of health data across components.
- Utilize `useState` and `useEffect` hooks for fetching initial data.
CSS
/*App.css*/
* {
background-color: #FBF6EE;
}
/* TrackerList.css */
.tracker-list {
display: flex;
flex-direction: column;
flex-wrap: wrap;
justify-content: center;
align-items: center;
max-width: 800px;
margin: 0 auto;
}
.tracker-list h2 {
width: 100%;
text-align: center;
color: #333;
margin-bottom: 16px;
}
#datePicker {
width: 200px;
}
.lists {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
/* TrackerCard.css */
.tracker-card {
background-color: #fff;
border: 1px solid #ddd;
border-radius: 8px;
padding: 16px;
margin: 16px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.312);
width: 300px;
box-sizing: border-box;
/* Include padding and border in the width */
}
.tracker-card h3 {
color: #333;
color: #FFB534;
}
.span {
font-weight: 800;
}
.tracker-card p {
margin: 8px 0;
color: #666;
}
/* TrackerApp */
.main-container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
color: #65B741;
}
/* Nav */
.nav {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 5px;
}
button {
background-color: #C1F2B0;
color: #FFB534;
}
#gfg {
background-color: #0fb300;
padding: 10px;
color: #FBF6EE;
border-radius: 10px;
}
/* Button.css */
.custom-button {
background-color: #3498db;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.custom-button:hover {
background-color: #2980b9;
}
/* Add any additional styles based on your design preferences */
/* HealthFormModal.css */
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
/* Semi-transparent black overlay */
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
/* Ensure it's above other content */
}
.health-form {
max-width: 400px;
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
z-index: 1001;
/* Ensure it's above the overlay */
}
.health-form h2 {
text-align: center;
color: #333;
}
/* HealthForm.css */
.health-form form {
display: flex;
flex-direction: column;
}
.health-form label {
margin-bottom: 10px;
font-size: 16px;
}
.health-form input {
padding: 8px;
font-size: 14px;
border: 1px solid #ddd;
border-radius: 4px;
margin-top: 4px;
}
.health-form button {
background-color: #3498db;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
margin-top: 10px;
transition: background-color 0.3s ease;
}
.health-form button:hover {
background-color: #2980b9;
}
.health-form button:last-child {
margin-top: 0;
/* Remove top margin for the close button */
background-color: #e74c3c;
}
.health-form button:last-child:hover {
background-color: #c0392b;
}
JavaScript
// src/App.js
import React from 'react';
import TrackerApp from './components/TrackerApp';
import './App.css'
function App() {
return (
<div className="App">
<TrackerApp />
</div>
);
}
export default App;
JavaScript
// src/components/TrackerApp.js
import React from 'react';
import Navbar from './Navbar';
import TrackerList from './TrackerList';
import { HealthProvider }
from '../context/HealthContext';
const TrackerApp = () => {
return (
<HealthProvider>
<div className='main-container'>
<Navbar />
<TrackerList />
</div>
</HealthProvider>
);
};
export default TrackerApp;
JavaScript
import React,
{
useContext,
useState
} from 'react';
import { HealthContext }
from '../context/HealthContext';
import TrackerCard from './TrackerCard';
const TrackerList = () => {
const { tracks, getTracksForDate } = useContext(HealthContext);
const [selectedDate, setSelectedDate] = useState(null);
const handleDateChange =
(event) => {
const selectedDate = event.target.value;
console.log(selectedDate);
setSelectedDate(selectedDate);
};
const filteredTracks =
selectedDate ?
getTracksForDate(selectedDate) : tracks;
return (
<div className="tracker-list">
<h2>Records List</h2>
<label htmlFor="datePicker">
Select a date:
</label>
<input
type="date"
id="datePicker"
value={selectedDate || ''}
onChange={handleDateChange} />
<div className='lists'>
{
filteredTracks.length === 0 ? (
<p>No tracks for the selected date.</p>
) : (
filteredTracks
.map(
(data) => (
<TrackerCard key={data.date} data={data} />
)
)
)
}
</div>
</div>
);
};
export default TrackerList;
JavaScript
import React from 'react';
const TrackerCard =
({ data }) => {
const {
date,
steps,
caloriesBurned,
distanceCovered,
weight,
} = data;
const formattedDate =
new Date(date).toLocaleDateString();
return (
<div className="tracker-card">
<h3> <span className='span'>
Date:
</span>
{formattedDate}
</h3>
<p>
<span className='span'>
Steps:
</span>
{steps}
</p>
<p>
<span className='span'>
Calories Burned:
</span>
{caloriesBurned}
</p>
<p>
<span className='span'>
Distance Covered:
</span>
{distanceCovered}
</p>
<p>
<span className='span'>
Weight:
</span>
{weight}Kg
</p>
</div>
);
};
export default TrackerCard;
JavaScript
// src/context/HealthContext.js
import React,
{
createContext,
useState,
useEffect
} from 'react';
import axios from 'axios';
const HealthContext = createContext();
const HealthProvider =
(
{
children
}
) => {
const [tracks, setTracks] = useState([]);
const [selectedDatqe, setSelectedDate] = useState(null);
useEffect(() => {
const fetchTracks =
async () => {
try {
const response =
await
axios.get('http://localhost:5000/tracks');
// Sort tracks by date in descending order (most recent first)
const sortedTracks =
(response.data)
.slice()
.sort(
(a, b) =>
new Date(b.date) -
new Date(a.date));
setTracks(sortedTracks);
} catch (error) {
console.error(
'Error fetching health tracks:',
error.message);
}
};
fetchTracks();
}, []);
const updateTrack =
async (date, newData) => {
try {
const response =
await axios
.put(
`http://localhost:5000/tracks/${date}`, newData);
setTracks(
(prevTracks) => {
const isoDate =
new Date(date).toISOString();
const index =
prevTracks.findIndex(
(track) =>
new Date(track.date)
.toISOString() === isoDate);
console.log('index: ', index);
if (index !== -1) {
// Replace the object at the found index
const updatedTracks = [...prevTracks];
updatedTracks[index] = response.data;
return updatedTracks;
}
// If the track with the given date
// is not found, return the original array
return prevTracks;
});
console.log('tracks updated', tracks);
} catch (error) {
console.error(
'Error updating health track:',
error.message
);
}
};
const getTracksForDate =
(date) => {
// Convert the input date string to a Date object
const selectedDate = new Date(date);
// Filter tracks based on the selected Date
const filteredTracks =
tracks.filter(
(track) => {
const trackDate =
new Date(track.date);
return trackDate.toISOString()
.split('T')[0] ===
selectedDate.toISOString()
.split('T')[0];
});
return filteredTracks;
};
const value = {
tracks,
setSelectedDate,
updateTrack,
getTracksForDate,
};
return <HealthContext.Provider
value={value}>
{children}
</HealthContext.Provider>;
};
export { HealthContext, HealthProvider };
Steps to run the App:
To run server.js:
node server.js
To run frontend:
npm start
Output:
Output of Data Saved in Database:
Db
Similar Reads
MERN Stack The MERN stack is a widely adopted full-stack development framework that simplifies the creation of modern web applications. Using JavaScript for both the frontend and backend enables developers to efficiently build robust, scalable, and dynamic applications.What is MERN Stack?MERN Stack is a JavaSc
9 min read
MERN Full Form MERN Stack is a JavaScript Stack that is used for easier and faster deployment of full-stack web applications. The full form of MERN includes four powerful technologies:MongoDBExpress.jsReact.jsNode.jsThese technologies together provide a full-stack JavaScript framework for developing modern, dynami
2 min read
How to Become a MERN Stack Developer? Do you also get amazed at those beautiful websites that appear in front of you? Those are designed by none other than Full-Stack Developers Or MERN stack developers. They are software developers who specialize in building web applications using the MERN stack, which is a popular set of technologies
6 min read
Difference between MEAN Stack and MERN Stack Web development is a procedure or process for developing a website. A website basically contains three ends: the client side, the server side, and the database. These three are different sides of an application that combine together to deliver an application; all ends are implemented separately with
3 min read
Best Hosting Platforms for MERN Projects Hosting your website grants you the thrilling opportunity to showcase it to the world. Whether you choose free or paid hosting, the process of deploying your website fills you with a mix of excitement, pride, and nervousness. You eagerly await user feedback, enthusiastically embracing the chance to
5 min read
Getting Started with React & Frontend
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. "Hello, World!" Program in ReactJavaScriptimport React from 'react'; function App() {
6 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React ComponentsIn React, components are reusable, independent blocks that define the structure and behavior of the UI. They accept inputs (props) and return elements that describe what should appear on the screen.Key Concepts of React Components:Each component handles its own logic and UI rendering.Components can
4 min read
ReactJS Props - Set 1The react props refer to properties in react that are passed down from parent component to child to render the dynamic content.Till now we have worked with components using static data only. In this article, we will learn about react props and how we can pass information to a Component.What are Prop
5 min read
ReactJS StateIn React, the state refers to an object that holds information about a component's current situation. This information can change over time, typically as a result of user actions or data fetching, and when state changes, React re-renders the component to reflect the updated UI. Whenever state change
4 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
React ListsIn lists, React makes it easier to render multiple elements dynamically from arrays or objects, ensuring efficient and reusable code. Since nearly 85% of React projects involve displaying data collectionsâlike user profiles, product catalogs, or tasksâunderstanding how to work with lists.To render a
4 min read
Create ToDo App using ReactJSIn this article, we will create a to-do app to understand the basics of ReactJS. We will be working with class based components in this application and use the React-Bootstrap module to style the components. This to-do list allows users to add new tasks and delete them by clicking the corresponding
3 min read
Redux Setup and basics
Introduction to Redux (Action, Reducers and Store)Redux is a state managing library used in JavaScript apps. It simply manages the state of your application or in other words, it is used to manage the data of the application. It is used with a library like React.Uses: It makes easier to manage state and data. As the complexity of our application in
4 min read
Redux and The Flux ArchitectureFlux Architecture: Flux is AN architecture that Facebook uses internally when operating with React. It is not a framework or a library. It is merely a replacement quite an architecture that enhances React and also the idea of unidirectional data flow. Redux is a predictable state container for JavaS
5 min read
React Redux Hooks: useSelector and useDispatch.State management is a major aspect of building React applications, allowing users to maintain and update application state predictably. With the introduction of React Hooks, managing state has become even more streamlined and efficient. Among the most commonly used hooks for state management in Reac
4 min read
What are Action's creators in React Redux?In React Redux, action creators are functions that create and return action objects. An action object is a plain JavaScript object that describes a change that should be made to the application's state. Action creators help organize and centralize the logic for creating these action objects.Action C
4 min read
What is Redux Thunk?Redux Thunk is like a co-worker for Redux, giving it the power to handle asynchronous actions. It's that extra tool that allows your Redux store to deal with things like fetching data from a server or performing tasks that take some time. With Redux Thunk, your app can smoothly manage both synchrono
3 min read
Creating custom middlewares in React ReduxIn React-Redux applications, managing the flow of data is crucial for building efficient and scalable apps. Redux provides a powerful state management solution, and custom middleware adds an extra layer of flexibility to handle complex scenarios effectively. Let's understand custom middleware in sim
5 min read
Common middleware libraries used in ReduxMiddleware libraries play a crucial role in Redux applications, enabling users to extend and enhance Redux's capabilities. The middleware libraries offer a wide range of capabilities and cater to different use cases and preferences. users can choose the middleware that best fits their requirements a
5 min read
Express and Mongo Setup
Mongo with Express TutorialMongoDB and ExpressJS are a powerful pair for web development. MongoDB provides flexible data storage, while ExpressJS simplifies server-side logic. Together, they make it easy to create modern web applications efficiently. MongoDB's document-based approach and ExpressJS's streamlined backend develo
5 min read
How to Install MongoDB on Windows?Looking to install MongoDB on your Windows machine? This detailed guide will help you install MongoDB on Windows (Windows Server 2022, 2019, and Windows 11) quickly and efficiently. Whether you are a developer or a beginner, follow this guide for seamless MongoDB installation, including setting up e
6 min read
How to Install Express in a Node Project?ExpressJS is a popular, lightweight web framework for NodeJS that simplifies the process of building web applications and APIs. It provides a robust set of features for creating server-side applications, including routing, middleware support, and easy integration with databases and other services.Be
2 min read
Mongoose Module IntroductionMongoose is a popular Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a straightforward and structured way to interact with MongoDB, allowing you to define schemas for your collections, apply constraints, and validate data before storing it in the database. In this guide, we'
5 min read
Mongoose ConnectionsA Mongoose connection is a Node.js module that establishes and manages connections between a Node.js application and a MongoDB database. It optimizes resource utilization, handles connection pooling, and manages errors, facilitating efficient data operations.What is Mongoose Connection?A Mongoose co
6 min read
How to Connect MongoDB with a Node.js Application using MongooseJSMongoose is a powerful MongoDB object modeling library for Node.js enabling you to easily interact between your Node.js app and MongoDB. In this article we are going to explore how you can connect your Node.js app to MongoDB using MongooseJS. You will learn how to create a connection, specify schema
4 min read
Node.js CRUD Operations Using Mongoose and MongoDB AtlasCRUD (Create, Read, Update, Delete) operations are fundamental in web applications for managing data. Mongoose simplifies interaction with MongoDB, offering a schema-based approach to model data efficiently. MongoDB Atlas is a fully managed cloud database that simplifies the process of setting up, m
8 min read
Signup Form Using Node.js and MongoDBInstallations First, we need to include a few packages for our Nodejs application. npm install express --save Express allows us to set up middlewares to respond to HTTP Requests. npm install body-parser --save If you want to read HTTP POST data , you have to use the "body-parser" node module. npm in
3 min read
API Routing and Authentication
Postman- Backend Testing
Introduction to Postman for API DevelopmentPostman: Postman is an API(application programming interface) development tool that helps to build, test and modify APIs. Almost any functionality that could be needed by any developer is encapsulated in this tool. It is used by over 5 million developers every month to make their API development eas
7 min read
Basics of API Testing Using PostmanAPIs(Application Programming Interfaces) are very commonly used in development. Postman is a tool that can be used for API Testing. In this article, we will learn how to do simple API Testing using Postman. Go to your workspace in Postman.Click on the + symbol to open a new tab.Enter the API Endpoin
2 min read
How to use postman for testing express applicationTesting an Express app is very important to ensure its capability and reliability in different use cases. There are many options available like Thunder client, PAW, etc but we will use Postman here for the testing of the Express application. It provides a great user interface and numerous tools whic
3 min read
How to send different types of requests (GET, POST, PUT, DELETE) in Postman.In this article, we are going to learn how can we send different types of requests like GET, POST, PUT, and DELETE in the Postman. Postman is a popular API testing tool that is used to simplify the process of developing and testing APIs (Application Programming Interface). API acts as a bridge betwe
5 min read
How to test GET Method of express with Postman ?The GET method is mainly used on the client side to send a request to a specified server to get certain data or resources. By using this GET method we can only access data but can't change it, we are not allowed to edit or completely change the data. It is widely one of the most used methods. In thi
2 min read
How to test POST Method of Express with Postman?The POST method is a crucial aspect of web development, allowing clients to send data to the server for processing. In the context of Express, a popular web framework for Node, using the POST method involves setting up routes to handle incoming data. In this article, we'll explore how to test the PO
2 min read
How to test DELETE Method of Express with Postman ?The DELETE method is an essential part of RESTful web services used to remove specific resources from a server. Whether you are building a simple API or a complex web application, knowing how to use this method effectively is key. Here, we will explore how to Implement the DELETE method in Express.j
3 min read
How to create and write tests for API requests in Postman?Postman is an API(utility programming interface) development device that enables to construct, take a look at and alter APIs. It could make numerous varieties of HTTP requests(GET, POST, PUT, PATCH), store environments for later use, and convert the API to code for various languages(like JavaScript,
3 min read