Travel Planning App API using Node & Express.js
Last Updated :
05 Apr, 2024
In this article, we’ll walk through the step-by-step process of creating a Travel Planning App With Node and ExpressJS. This application will provide users with the ability to plan their trips by searching for destinations, booking flights and hotels, submitting reviews, receiving notifications, sharing their trips on social media, and processing payments.
Prerequisites:
Approach to Create Travel Planning App API using Node and ExpressJS:
- Identify key features like user authentication, booking flights/hotels, reviews, notifications, and payments.
- Install Node.js, npm, and ExpressJS.
- Create a new project directory and initialize it.
- Implement features like user authentication, booking, review submission, and payment processing using Express.js controllers and routes.
- Integrate third-party APIs for flight/hotel booking, implement notifications, and enable trip sharing on social media.
Steps to Create the NodeJS App and Installing Module:
Step 1: Create a NodeJS project using the following command.
npm init -y
Step 2: Install Express.js and other necessary dependencies.
npm install express mongoose body-parser bcrypt jsonwebtoken
Step 3: Create folders for different parts of the application such as models, controllers, routes, and middleware. Inside each folder, create corresponding files for different components of the application.
Step 4: Set up a MongoDB database either locally or using a cloud-based service like MongoDB Atlas. Define Mongoose models for the data entities such as User, Trip, Booking, Review, Notification, and Payment.
Step 5: Create controller functions for each feature such as searchDestinations, bookFlight, bookHotel, submitReview, sendNotification, shareTrip, and processPayment. Implement authentication middleware (authenticate) to protect routes that require authentication. Define route handlers for each feature in separate route files (authRoutes.js, tripRoutes.js, bookingRoutes.js, etc.).
Project Structure:
Project Folder StructureThe updated dependencies in package.json file will look like:
"dependencies": {
"express": "^4.18.2",
"mongoose": "^8.2.1",
"body-parser": "^1.20.2",
"bcrypt": "^5.1.1",
"jsonwebtoken": "^9.0.2"
}
Example: Below is an example of Travel Planning App with NodeJS and ExpressJS.
JavaScript
// authController.js
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const { secret } = require('../config');
async function signup(req, res) {
try {
const { email, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
const user = await User.create({
email, password: hashedPassword
});
res.status(201).json({ user });
} catch (error) {
res.status(400).json({
error: error.message
});
}
}
async function login(req, res) {
try {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user) {
throw new Error('User not found');
}
const validPassword = await bcrypt.compare(
password, user.password);
if (!validPassword) {
throw new Error('Invalid password');
}
const token = jwt.sign({
userId: user._id
},
secret, { expiresIn: '1h' });
res.status(200).json({ token });
} catch (error) {
res.status(401).json({
error: error.message
});
}
}
module.exports = { signup, login };
JavaScript
// bookingController.js
const Booking = require('../models/Booking');
async function bookFlight(req, res) {
try {
/* Assuming request body contains
necessary details for flight booking
*/
const { userId, tripId, flightDetails } = req.body;
// Create a new flight booking document in the database
const booking = await Booking.create({
userId,
tripId,
type: 'Flight',
details: flightDetails,
// Store flight details in the database
});
res.status(201).json({ booking });
} catch (error) {
res.status(400).json({
error: error.message
});
}
}
async function bookHotel(req, res) {
try {
/* Assuming request body contains
necessary details for hotel booking
*/
const { userId, tripId, hotelDetails } = req.body;
// Create a new hotel booking document in the database
const booking = await Booking.create({
userId,
tripId,
type: 'Hotel',
details: hotelDetails,
// Store hotel details in the database
});
res.status(201).json({ booking });
} catch (error) {
res.status(400).json({
error: error.message
});
}
}
module.exports = { bookFlight, bookHotel };
JavaScript
// notificationController.js
const Notification = require('../models/Notification');
async function sendNotification(req, res) {
try {
/* Assuming request body contains
necessary details for sending notification
*/
const { userId, message } = req.body;
// Create a new notification document in the database
const notification = await Notification.create({
userId,
message,
sentAt: new Date(),
// Record the time when the notification is sent
});
res.status(201).json({ notification });
} catch (error) {
res.status(400).json({
error: error.message
});
}
}
module.exports = { sendNotification };
JavaScript
// paymentController.js
const Payment = require('../models/Payment');
async function processPayment(req, res) {
try {
/*
Assuming request body contains
necessary details for processing payment
*/
const { userId, amount, paymentDetails } = req.body;
// Create a new payment document in the database
const payment = await Payment.create({
userId,
amount,
paymentDetails, // Store payment details in the database
status: 'Success', // Assuming payment is successful
createdAt: new Date(),
// Record the time when the payment is processed
});
res.status(201).json({ payment });
} catch (error) {
res.status(400).json({
error: error.message
});
}
}
module.exports = { processPayment };
JavaScript
// reviewController.js
const Review = require('../models/Review');
async function submitReview(req, res) {
try {
/* Assuming request body contains necessary
details for submitting a review
*/
const { userId, destination, rating, comment } = req.body;
// Create a new review document in the database
const review = await Review.create({
userId,
destination,
rating,
comment,
createdAt: new Date(),
// Record the time when the review is submitted
});
res.status(201).json({ review });
} catch (error) {
res.status(400).json({
error: error.message });
}
}
module.exports = { submitReview };
JavaScript
// socialController.js
async function shareTrip(req, res) {
try {
/* Assuming request body contains necessary
details for sharing a trip
*/
const { userId, tripId, socialMedia, message } = req.body;
// Implement social sharing logic here
// Assuming sharing is successful
res.status(200).json({
message: 'Trip shared successfully'
});
} catch (error) {
res.status(400).json({
error: error.message
});
}
}
module.exports = { shareTrip };
JavaScript
// tripController.js
const Trip = require('../models/Trip');
async function searchDestinations(req, res) {
try {
/* For simplicity, let's assume we return a
list of destinations from the database
*/
const destinations = await Trip.find().distinct('destination');
res.status(200).json({ destinations });
} catch (error) {
res.status(400).json({ error: error.message });
}
}
async function createItinerary(req, res) {
try {
/* Assuming request body contains necessary
details for creating an itinerary
*/
const { userId, destination, startDate, endDate } = req.body;
// Create a new itinerary document in the database
const itinerary = await Trip.create({
userId,
destination,
startDate,
endDate,
createdAt: new Date(),
// Record the time when the itinerary is created
});
res.status(201).json({ itinerary });
} catch (error) {
res.status(400).json({ error: error.message });
}
}
module.exports = { searchDestinations, createItinerary };
JavaScript
// authMiddleware.js
const jwt = require('jsonwebtoken');
const { secret } = require('../config');
function authenticate(req, res, next) {
const token = req.headers.authorization;
if (!token) {
return res.status(401).json({
error: 'Authorization header missing'
});
}
try {
const decodedToken = jwt.verify(token, secret);
req.userId = decodedToken.userId;
next();
} catch (error) {
return res.status(401).json({
error: 'Invalid token'
});
}
}
module.exports = { authenticate };
JavaScript
// errorMiddleware.js
function errorHandler(err, req, res, next) {
console.error(err.stack);
res.status(500).json({
error: 'Something went wrong!'
});
}
module.exports = { errorHandler };
JavaScript
// Booking.js
const mongoose = require('mongoose');
const bookingSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
tripId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Trip',
required: true
},
type: {
type: String,
required: true
}, // Flight, Hotel, Car, etc.
// Add more fields as needed
});
const Booking = mongoose.model('Booking', bookingSchema);
module.exports = Booking;
JavaScript
// Notification.js
const mongoose = require('mongoose');
const notificationSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User', required: true
},
message: {
type: String,
required: true
},
// Add more fields as needed
});
const Notification = mongoose.model('Notification', notificationSchema);
module.exports = Notification;
JavaScript
// Payment.js
const mongoose = require('mongoose');
const paymentSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User', required: true
},
amount: {
type: Number,
required: true
},
status: {
type: String,
default: 'Pending'
},
// Add more fields as needed
});
const Payment = mongoose.model('Payment', paymentSchema);
module.exports = Payment;
JavaScript
// Review.js
const mongoose = require('mongoose');
const reviewSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User', required: true
},
destination: {
type: String,
required: true
},
rating: {
type: Number,
required: true
},
comment: {
type: String
},
// Add more fields as needed
});
const Review = mongoose.model('Review', reviewSchema);
module.exports = Review;
JavaScript
// Trip.js
const mongoose = require('mongoose');
const tripSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User', required: true
},
destination: {
type: String,
required: true
},
startDate: {
type: Date,
required: true
},
endDate: {
type: Date,
required: true
},
// Add more fields as needed
});
const Trip = mongoose.model('Trip', tripSchema);
module.exports = Trip;
JavaScript
// User.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
// Add more fields as needed
});
const User = mongoose.model('User', userSchema);
module.exports = User;
JavaScript
// authRoutes.js
const express = require('express');
const router = express.Router();
const { signup, login } = require('../controllers/authController');
router.post('/signup', signup);
router.post('/login', login);
module.exports = router;
JavaScript
// bookingRoutes.js
const express = require('express');
const router = express.Router();
const { bookFlight, bookHotel } = require('../controllers/bookingController');
const { authenticate } = require('../middleware/authMiddleware');
router.post('/book-flight', authenticate, bookFlight);
router.post('/book-hotel', authenticate, bookHotel);
module.exports = router;
JavaScript
// notificationRoutes.js
const express = require('express');
const router = express.Router();
const { sendNotification } = require('../controllers/notificationController');
const { authenticate } = require('../middleware/authMiddleware');
router.post('/send-notification', authenticate, sendNotification);
module.exports = router;
JavaScript
// paymentRoutes.js
const express = require('express');
const router = express.Router();
const { processPayment } = require('../controllers/paymentController');
const { authenticate } = require('../middleware/authMiddleware');
router.post('/process-payment', authenticate, processPayment);
module.exports = router;
JavaScript
// reviewRoutes.js
const express = require('express');
const router = express.Router();
const { submitReview } = require('../controllers/reviewController');
const { authenticate } = require('../middleware/authMiddleware');
router.post('/submit-review', authenticate, submitReview);
module.exports = router;
JavaScript
// socialRoutes.js
const express = require('express');
const router = express.Router();
const { shareTrip } = require('../controllers/socialController');
const { authenticate } = require('../middleware/authMiddleware');
router.post('/share-trip', authenticate, shareTrip);
module.exports = router;
JavaScript
// tripRoutes.js
const express = require('express');
const router = express.Router();
const { searchDestinations, createItinerary } = require('../controllers/tripController');
const { authenticate } = require('../middleware/authMiddleware');
router.get('/destinations', searchDestinations);
router.post('/itinerary', authenticate, createItinerary);
module.exports = router;
JavaScript
// constants.js
const secret = 'your_secret_key_here';
module.exports = { secret };
JavaScript
// helper.js
// This file contains helper functions that can be used across the application
function formatDate(date) {
// Implement date formatting logic here
const options = {
year: 'numeric',
month: 'long',
day: 'numeric'
};
return date.toLocaleDateString('en-US', options);
}
function calculateTotalCost(items) {
// Implement logic to calculate total cost based on items
return items.reduce(
(total, item) => total + item.cost, 0);
}
module.exports = { formatDate, calculateTotalCost };
JavaScript
// app.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const authRoutes = require('./routes/authRoutes');
const tripRoutes = require('./routes/tripRoutes');
const bookingRoutes = require('./routes/bookingRoutes');
const reviewRoutes = require('./routes/reviewRoutes');
const notificationRoutes = require('./routes/notificationRoutes');
const socialRoutes = require('./routes/socialRoutes');
const paymentRoutes = require('./routes/paymentRoutes');
const { errorHandler } = require('./middleware/errorMiddleware');
// Initialize Express app
const app = express();
// Middleware
app.use(bodyParser.json());
// Connect to MongoDB
mongoose.connect('mongodb+srv://admn:<password>@cluster0.tudvjbv.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('Connected to MongoDB'))
.catch(error => console.error('MongoDB connection error:', error));
// Routes
app.use('/api/auth', authRoutes);
app.use('/api/trip', tripRoutes);
app.use('/api/booking', bookingRoutes);
app.use('/api/review', reviewRoutes);
app.use('/api/notification', notificationRoutes);
app.use('/api/social', socialRoutes);
app.use('/api/payment', paymentRoutes);
// Error handling middleware
app.use(errorHandler);
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
JavaScript
// config.js
module.exports = {
secret: 'your_secret_key_here',
};
Start your server using the following command:
node app.js
Output:
Final Output
Similar Reads
Web and API Development
How to build Node.js Blog API ?
In this article, we are going to create a blog API using Node.js. A Blog API is an API by which users can fetch blogs, write blogs to the server, delete blogs, and even filter blogs with various parameters. Functionalities: Fetch BlogsCreate BlogsDelete BlogsFilter BlogsApproach: In this project, we
5 min read
RESTful Blogging API with Node and Express.js
Blogs Websites have become very popular nowadays for sharing your thoughts among the users over internet. In this article, you will be guided through creating a Restful API for the Blogging website with the help of Node, Express, and MongoDB. Prerequisites:Node JS & NPMExpress JSMongoDBApproach
6 min read
Build a Social Media REST API Using Node.js: A Complete Guide
Developers build an API(Application Programming Interface) that allows other systems to interact with their Applicationâs functionalities and data. In simple words, API is a set of protocols, rules, and tools that allow different software applications to access allowed functionalities, and data and
15+ min read
Communication and Social Platforms
Management Systems
Customer Relationship Management (CRM) System with Node.js and Express.js
CRM systems are important tools for businesses to manage their customer interactions, both with existing and potential clients. In this article, we will demonstrate how to create a CRM system using Node.js and Express. We will cover the key functionalities, prerequisites, approach, and steps require
15+ min read
Library Management Application Backend
Library Management System backend using Express and MongoDB contains various endpoints that will help to manage library users and work with library data. The application will provide an endpoint for user management. API will be able to register users, authenticate users, borrow books, return books,
10 min read
How to Build Library Management System Using NodeJS?
A Library Management System is an essential application for managing books, users, and transactions in a library. It involves adding, removing, updating, and viewing books and managing users. In this article, we will walk through how to build a simple Library Management System using NodeJS. What We
6 min read
Student Management System using Express.js and EJS Templating Engine
In this article, we build a student management student which will have features like adding students to a record, removing students, and updating students. We will be using popular web tools NodeJS, Express JS, and MongoDB for the backend. We will use HTML, CSS, and JavaScript for the front end. We'
5 min read
Subscription Management System with NodeJS and ExpressJS
In this article, weâll walk through the step-by-step process of creating a Subscription Management System with NodeJS and ExpressJS. This application will provide users with the ability to subscribe to various plans, manage their subscriptions, and include features like user authentication and autho
5 min read
Building a Toll Road Management System using Node.js
In this article, we are going to build a simple Toll Road Management System using Node.js, where the data will be stored in a local MongoDB database. Problem Statement: In a toll tax plaza, it is difficult to record all the transactions and store them in a single place, along with that, if required,
15+ min read
How to Build User Management System Using NodeJS?
A User Management System is an essential application for handling user accounts and information. It involves creating, reading, updating, and deleting user accounts, also known as CRUD operations. In this article, we will walk through how to build a simple User Management System using NodeJS. What W
6 min read
User Management System Backend
User Management System Backend includes numerous endpoints for performing user-dealing tasks. The backend could be constructed with the use of NodeJS and MongoDB with ExpressJS . The software will offer an endpoint for consumer management. API will be capable of registering, authenticating, and cont
4 min read
File and Document Handling
Build a document generator with Express using REST API
In the digital age, the need for dynamic and automated document generation has become increasingly prevalent. Whether you're creating reports, invoices, or any other type of document, having a reliable system in place can streamline your workflow. In this article, we'll explore how to build a Docume
2 min read
DOCX to PDF Converter using Express
In this article, we are going to create a Document Conversion Application that converts DOCX to PDF. We will follow step by step approach to do it. We also make use of third-party APIs. Prerequisites:Express JS multernpm Preview of the final output: Let us have a look at how the final output will lo
4 min read
How to Send Email using NodeJS?
Sending emails programmatically is a common requirement in many applications, especially for user notifications, order confirmations, password resets, and newsletters. In this article, we will learn how to build a simple email-sending system using NodeJS. We will use Nodemailer, a popular module for
5 min read
File Sharing Platform with Node.js and Express.js
In today's digital age, the need for efficient File sharing platforms has become increasingly prevalent. Whether it's sharing documents for collaboration or distributing media files, having a reliable solution can greatly enhance productivity and convenience. In this article, we'll explore how to cr
4 min read
React Single File Upload with Multer and Express.js
When we want to add functionality for uploading or deleting files, file storage becomes crucial, whether it's for website or personal use. The File Storage project using Express aims to develop a web application that provides users with a secure and efficient way to store and manage their files onli
5 min read
Task and Project Management
Task Management System using Node and Express.js
Task Management System is one of the most important tools when you want to organize your tasks. NodeJS and ExpressJS are used in this article to create a REST API for performing all CRUD operations on task. It has two models User and Task. ReactJS and Tailwind CSS are used to create a frontend inter
15+ min read
Task Manager App using Express, React and GraphQL.
The Task Manager app tool is designed to simplify task management with CRUD operation: creation, deletion, and modification of tasks. Users can easily generate new tasks, remove completed ones, and update task details. In this step-by-step tutorial, you will learn the process of building a Basic Tas
6 min read
Simple Task Manager CLI Using NodeJS
A Task Manager is a very useful tool to keep track of your tasks, whether it's for personal use or a work-related project. In this article, we will learn how to build a Simple Task Manager CLI (Command Line Interface) application using Node.js. What We Are Going to Create?We will build a CLI task ma
5 min read
Task Scheduling App with Node and Express.js
Task Scheduling app is an app that can be used to create, update, delete, and view all the tasks created. It is implemented using NodeJS and ExpressJS. The scheduler allows users to add tasks in the cache of the current session, once the app is reloaded the data gets deleted. This can be scaled usin
4 min read
Todo List CLI application using Node.js
CLI is a very powerful tool for developers. We will be learning how to create a simple Todo List application for command line. We have seen TodoList as a beginner project in web development and android development but a CLI app is something we don't often hear about. Pre-requisites:A recent version
13 min read