0% found this document useful (0 votes)
3 views62 pages

Module 5

This document provides an overview of React and Vue, two popular JavaScript libraries and frameworks for building web applications. It covers key features, setup instructions, and comparisons between React and Angular, as well as an introduction to PHP for server-side scripting. The document also includes examples of creating components and rendering them in both React and Vue, along with a brief history of their development.

Uploaded by

sranjana18
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views62 pages

Module 5

This document provides an overview of React and Vue, two popular JavaScript libraries and frameworks for building web applications. It covers key features, setup instructions, and comparisons between React and Angular, as well as an introduction to PHP for server-side scripting. The document also includes examples of creating components and rendering them in both React and Vue, along with a brief history of their development.

Uploaded by

sranjana18
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module-5 Back-End Integration and Deployment:

React Introduction

ReactJS 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.

●​ It is developed and maintained by Facebook.


●​ The latest version of React is React 19.
●​ Uses a virtual DOM for faster updates.
●​ Supports a declarative approach to designing UI components.
●​ Ensures better application control with one-way data binding.

Setting up a React Environment

If you have npx and [Link] installed, you can create a React application by using
create-react-app.

If you've previously installed create-react-app globally, it is recommended that you uninstall the
package to ensure npx always uses the latest version of create-react-app.

To uninstall, run this command: npm uninstall -g create-react-app.

Run this command to create a React application named my-react-app:

npx cate-react-app my-react-app

The create-react-app will set up everything you need to run a React application.

Run the React Application

Now you are ready to run your first real React application!

Run this command to move to the my-react-app directory:


Module-5 Back-End Integration and Deployment:

cd my-react-app

Run this command to run the React application my-react-app:

npm start

A new browser window will pop up with your newly created React App! If not, open your
browser and type localhost:3000 in the address bar.

"Hello, World!" Program in React


import React from 'react';

In this example:

●​ import React from 'react': Imports React to create components and use JSX.
●​ function App() { ... }: Defines a functional component called App.
●​ return ( ... ): Returns JSX that represents the UI (a div with an h1 tag displaying
"Hello, World!").
●​ export default App: Exports the App component so it can be used elsewhere.

How does React work?

React operates by creating an in-memory virtual DOM rather than directly manipulating the
browser’s DOM. It performs necessary manipulations within this virtual representation
before applying changes to the actual browser DOM.
Module-5 Back-End Integration and Deployment:

Here’s how the process works:

1. Actual DOM and Virtual DOM

●​ Initially, there is an Actual DOM(Real DOM) containing a div with two child
elements: h1 and h2.
●​ React maintains a previous Virtual DOM to track the UI state before any updates.

2. Detecting Changes

●​ When a change occurs (e.g., adding a new h3 element), React generates a New
Virtual DOM.
●​ React compares the previous Virtual DOM with the New Virtual DOM using a
process called reconciliation.

3. Efficient DOM Update

●​ React identifies the differences (in this case, the new h3 element).
●​ Instead of updating the entire DOM, React updates only the changed part in the
New Actual DOM, making the update process more efficient.

Key Features of React


Module-5 Back-End Integration and Deployment:

React is one of the most demanding JavaScript libraries because it is equipped with a ton of
features which makes it faster and production-ready. Below are the few features of React.

1. Virtual DOM

React uses a Virtual DOM to optimize UI rendering. Instead of updating the entire real DOM
directly, React:

●​ Creates a lightweight copy of the DOM (Virtual DOM).


●​ Compare it with the previous version to detect changes (diffing).
●​ Updates only the changed parts in the actual DOM (reconciliation), improving
performance.

2. Component-Based Architecture

React follows a component-based approach, where the UI is broken down into reusable
components. These components:

●​ Can be functional or class-based.


●​ It allows code reusability, maintainability, and scalability.

3. JSX (JavaScript XML)

React usesJSX, a syntax extension that allows developers to write HTML inside JavaScript.
JSX makes the code:

●​ More readable and expressive.


●​ Easier to understand and debug.

4. One-Way Data Binding

React uses one-way data binding, meaning data flows in a single direction from parent
components to child components via props. This provides better control over data and helps
maintain predictable behavior.
Module-5 Back-End Integration and Deployment:

5. React Router

React provides a React Router for managing navigation in single-page applications (SPAs). It
enables dynamic routing without requiring full-page reloads.

What is Babel?

Babel is a JavaScript compiler that can translate markup or programming languages into
JavaScript.

Babel is available for different conversions. React uses Babel to convert JSX into JavaScript.
Applications of React

●​ Web Development: React is used to build dynamic and responsive web


applications, including social media platforms, e-commerce sites, and blogs.
●​ Mobile Apps: React Native allows developers to build mobile apps for iOS and
Android using the same codebase.
●​ Enterprise Applications: React is used in building large-scale enterprise
applications that require a highly interactive UI.
●​ Dashboards and Data Visualizations: React is great for building real-time
dashboards and data visualization tools due to its high performance.

React vs Angular
Module-5 Back-End Integration and Deployment:

React Angular

React is a JavaScript library Angular is a JavaScript framework

React uses one-way data binding, Angular uses two-way data binding

React uses JSX (JavaScript XML) for Angular uses HTML templates with
templating. special Angular directives.

React uses the Virtual Dom concept Angular used the Real Dom concept

History of React

●​ React was developed by Facebook in 2011 to improve the performance of


their applications and was officially released as an open-source library in
2013.
●​ It was designed to create dynamic, fast, and responsive user interfaces for
web applications by focusing on the view layer.
●​ React introduced concepts like components (reusable UI pieces) and the
virtual DOM (a lightweight copy of the real DOM) for optimizing UI updates.
Module-5 Back-End Integration and Deployment:

●​ React is now a widely used framework for building modern web and mobile
apps, supported by a strong community and major companies.

React JS ReactDOM
ReactDom is a core react package that provides methods to interact with the Document
Object Model or DOM. This package allows developers to access and modify the DOM.
How to use ReactDOM ?
To use the ReactDOM in any React web app we must first install the react-dom package in
our project. To install the react-dom package use the following command.
// Installing
npm i react-dom
After installing the package use the following command to import the package in your
application file
// Importing
import ReactDOM from 'react-dom'
After installing react-dom it will appear in the dependenices in [Link] file like:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
}
React Render HTML

React's goal is in many ways to render HTML in a web page.

React renders HTML to the web page by using a function called createRoot() and its method
render().

The createRoot Function

The createRoot() function takes one argument, an HTML element.

The purpose of the function is to define the HTML element where a React component should
be displayed.

The render Method


Module-5 Back-End Integration and Deployment:

The render() method is then called to define the React component that should be rendered.

But render where?

There is another folder in the root directory of your React project, named "public". In this
folder, there is an [Link] file.

You'll notice a single <div> in the body of this file. This is where our React application will
be rendered.

import React from 'react';


import ReactDOM from 'react-dom/client';

const container = [Link]('root');


const root = [Link](container);
[Link](<p>Hello</p>);

React Components
Components are independent and reusable bits of code. They serve the same purpose as
JavaScript functions, but work in isolation and return HTML.

Components come in two types, Class components and Function components, in this tutorial
we will concentrate on Function components
Create Your First Component

When creating a React component, the component's name MUST start with an upper
case letter.

Class Component

A class component must include the extends [Link] statement. This


statement creates an inheritance to [Link], and gives your component access
to [Link]'s functions.

The component also requires a render() method, this method returns HTML.

Function Component

Here is the same example as above, but created using a Function component instead.
Module-5 Back-End Integration and Deployment:

A Function component also returns HTML, and behaves much the same way as a Class
component, but Function components can be written using much less code, are easier to
understand, and will be preferred in this tutorial.

Create a Function component called Car

function Car() {
return <h2>Hi, I am a Car!</h2>;
}

Rendering a Component

Now your React application has a component called Car, which returns an <h2>
element.

To use this component in your application, use similar syntax as normal HTML: <Car
/>

Example

Display the Car component in the "root" element:

const root = [Link]([Link]('root'));

[Link](<Car />);

Vue Introduction
Vue is a JavaScript Framework

Vue is a front-end JavaScript framework written in [Link] You, a Google employee


using AngularJS, started to develop Vue in 2013.
Module-5 Back-End Integration and Deployment:

Vue version 1.0 was released in 2015.

Similar frameworks to Vue are React and Angular, but Vue is more lightweight and easier to
start with.

Vue is distributed as a JavaScript file, and can be added to a web page with a script tag:

<script

src="[Link]

</script>

Why Learn Vue?

●​ It is simple and easy to use.


●​ It is able to handle both simple and complex projects.
●​ Its growing popularity and open-source community support.
●​ In normal JavaScript we need to write HOW HTML and JavaScript is connected, but
in Vue we simply need to make sure that there IS a connection and let Vue take care
of the rest.
●​ It allows for a more efficient development process with a template-based syntax,
two-way data binding, and a centralized state management.

If some of these points are hard to understand, don't worry, you will understand at the end of
the tutorial.

The Options API

There are two different ways to write code in Vue: The Options API and The Composition
API.

The underlying concepts are the same for both the Options API and Composition API, so
after learning one, you can easily switch to the other.

The Options API is what is written in this tutorial because it is considered to be more
beginner-friendly, with a more recognizable structure.

Take a look at this page at the end of this tutorial to learn more about the differences between
the Options API and the Composition API.
Module-5 Back-End Integration and Deployment:

My first page

We will now learn how we can create our very first Vue web page, in 5 basic steps:

1.​ Start with a basic HTML file.


2.​ Add a <div> tag with id="app" for Vue to connect with.
3.​ Tell the browser how to handle Vue code by adding a <script> tag with a link to Vue.
4.​ Add a <script> tag with the Vue instance inside.
5.​ Connect the Vue instance to the <div id="app"> tag.

These steps are described in detail below, with the full code in a 'Try It Yourself' example in
the end.

Step 1: HTML page

Start with a simple HTML page:

<!DOCTYPE html>
<html lang="en">
<head>
<title>My first Vue page</title>
</head>
<body>
</body>
</html>

Step 2: Add a <div>

Vue needs an HTML element on your page to connect to.

Put a <div> tag inside the <body> tag and give it an id:

<body>
<div id="app"></div>
</body>

Step 3: Add a link to Vue

To help our browser to interpret our Vue code, add this <script> tag:
Module-5 Back-End Integration and Deployment:

<script src="[Link]

Step 4: Add the Vue instance

Now we need to add our Vue code.

This is called the Vue instance and can contain data and methods and other things, but now it
just contains a message.

On the last line in this <script> tag our Vue instance is connected to the <div id="app"> tag:

<div id="app"></div>

<script src="[Link]

<script>

const app = [Link]({


data() {
return {
message: "Hello World!"
}
}
})

[Link]('#app')

</script>

Step 5: Display 'message' with Text Interpolation

Finally, we can use text interpolation, a Vue syntax with double curly braces {{ }} as a
placeholder for data.

<div id="app"> {{ message }} </div>

The browser will exchange {{ message }} with the text stored in the 'message' property
inside the Vue instance.

Here is our very first Vue page:


Module-5 Back-End Integration and Deployment:

Text Interpolation

Text interpolation is when text is taken from the Vue instance to show on the web page.

The browser receives the page with this code inside:

<div id="app"> {{ message }} </div>

Then the browser finds the text inside the 'message' property of the Vue instance and
translates the Vue code into this:

<div id="app">Hello World!</div>

JavaScript in Text Interpolation

Simple JavaScript expressions can also be written inside the double curly braces {{ }}.

PHP(Hypertext Preprocessor)

PHP is a popular, open-source scripting language mainly used in web development. It runs on
the server side and generates dynamic content that is displayed on a web application. PHP is
easy to embed in HTML, and it allows developers to create interactive web pages and handle
tasks like database management, form handling, and user authentication.
●​ PHP code is executed on the server, generating HTML output sent to the client's
browser.
●​ It is a dynamically typed language, allowing variables to change types during
execution, offering flexibility in coding.
●​ PHP is platform-independent, which means it can run on various operating
systems such as Windows, Linux, and macOS.
●​ PHP supports session management, which allows tracking user activities across
different pages on a website.
Module-5 Back-End Integration and Deployment:

PHP Versions
PHP has been a key technology in web development from the beginning, helping create
interactive websites and web applications. Over the years, PHP has evolved, introducing new
features, performance improvements, and better security. Understanding the different PHP
versions and their changes is essential for developers to keep their code up to date and take
advantage of the latest improvements.
Here we explore the evolution of PHP from PHP 3 to the latest stable PHP 8.4 and offers
practical guidance for choosing and migrating between versions.

Let’s take a look at the different versions of PHP, their release years, and the key features
they introduced:
What is a PHP File?

●​ PHP files can contain text, HTML, CSS, JavaScript, and PHP code
Module-5 Back-End Integration and Deployment:

●​ PHP code is executed on the server, and the result is returned to the browser as plain
HTML
●​ PHP files have extension ".php"

What Can PHP Do?

●​ PHP can generate dynamic page content


●​ PHP can create, open, read, write, delete, and close files on the server
●​ PHP can collect form data
●​ PHP can send and receive cookies
●​ PHP can add, delete, modify data in your database
●​ PHP can be used to control user-access
●​ PHP can encrypt data

With PHP you are not limited to output HTML. You can output images or PDF files. You can
also output any text, such as XHTML and XML.

Why PHP?

●​ PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)


●​ PHP is compatible with almost all servers used today (Apache, IIS, etc.)
●​ PHP supports a wide range of databases
●​ PHP is free. Download it from the official PHP resource: [Link]
●​ PHP is easy to learn and runs efficiently on the server side
●​

PHP Syntax
Basic PHP Syntax
PHP code is executed between PHP tags, allowing the integration of PHP code within
HTML. The most common PHP tag is <?php ... ?>, which is used to enclose PHP code. The
<?php ....?> is called Escaping to PHP.
<?php
// code
?>

The script starts with <?php and ends with ?>. These tags are also called 'Canonical PHP
tags'. Everything outside of a pair of opening and closing tags is ignored by the PHP parser.
The open and closing tags are called delimiters. Every PHP command ends with a semi-colon
(;).
Basic Example of PHP
<?php

Module-5 Back-End Integration and Deployment:

// Here echo command is used to print


echo "Hello, world!";

?>

PHP echo and print Statements

echo and print are more or less the same. They are both used to output data to the screen.

The differences are small: echo has no return value while print has a return value of 1 so it
can be used in expressions. echo can take multiple parameters (although such usage is rare)
while print can take one argument. echo is marginally faster than print.

echo "Hello";
//same as:

echo("Hello");

The print statement can be used with or without parentheses: print or print().
print "Hello";
//same as:

print("Hello");

Embedding PHP in HTML


PHP code can be embedded within HTML using the standard PHP tags. In this example, the
<?php echo "Hello, PHP!"; ?> statement dynamically inserts a heading into the HTML
document.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP Syntax Example</title>
</head>
<body>
<h1><?php echo "Hello, PHP!"; ?></h1>
</body>
</html>
Case Sensitivity
PHP is partially case-sensitive-
●​ Keywords (like if, else, while, echo) are not case-sensitive.
●​ Variable names are case-sensitive.
Module-5 Back-End Integration and Deployment:

Example:
<?php

$Var = "Hello Geeks";

// Outputs: Hello Geeks


echo $Var;

// Error: Undefined variable $variable


echo $var;

?>

For Windows (Using XAMPP – Recommended for Beginners)

○​ Download XAMPP:​
Go to [Link]
Download the installer for Windows.​

○​ Install XAMPP:​
Run the installer and follow the steps.​
During installation, make sure Apache and PHP are selected.​

2.​ Start Apache Server:​

○​ Open the XAMPP Control Panel.


○​ Click Start next to Apache.​

3.​ Test PHP Installation:


○​ Go to C:\xampp\htdocs\​
Create a file named [Link]

with the following code:​



<?php
Module-5 Back-End Integration and Deployment:

phpinfo();
?>

Open your browser and go to:​


[Link]
You should see a PHP information page.

Comments in PHP
Comments are used to make code more readable by explaining the purpose of specific
code blocks. Comments are ignored by the PHP interpreter.

1. Single Line Comment

As the name suggests, these are single line or short relevant explanations that one can
add to their code. To add this, we need to begin the line with (//) or (#).
<?php

// This is a single line comment
// These cannot be extended to more lines

echo "Hello World!";

# This is also a single line comment

?>

2. Multi-Line or Multiple Line Comment

It is used to accommodate multiple lines with a single tag and can be extended to
many lines as required by the user. To add this, we need to begin and end the line with
(/*...*/) ​

<?php

/* This is a multi line comment
In PHP variables are written
by adding a $ sign at the
beginning.*/

Module-5 Back-End Integration and Deployment:

$geek = "Hello World!";


echo $geek;

?>

PHP Variables

A variable in PHP is a container used to store data such as numbers, strings, arrays, or
objects. The value stored in a variable can be changed or updated during the execution of the
script.

●​ All variable names start with a dollar sign ($).


●​ Variables can store different data types, like integers, strings, arrays, etc.
●​ PHP is loosely typed, so you don’t need to declare a data type explicitly.
●​ Variable values can change during the script’s execution.

Declaring Variables in PHP

To declare a variable in PHP, you simply assign a value to it using the $ symbol followed by
the variable name. PHP variables are case-sensitive and must start with a letter or an
underscore, followed by any number of letters, numbers, or underscores.

Syntax:

$variable_name = value;

Now, let us understand with the help of the example:

<?php
$name = "XYZ"; // String
$age = 30; // Integer
$salary = 45000.50; // Float
$isEmployed = true; // Boolean
?>

Variable Naming Conventions

In PHP, it’s important to follow certain naming conventions for PHP variables to ensure
readability and maintainability:
Module-5 Back-End Integration and Deployment:

●​ Start with a Letter or Underscore: Variable names must begin with a letter or an
underscore (_), not a number.
●​ Use Descriptive Names: Variable names should be descriptive of their purpose,
e.g., $userName, $totalAmount.
●​ Case Sensitivity: PHP variable names are case-sensitive, meaning $name and
$Name are different variables.
●​ Avoid Reserved Words: Do not use PHP reserved words or keywords as variable
names (e.g., function, class, echo).

Example of Valid and Invalid Variable Names

<?php

$firstName = "Alice"; // Valid


$_age = 25; // Valid
$2ndPlace = "Bob"; // Invalid: Cannot start with a number
$class = "Physics"; // Valid, but avoid reserved words
?>

PHP Variable Scope

The scope of a variable refers to where it can be accessed within the code. PHP variables can
have local, global, static, or superglobal scope.

1. Local Scope or Local Variable

Variables declared within a function have local scope and cannot be accessed outside the
function. Any declaration of a variable outside the function with the same name (as within the
function) is a completely different variable.

2. Global Scope or Global Variable

The variables declared outside a function are called global variables. These variables can be
accessed directly outside a function. To get access within a function we need to use the
“global” keyword before the variable to refer to the global variable.

Python
Module-5 Back-End Integration and Deployment:

Python was created by Guido van Rossum in 1991 and further developed by the Python
Software [Link] is one of the most popular programming languages. It’s simple
to use, packed with features and supported by a wide range of libraries and frameworks. Its
clean syntax makes it beginner-friendly.
●​ A high-level language, used in web development, data science, automation, AI
and more.
●​ Known for its readability, which means code is easier to write, understand and
maintain.
●​ Backed by library support, so we don’t have to build everything from scratch,
there’s probably a library that already does what we need.

Why Python?

●​ Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
●​ Python has a simple syntax similar to the English language.
●​ Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
●​ Python runs on an interpreter system, meaning that code can be executed as soon as it
is written. This means that prototyping can be very quick.
●​ Python can be treated in a procedural way, an object-oriented way or a functional way.

Key Features of Python


●​ Python’s simple and readable syntax makes it beginner-friendly.
●​ Python runs seamlessly on Windows, macOS and Linux.
●​ Includes libraries for tasks like web development, data analysis and machine
learning.
●​ Variable types are determined automatically at runtime, simplifying code writing.
●​ Supports multiple programming paradigms, including object-oriented, functional
and procedural programming.
●​ Python is free to use, distribute and modify.

Famous Application Built using Python


●​ YouTube: World’s largest video-sharing platform uses Python for features like
video streaming and backend services.
Module-5 Back-End Integration and Deployment:

●​ Instagram: This popular social media app relies on Python’s simplicity for scaling
and handling millions of users.
●​ Spotify: Python is used for backend services and machine learning to personalize
music recommendations.
●​ Dropbox: The file hosting service uses Python for both its desktop client and
server-side operations.
●​ Netflix: Python powers key components of Netflix’s recommendation engine and
content delivery systems (CDN).
●​ Google: Python is one of the key languages used in Google for web crawling,
testing and data analysis.
●​ Uber: Python helps Uber handle dynamic pricing and route optimization using
machine learning.
●​ Pinterest: Python is used to process and store huge amounts of image data
efficiently.

Input and Output in Python

Understanding input and output operations is fundamental to Python programming. With the
print() function, we can display output in various formats, while the input() function enables
interaction with users by gathering input during program execution.

Taking input in Python

Python's input() function is used to take user input. By default, it returns the user input in
form of a string.

Example:

name = input("Enter your name: ")


print("Hello,", name, "! Welcome!")
Printing Output using print() in Python
At its core, printing output in Python is straightforward, thanks to the print() function. This
function allows us to display text, variables and expressions on the console. Let's begin with
the basic usage of the print() function:
Module-5 Back-End Integration and Deployment:

In this example, "Hello, World!" is a string literal enclosed within double quotes. When
executed, this statement will output the text to the console.

print("Hello, World!")
How does this work:

●​ print() is a built-in Python function that tells the computer to show something on
the screen.
●​ The message "Hello, World!" is a string, which means it's just text. In Python,
strings are always written inside quotes (either single ' or double ").
●​ Anything after # in a line is a comment. Python ignores comments when running
the code, but they help people understand what the code is doing.
●​ Comments are helpful for explaining code, making notes or skipping lines while
testing.

We can also write multi-line comments using triple quotes:

"""
This is a multi-line comment.
It can be used to describe larger sections of code.
"""

Python Variables

In Python, variables are used to store data that can be referenced and manipulated during
program execution. A variable is essentially a name that is assigned to a value. Unlike many
other programming languages, Python variables do not require explicit declaration of type.
The type of the variable is inferred based on the value assigned.

Variables act as placeholders for data. They allow us to store and reuse values in our program.

Example:

# Variable 'x' stores the integer value 10


x=5
​# Variable 'name' stores the string "Samantha"
name = "Samantha"

print(x)
print(name)
Module-5 Back-End Integration and Deployment:

Python Operators

In Python programming, operators in general are used to perform operations on values and
variables. These are standard symbols used for logical and arithmetic operations. In this
article, we will look into different types of Python operators.

●​ OPERATORS: These are the special symbols. Eg- + , * , /, etc.


●​ OPERAND: It is the value on which the operator is applied.

Types of Operators in Python

Python Data Types


Python Data types are the classification or categorization of data items. It represents the kind
of value that tells what operations can be performed on a particular data. Since everything is
an object in Python programming, Python data types are classes and variables are instances
(objects) of these classes. The following are the standard or built-in data types in Python:
Module-5 Back-End Integration and Deployment:

x = "Hello World" str

x = 20 int

x = 20.5 float

x = 1j complex

x = ["apple", "banana", "cherry"] list

x = ("apple", "banana", "cherry") tuple

x = range(6) range

x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

What is [Link]?

[Link] is a free, open-source JavaScript runtime that runs on Windows, Mac, Linux, and
more.
Module-5 Back-End Integration and Deployment:

It lets you execute JavaScript code outside of a web browser, enabling server-side
development with JavaScript

Why [Link]?

[Link] excels at handling many simultaneous connections with minimal overhead, making it
perfect for:

●​ Real-time applications (chats, gaming, collaboration tools)


●​ APIs and microservices
●​ Data streaming applications
●​ Command-line tools
●​ Server-side web applications

Its non-blocking, event-driven architecture makes it highly efficient for I/O-heavy workloads.

Asynchronous Programming

[Link] uses asynchronous (non-blocking) programming.

This means it can keep working while waiting for tasks like reading files or talking to a
database.

With asynchronous code, [Link] can handle many things at once—making it fast and
efficient.

What Can [Link] Do?

●​ Web Servers: Create fast, scalable network applications


●​ File Operations: Read, write, and manage files on the server
●​ Database Interaction: Work with databases like MongoDB, MySQL, and more
●​ APIs: Build RESTful services and GraphQL APIs
●​ Real-time: Handle WebSockets for live applications
●​ CLI Tools: Create command-line applications

[Link] Get Started

Download and Install [Link]

1.​ Go to [Link]
2.​ Download the LTS (Long Term Support) version
3.​ Run the installer and follow the instructions

Verify Installation
Module-5 Back-End Integration and Deployment:

Open your terminal/command prompt and type:

node --version
npm --version

You should see version numbers for both [Link] and npm (Node Package Manager).

Troubleshooting

If the commands don't work:

●​ Restart your terminal/command prompt


●​ Make sure [Link] was added to your system's PATH during installation
●​ On Windows, you might need to restart your computer

Getting Started

Once you have installed [Link], let's create your first server that says "Hello World!" in a
web browser.

Create a file called [Link] and add this code:

[Link]

let http = require('http');


[Link](function (req, res) {
[Link](200, {'Content-Type': 'text/html'});
[Link]('Hello World!');
}).listen(8080);

Save the file on your computer, for example: C:\Users\Your Name\[Link]

This code creates a simple web server.

When someone visits your computer on port 8080, it will show "Hello World!".

Explanation:
Module-5 Back-End Integration and Deployment:

Line Description

const http = require('http'); This loads [Link]’s built-in http module,


which allows you to create a web server.

[Link]((req, res) => { ... }) This creates a server that handles incoming
requests (req) and sends responses (res).

[Link](200, {'Content-Type': Sets the HTTP status code to 200 (OK) and
'text/plain'}); the content type to plain text.

[Link]('Hello, this is your first [Link] Ends the response and sends the text back
web server!'); to the browser.

[Link](3000, ...) Starts the server and tells it to listen on


port 3000.

[Link](...) Prints a message in the terminal when the


server is running.

Command Line Interface

[Link] files must be initiated in the "Command Line Interface" program of your computer.

How to open the command line interface on your computer depends on the operating system.

For Windows users, press the start button and look for "Command Prompt", or simply write
"cmd" in the search field.

Navigate to the folder that contains the file "[Link]", the command line interface window
should look something like this:

C:\Users\Your Name>_

Initiate the [Link] File

The file you have just created must be initiated by [Link] before any action can take place.

Start your command line interface, write node [Link] and hit enter:
Module-5 Back-End Integration and Deployment:

Initiate "[Link]":

C:\Users\Your Name>node [Link]

Now, your computer works as a server!

If anyone tries to access your computer on port 8080, they will get a "Hello World!" message
in return!

Start your internet browser, and type in the address: [Link]

Understanding RESTful APIs

REST (Representational State Transfer) is an architectural style for designing networked


applications that has become the standard for web services.

RESTful APIs provide a flexible, lightweight way to integrate applications and enable
communication between different systems.

RESTful APIs use HTTP requests to perform CRUD operations (Create, Read, Update,
Delete) on resources, which are represented as URLs.

REST is stateless, meaning each request from a client to a server must contain all the
information needed to understand and process the request.

HTTP Methods and Their Usage

RESTful APIs use standard HTTP methods to perform operations on resources.

Each method has specific semantics and should be used appropriately.

Idempotency and Safety:

●​ Safe Methods: GET, HEAD, OPTIONS (should not modify resources)


●​ Idempotent Methods: GET, PUT, DELETE (multiple identical requests = same effect
as one)
●​ Non-Idempotent: POST, PATCH (may have different effects with multiple calls)

Always use the most specific method that matches your operation's intent.
Module-5 Back-End Integration and Deployment:

Method Action Example

GET Retrieve resource(s) GET /api/users

POST Create a new resource POST /api/users

PUT Update a resource completely PUT /api/users/123

PATCH Update a resource partially PATCH /api/users/123

DELETE Delete a resource DELETE /api/users/123

RESTful API Structure and Design

A well-designed API follows consistent patterns that make it intuitive and easy to use. Good
API design is crucial for developer experience and long-term maintainability.

Design Considerations:

●​ Resource Naming: Use nouns, not verbs (e.g., /users not /getUsers)
●​ Pluralization: Use plural for collections (/users/123 not /user/123)
●​ Hierarchy: Nest resources to show relationships (/users/123/orders)
●​ Filtering/Sorting: Use query parameters for optional operations
●​ Versioning Strategy: Plan for API versioning from the start (e.g., /v1/users vs
/v2/users).

A well-structured API follows these conventions:

●​ Use nouns for resources: /users, /products, /orders (not /getUsers)


●​ Use plurals for collections: /users instead of /user
●​ Nest resources for relationships: /users/123/orders
●​ Use query parameters for filtering: /products?category=electronics&min_price=100
●​ Keep URLs consistent: Choose a convention (kebab-case, camelCase) and stick to it

Example: Well-structured API Routes


// Good API structure
[Link]('/api/products', getProducts);
[Link]('/api/products/:id', getProductById);
[Link]('/api/products/:id/reviews', getProductReviews);
[Link]('/api/users/:userId/orders', getUserOrders);
[Link]('/api/orders', createOrder);
// Filtering and pagination
[Link]('/api/products?category=electronics&sort=price&limit=10&page=2');
Building REST APIs with [Link] and Express
Module-5 Back-End Integration and Deployment:

[Link] with [Link] provides an excellent foundation for building RESTful APIs.

The following sections outline best practices and patterns for implementation.

Key Components:

●​ Express Router: For organizing routes


●​ Middleware: For cross-cutting concerns
●​ Controllers: For handling request logic
●​ Models: For data access and business logic
●​ Services: For complex business logic

[Link] is the most popular framework for building REST APIs in [Link].

Here's a basic project structure:

// routes/[Link]

const express = require('express');


const router = [Link]();
const { getUsers, getUserById, createUser, updateUser, deleteUser } =
require('../controllers/userController');
[Link]('/', getUsers);
[Link]('/:id', getUserById);
[Link]('/', createUser);
[Link]('/:id', updateUser);
[Link]('/:id', deleteUser);
[Link] = router;

// [Link]

const express = require('express');


const app = express();
const userRoutes = require('./routes/users');

[Link]([Link]());
[Link]('/api/users', userRoutes);

[Link](8080, () => {
[Link]('Server is running on port 8080');
});

Database Integration
Module-5 Back-End Integration and Deployment:

MySQL Database connection from node js application

What is Full Stack?


Full-stack Web Developer

A full-stack web developer is a person who can develop both client and server software.

In addition to mastering HTML and CSS, he/she also knows how to:

●​ Program a browser (e.g. using JavaScript, jQuery, Angular, or Vue)


●​ Program a server (e.g. using PHP, ASP, Python, or Node)
●​ Program a database (e.g. using SQL, SQLite, or MongoDB)

Build a Full-Stack CRUD App Using React, Node, MySQL for Beginners

Advantages

The advantage of being a full-stack web developer is:

●​ You can master all the techniques involved in a development project


●​ You can make a prototype very rapidly
●​ You can provide help to all the team members
●​ You can reduce the cost of the project
●​ You can reduce the time used for team communication
●​ You can switch between front- and back-end development based on requirements
●​ You can better understand all aspects of new and upcoming technologies

Disadvantages

●​ The solution chosen can be wrong for the project


●​ The solution chosen can be dependent on developer skills
●​ The solution can generate a key person risk
●​ Being a full stack developer is increasingly complex

Let's build a simple full-stack web application step by step. We'll use:

●​ Frontend: HTML + CSS + JavaScript (with React)


●​ Backend: [Link] + Express
●​ Database: MongoDB (via Mongoose)​
Module-5 Back-End Integration and Deployment:

📝 App Idea: "Task Tracker"


Basic features:

●​ Add a task

●​ Mark task as complete

●​ Delete task
●​ Store tasks in a MongoDB database​

✅ Step-by-Step Plan (Full Stack)


1. Project Structure

task-tracker/

├── backend/

│ ├── [Link]

│ ├── models/

│ │ └── [Link]

│ └── routes/

│ └── [Link]

├── frontend/

│ ├── public/

│ │ └── [Link]

│ └── src/

│ ├── [Link]

│ ├── [Link]

│ └── components/

│ └── [Link]

└── [Link]
Module-5 Back-End Integration and Deployment:

2. Backend ([Link] + Express + MongoDB)

2.1. Init Backend

mkdir backend && cd backend


npm init -y
npm install express mongoose cors

2.2. MongoDB Model: models/[Link]

const mongoose = require('mongoose');

const TaskSchema = new [Link]({

title: { type: String, required: true },

completed: { type: Boolean, default: false }

});

[Link] = [Link]('Task', TaskSchema);

2.3. Routes: routes/[Link]

const express = require('express');


const router = [Link]();
const Task = require('../models/Task');

// Get all tasks


[Link]('/', async (req, res) => {
const tasks = await [Link]();
[Link](tasks);
});

// Add a new task


[Link]('/', async (req, res) => {
const newTask = new Task({ title: [Link] });
await [Link]();
[Link](201).json(newTask);
});

// Toggle completion
[Link]('/:id', async (req, res) => {
Module-5 Back-End Integration and Deployment:

const task = await [Link]([Link]);


[Link] = ![Link];
await [Link]();
[Link](task);
});

// Delete a task
[Link]('/:id', async (req, res) => {
await [Link]([Link]);
[Link](204).end();
});

[Link] = router;

2.4. Express Server: [Link]

const express = require('express');

const mongoose = require('mongoose');

const cors = require('cors');

const tasksRoute = require('./routes/tasks');

const app = express();

[Link](cors());

[Link]([Link]());

[Link]('/api/tasks', tasksRoute);

[Link]('mongodb://localhost:27017/taskdb')

.then(() => [Link](5000, () => [Link]('Server running on port 5000')))

.catch(err => [Link](err));

3. Frontend (React App)


Module-5 Back-End Integration and Deployment:

3.1. Init Frontend

npx create-react-app frontend

cd frontend

npm install axios

3.2. React Component: src/components/[Link]

import React, { useState, useEffect } from 'react';

import axios from 'axios';

const API_URL = '[Link]

export default function TaskList() {

const [tasks, setTasks] = useState([]);

const [title, setTitle] = useState('');

const fetchTasks = async () => {

const res = await [Link](API_URL);

setTasks([Link]);

};

useEffect(() => {

fetchTasks();

}, []);
Module-5 Back-End Integration and Deployment:

const addTask = async () => {

if ([Link]() === '') return;

await [Link](API_URL, { title });

setTitle('');

fetchTasks();

};

const toggleTask = async (id) => {

await [Link](`${API_URL}/${id}`);

fetchTasks();

};

const deleteTask = async (id) => {

await [Link](`${API_URL}/${id}`);

fetchTasks();

};

return (

<div>

<h2>Task Tracker</h2>

<input

value={title}

onChange={e => setTitle([Link])}

placeholder="New Task"

/>
Module-5 Back-End Integration and Deployment:

<button onClick={addTask}>Add</button>

<ul>

{[Link](task => (

<li key={task._id}>

<span

onClick={() => toggleTask(task._id)}

style={{ textDecoration: [Link] ? 'line-through' : 'none', cursor:


'pointer' }}

>

{[Link]}

</span>

<button onClick={() => deleteTask(task._id)}>X</button>

</li>

))}

</ul>

</div>

);

3.3. App & Index

// [Link]

import TaskList from './components/TaskList';

export default function App() {


Module-5 Back-End Integration and Deployment:

return (

<div className="App">

<TaskList />

</div>

);

// [Link]

import React from 'react';

import ReactDOM from 'react-dom/client';

import App from './App';

[Link]([Link]('root')).render(<App />);

🔧 Run the App


Start Backend

cd backend

node [Link]

Start Frontend

cd frontend

npm start

What is CORS?

CORS stands for Cross-Origin Resource Sharing.​


It's a security mechanism implemented by web browsers to restrict web pages from making
requests to a different domain (origin) than the one that served the web page.
Module-5 Back-End Integration and Deployment:

❖​Case Study: Building a Full-Stack Web Application

Project Overview

Application Name: Task Tracker​


Purpose: To create a web-based task management application that allows users to add,
complete, and delete tasks with data persistence.​
Stack Used:

●​ Frontend: [Link]
●​ Backend: [Link] with [Link]
●​ Database: MongoDB
●​ Tools: Axios, CORS, Mongoose

Objectives

●​ Implement a responsive UI to manage tasks.


●​ Develop RESTful APIs to handle CRUD operations.
●​ Store data persistently using a NoSQL database.
●​ Ensure smooth communication between frontend and backend using HTTP requests.

System Architecture

The architecture follows a client-server model:

●​ Frontend (Client): Sends HTTP requests to the backend.


●​ Backend (Server): Handles requests, performs logic, and interacts with the database.
●​ Database: Stores user-generated task data.

[React Frontend] <--> [Express API Server] <--> [MongoDB Database]

Implementation Details

Frontend (React)

●​ Built with Create React App or Vite.


●​ Uses components like <TaskList /> and <TaskForm />.
●​ Axios handles all HTTP requests to the backend.
●​ Manages state with useState and side-effects with useEffect.

Backend (Express)

●​ Express sets up API endpoints (GET, POST, PATCH, DELETE).


●​ CORS middleware is used to enable communication with the frontend.
●​ Mongoose provides schemas and models for MongoDB interaction.
Module-5 Back-End Integration and Deployment:

Database (MongoDB)

●​ Stores tasks with fields: title (String), completed (Boolean).


●​ Mongoose ensures schema validation.

Key Features

●​ Add a new task


●​ Toggle task completion status
●​ Delete a task
●​ Data persistence

Challenges & Solutions

1. CORS Issues

●​ Problem: Frontend couldn't access backend.


●​ Solution: Added [Link](cors()) in the Express server.

2. MongoDB Connectivity

●​ Problem: Server failed to connect to MongoDB.


●​ Solution: Ensured MongoDB was running locally and connection URI was correct.

3. State Sync

●​ Problem: UI was not updating after operations.


●​ Solution: Called fetchTasks() after each operation to refresh state.

Outcome

●​ Fully functional task tracker web app.


●​ Scalable structure for adding auth or advanced features.
●​ User-friendly interface with real-time feedback.

Future Enhancements

●​ Add user authentication with JWT.


●​ Deploy with Docker and Docker Compose.
●​ Host backend on Render and frontend on Vercel.
●​ Add search, filter, and pagination features.

Conclusion
Module-5 Back-End Integration and Deployment:

This case study demonstrates a complete, modular full-stack application build. It highlights
common issues and best practices for beginners and intermediate developers building web
apps using the MERN (MongoDB, Express, React, [Link]) stack.

[Link] a React app to Google Cloud.


[Link] to deploy React App on AWS S3
[Link] Your React App on GitHub Pages in 5 Minutes!
Deploy NodeJs application GCP Cloud Run with CI/CD (Serverless)
Deploy [Link] Backend on AWS EC2 Instance (Windows)
Deploy node js application with Heroku

Cloud Platform Deployment

Cloud platforms provide ready-to-use infrastructure and services for deploying [Link]
applications with minimal configuration. These platforms abstract away much of the
complexity of infrastructure management.

Popular Cloud Platforms for [Link]


Module-5 Back-End Integration and Deployment:

Platform Features Best For

Heroku Simple deployment via Git, Quick prototyping,


auto-scaling, add-ons startups, simple
marketplace deployments

AWS Elastic Auto-scaling, load balancing, AWS ecosystem


Beanstalk health monitoring integration, enterprise
applications

Google App Engine Auto-scaling, traffic Google Cloud ecosystem,


splitting, versioning high-traffic applications

Azure App Service Built-in CI/CD, staging Microsoft ecosystem,


environments, easy scaling enterprise applications

1. Heroku
🔹 Overview:
Heroku is a cloud platform that allows developers to deploy, manage, and scale applications
quickly. It supports multiple programming languages and offers an easy deployment method
using Git.

🔹 Key Features:
●​ Simple deployment via Git​

●​ Auto-scaling​

●​ Marketplace for add-ons like databases, caching, logging, etc.​

🔹 Best Use:
Module-5 Back-End Integration and Deployment:

●​ Quick prototyping​

●​ Startups and small to medium web applications​

🔹 Step-by-Step Deployment:
✅ Prerequisites:
●​ Install Heroku CLI​

●​ Install Git​

●​ [Link] app with [Link]​

✅ Steps:
Login to Heroku CLI:​

heroku login

1.​ Create a [Link] App:​



mkdir myapp

cd myapp

npm init -y

npm install express

Create [Link]:​

const express = require('express');

const app = express();

const PORT = [Link] || 3000;

[Link]('/', (req, res) => {

[Link]('Hello from Heroku!');


Module-5 Back-End Integration and Deployment:

});

[Link](PORT, () => {

[Link](`Server is running on port ${PORT}`);

});

2.​ Create Procfile:​


(No extension. This tells Heroku how to run your app)​

web: node [Link]

3.​ Deploy using Git:​




git init

git add .

git commit -m "Initial commit"

heroku create

git push heroku master

heroku open

☁️ 2. AWS Elastic Beanstalk


🔹 Overview:
AWS Elastic Beanstalk is a Platform-as-a-Service (PaaS) from Amazon that automates the
deployment of applications on cloud infrastructure like EC2, S3, and Load Balancers.

🔹 Key Features:
●​ Auto-scaling and load balancing​
Module-5 Back-End Integration and Deployment:

●​ Health monitoring​

●​ Easy integration with AWS services (RDS, S3, etc.)​

🔹 Best Use:
●​ Scalable, production-grade enterprise applications​

🔹 Step-by-Step Deployment:
✅ Prerequisites:
●​ AWS account​

●​ Install AWS CLI​

●​ Install EB CLI​

●​ [Link] app​

✅ Steps:
[Link] your project:​

eb init

○​ Choose region​

○​ Select platform ([Link])​

○​ Create SSH key if prompted

[Link] environment and deploy:​



​ eb create my-node-env

3. Open your app in browser:​



​ eb open

4. Check environment health:​



​ eb health
Module-5 Back-End Integration and Deployment:

☁️ 3. Google App Engine


🔹 Overview:
Google App Engine (GAE) is a serverless platform that allows you to deploy and scale
applications automatically on Google Cloud infrastructure.

🔹 Key Features:
●​ Auto-scaling​

●​ Traffic splitting and version control​

●​ Google Cloud integration (Cloud Storage, Firestore, etc.)​

🔹 Best Use:
●​ High-traffic apps​

●​ Apps needing Google Cloud services integration​

🔹 Step-by-Step Deployment:
✅ Prerequisites:
●​ Install Google Cloud SDK​

●​ Google Cloud project with billing enabled​

✅ Steps:
1.​ Login and initialize SDK:​

gcloud auth login

gcloud init
Module-5 Back-End Integration and Deployment:

2. Create [Link]:​
This configures App Engine for your [Link] app.​
runtime: nodejs18
instance_class: F1
Handlers:

- url: /.*

script: auto

1.​ Deploy the app:​



gcloud app deploy
2.​ Open the app in browser:​

gcloud app browse

Security best practices for web applications:-


Why Security is Important

[Link] applications are vulnerable to a wide range of attacks if not secured properly.
Hackers can:

●​ Steal data (e.g., usernames, passwords)​

●​ Corrupt or delete databases​

●​ Gain unauthorized server access​

Securing your application is not optional, it’s mandatory to protect your users and your
server.

●​ Common Security Vulnerabilities in [Link]

Vulnerability Description Impact

Injection Attacks Inserting malicious code into Data theft,


inputs processed by the application unauthorized access,
(SQL, NoSQL, OS commands) service disruption
Module-5 Back-End Integration and Deployment:

Cross-Site Scripting Injecting client-side scripts into Session hijacking,


(XSS) web pages viewed by other users credential theft,
defacement

Broken Flaws in authentication Account takeover,


Authentication mechanisms that allow credential privilege escalation
compromise

Insecure Using third-party packages with Inheriting all


Dependencies known vulnerabilities vulnerabilities from
dependencies

Information Leaking sensitive data through System information


Exposure error messages, logs, or responses disclosure, data leakage

Cross-Site Request Tricking users into making Performing


Forgery (CSRF) unwanted actions on a web app unauthorized
they're authenticated to. operations on behalf of
users

Security Improper configuration of security Various security gaps


Misconfiguration settings in [Link] apps and vulnerabilities

Path Traversal Accessing files and directories Unauthorized file


outside of intended application access, code execution
paths

Essential Security Best Practices

1. Avoid Exposing Sensitive Information

Problem:

If the application crashes, error messages may reveal sensitive information like:
Module-5 Back-End Integration and Deployment:

●​ File paths​

●​ Database structure​

●​ Server configuration​

Best Practice:

●​ Disable detailed error reporting in production​

●​ Use:​

[Link](function (err, req, res, next) {


[Link](500).send("Something went wrong!");
});

🔸 2. Validate User Input


Problem:

Unsanitized input can lead to SQL Injection, XSS, etc.

Best Practice:

●​ Validate input on both client and server side​

●​ Never trust user input​

●​ Use packages like:​

○​ express-validator​

○​ [Link]​

const { check } = require('express-validator');


[Link]('/submit', [
check('email').isEmail(),
check('password').isLength({ min: 6 })
], (req, res) => {
Module-5 Back-End Integration and Deployment:

// Your logic here


});

🔸 3. Use HTTPS
Problem:

Data sent over HTTP can be intercepted.

Best Practice:

●​ Use HTTPS (SSL encryption) to protect data in transit.​

●​ Get an SSL certificate and configure it with your server.​

Example using HTTPS module:

const https = require('https');


const fs = require('fs');

const options = {
key: [Link]('[Link]'),
cert: [Link]('[Link]')
};

[Link](options, app).listen(443);

🔸 4. Protect Against Injection Attacks


Problem:

Attackers inject malicious code into your app (e.g., SQL queries).

Best Practice:

●​ Use parameterized queries for SQL (with packages like mysql2, pg)​

●​ Sanitize and escape inputs​


Module-5 Back-End Integration and Deployment:

●​ Use Object Data Modeling tools like Mongoose for MongoDB

Example:

// Using mysql2 prepared statements


[Link]('SELECT * FROM users WHERE email = ?', [email]);

🔸 5. Use Helmet for Security Headers


Problem:

Web apps are vulnerable to attacks like XSS, clickjacking, etc.

Best Practice:

●​ Use the helmet middleware to set secure HTTP headers​

npm install helmet

const helmet = require('helmet');


[Link](helmet());

Helmet helps protect your app by setting headers like:

●​ X-Content-Type-Options​

●​ Content-Security-Policy​

●​ X-Frame-Options​

🔸 6. Authentication and Password Security


Problem:

Weak password handling can expose user accounts.

Best Practice:
Module-5 Back-End Integration and Deployment:

●​ Use bcrypt to hash passwords​

●​ Never store plain-text passwords​

npm install bcrypt

const bcrypt = require('bcrypt');


const hash = await [Link]("userpassword", 10);

●​ Always compare using:

●​ await [Link]("inputPassword", hash);

🔸 7. Limit Login Attempts


Problem:

Attackers can try many combinations (brute force) to guess passwords.

Best Practice:

●​ Use packages like express-rate-limit​

npm install express-rate-limit

const rateLimit = require('express-rate-limit');

const limiter = rateLimit({


windowMs: 15 * 60 * 1000, // 15 minutes
max: 100
});

[Link](limiter);

🔸 8. Keep Software Updated


Problem:
Module-5 Back-End Integration and Deployment:

Outdated packages may contain known vulnerabilities.

Best Practice:

●​ Regularly update [Link] and npm packages​

●​ Use:​

npm outdated
npm update

●​ Run security audits:​


npm audit

🔸 9. Use Environment Variables


Problem:

Hardcoding secrets (like API keys or DB credentials) in source code is risky.

Best Practice:

●​ Store credentials in .env file​

●​ Use dotenv package​

npm install dotenv

require('dotenv').config();
const dbPassword = [Link].DB_PASSWORD;

.env:

DB_PASSWORD=your_secret_password

🔸 10. Database Security


Best Practice:
Module-5 Back-End Integration and Deployment:

●​ Use strong credentials​

●​ Restrict IPs that can connect to the DB​

●​ Disable remote root access​

●​ Limit database user permissions to only what’s needed​

Authentication and Authorization

🔸 1. What is Authentication?
➤ Definition:

Authentication is the process of verifying the identity of a user or system.

➤ Goal:

To ensure that the user is who they claim to be.

✅ Examples of Authentication:
●​ Logging into a website with a username and password.​

●​ Using a fingerprint or face ID on a phone.​

●​ Logging in with Google/Facebook (OAuth).​

🔧 Common Authentication Methods:


Module-5 Back-End Integration and Deployment:

Method Description

Password-based User logs in with username and password

Token-based (JWT) User receives a token after login to access secure


resources

OAuth2.0 Authentication via third-party providers like Google or


GitHub

Multi-Factor Authentication Adds an extra layer, like OTP or biometric


(MFA)

🔐 [Link] Authentication with JWT (JSON Web Token)


1. Install Required Packages:

npm install express jsonwebtoken bcryptjs

2. Register a User with Hashed Password:


const bcrypt = require('bcryptjs');
const hashedPassword = await [Link]([Link], 10);

3. Login and Generate Token:

const jwt = require('jsonwebtoken');

[Link]('/login', async (req, res) => {


const user = await findUser([Link]);
const valid = await [Link]([Link], [Link]);

if (!valid) return [Link](401).send("Invalid credentials");

const token = [Link]({ id: [Link], role: [Link] }, 'secretKey', { expiresIn: '1h' });
[Link]({ token });
});

4. Verify Token Middleware:

function authenticateToken(req, res, next) {


const token = [Link]['authorization']?.split(' ')[1];
Module-5 Back-End Integration and Deployment:

if (!token) return [Link](401);

[Link](token, 'secretKey', (err, user) => {


if (err) return [Link](403);
[Link] = user;
next();
});
}

🔸 2. What is Authorization?
➤ Definition:

Authorization is the process of granting or denying access to resources based on the


user’s identity and permissions.

➤ Goal:

To control what a user is allowed to do once authenticated.

✅ Examples of Authorization:
●​ An admin can create or delete users, but a regular user cannot.​

●​ A user can view their own data, but not another user’s data.​

🔧 Common Authorization Types:


Type Description

Role-Based Access Control (RBAC) Access based on user roles (admin, editor,
viewer)

Attribute-Based Access Control Access based on user attributes (e.g., age,


(ABAC) location)

Access Control Lists (ACL) Permissions assigned to specific resources


Module-5 Back-End Integration and Deployment:

🔐 [Link] Authorization Example (Role-Based)


1. Authorization Middleware:

function authorizeRoles(...roles) {
return (req, res, next) => {
if (![Link]([Link])) {
return [Link](403).send('Access denied');
}
next();
};
}

2. Use in Routes:

[Link]('/admin', authenticateToken, authorizeRoles('admin'), (req, res) => {


[Link]("Welcome Admin");
});

🔁 Difference: Authentication vs Authorization


Feature Authentication Authorization

Definition Verifies who the user is Verifies what the user can access

Happens Before authorization After successful authentication

Example Login with credentials Admin-only page access

Data Used Username/password, User roles, permissions

Outcome Identity confirmed Access granted or denied

Performance Optimization for Web Applications

🔍 What is Performance Optimization?


Performance optimization refers to the practice of enhancing a web application’s speed,
responsiveness, and resource efficiency, ensuring it performs well under various loads and
conditions.
Module-5 Back-End Integration and Deployment:

✅ Goals of Performance Optimization:


●​ Reduce response time (faster page loading)​

●​ Improve scalability (handle more users)​

●​ Lower CPU and memory usage​

●​ Ensure smooth user experience​

🔧 Common Performance Optimization Techniques in [Link] and Web Apps


1. 🧠 Use Caching

Avoids re-computing or re-fetching frequently used data.

How:

●​ Memory caching using node-cache, memory-cache​

●​ External caching using Redis or Memcached​

const NodeCache = require("node-cache");


const myCache = new NodeCache();
[Link]("userId:101", userObject, 600); // Cache for 10 min

2. 🌐 Use Content Delivery Network (CDN)


Delivers static files (images, CSS, JS) from the closest server to the user.

Benefits:

●​ Reduces server load​

●​ Speeds up static asset delivery​

Popular Cloudflare, AWS CloudFront


Module-5 Back-End Integration and Deployment:

3. 📦 Minimize and Compress Files


Smaller file sizes = faster load time

How:

●​ Minify CSS, JS using tools like uglify-js, cssnano​

●​ Use Gzip or Brotli compression on server​

const compression = require('compression');

[Link](compression()); // Enable gzip compression

4. 🧵 Asynchronous and Non-blocking Code


[Link] is single-threaded; blocking calls slow everything down.

Do:

●​ Use async/await or Promises​

●​ Avoid synchronous file operations like [Link]()

// BAD (Blocking)
const data = [Link]('[Link]');

// GOOD (Non-blocking)
[Link]('[Link]', (err, data) => {
if (err) throw err;
[Link]([Link]());
});

5. Use Efficient Database Queries

Poorly written queries cause slow responses.

Tips:

●​ Use indexes​
Module-5 Back-End Integration and Deployment:

●​ Limit the number of records fetched​

●​ Use pagination​

-- BAD

SELECT * FROM orders;

-- GOOD
SELECT * FROM orders LIMIT 20 OFFSET 0;

6. Use Load Balancing

Distributes incoming traffic across multiple servers.

Tools:

●​ Nginx, HAProxy for HTTP load balancing​

●​ Cloud load balancers like AWS ELB, Google Cloud Load Balancing​

7. Clean and Optimize Code

Well-structured, clean code performs better and is easier to maintain.

Best Practices:

●​ Avoid nested loops and heavy computations on the main thread​

●​ Use proper data structures (e.g., Map instead of Object for lookups)​

●​ Refactor and modularize code​

8. Monitor and Profile Your App

Why: Identifies bottlenecks and memory leaks.

Tools:
Module-5 Back-End Integration and Deployment:

●​ [Link] for performance profiling​

●​ newrelic, appmetrics, PM2 monitoring dashboard​

●​ Google Chrome’s Lighthouse for frontend performance​

9. Use HTTP/2

Faster than HTTP/1.1 by supporting multiplexing, header compression, etc.

How:​
Enable it on your web server (Nginx/Apache) or use a cloud provider that supports HTTP/2.

10. Implement Lazy Loading

Improves initial load time by loading content on demand.

How:​
Used mostly in frontend frameworks (React, Angular) and with images.

<img loading="lazy" src="[Link]" />

You might also like