0% found this document useful (0 votes)
5 views16 pages

Content Beyond The Syllabus WDF

The document provides an overview of web development frameworks, focusing on JAMstack architecture, Node.js debugging techniques, MongoDB aggregation framework, JWT authentication in Express, and React hooks. It explains the core components and benefits of JAMstack, debugging methods in Node.js, and how to implement JWT for secure authentication in Express applications. Additionally, it covers the use of React hooks for managing state and lifecycle features in functional components.

Uploaded by

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

Content Beyond The Syllabus WDF

The document provides an overview of web development frameworks, focusing on JAMstack architecture, Node.js debugging techniques, MongoDB aggregation framework, JWT authentication in Express, and React hooks. It explains the core components and benefits of JAMstack, debugging methods in Node.js, and how to implement JWT for secure authentication in Express applications. Additionally, it covers the use of React hooks for managing state and lifecycle features in functional components.

Uploaded by

karpagamrathan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 16

ERODE SENGUNTHAR

ENGINEERING COLLEGE
(An Autonomous Institution)
Approved by AICTE, New Delhi, Permanently Affiliated to Anna University- Chennai,
Accredited by National Board of Accreditation (NBA), New Delhi &
National Assessment and Accreditation Council (NAAC), Bangalore with ‘A’ Grade
PERUNDURAI -638 057, TAMILNADU, INDIA.

DEPARTMENT OF M.TECH COMPUTER SCIENCE AND ENGINEERING


(5 YEARS INTEGRATED COURSE)
21CS902 WEB DEVELOPMENT FRAMEWORK

CONTENT BEYOND THE SYLLABUS


Unit I – Basic Web Development Framework

JAMstack Architecture
1. Introduction to JAMstack
JAMstack stands for JavaScript, APIs, and Markup. It is a modern web development
architecture that focuses on performance, scalability, security, and better developer experience.
Unlike traditional monolithic architectures, JAMstack decouples the frontend from the backend,
allowing content and services to be served directly from a Content Delivery Network (CDN).
JAMstack is not a specific technology or framework but a development philosophy that
leverages static site generation and headless CMSs to deliver fast, secure, and dynamic web
applications.
2. Core Components of JAMstack

A. JavaScript
JavaScript is used to handle dynamic functionalities on the client-side.
It runs entirely in the browser and fetches data via APIs.
Frameworks like React, Vue, Angular, or even plain JavaScript can be used.
B. APIs
All server-side operations or database actions are abstracted into reusable APIs.
These can be third-party services (e.g., Stripe, Auth0) or custom-built using serverless functions.
Examples: REST, GraphQL, or third-party cloud services.
C. Markup
Prebuilt HTML pages are generated at build time using Static Site Generators (SSGs).
Tools like Next.js, Gatsby, Hugo, Jekyll are popular.
These markup files are served from a CDN for high-speed delivery.
3. JAMstack Workflow
Developer writes content or code using a static site generator and version control (e.g., Git).
Content is pulled from a Headless CMS (like Contentful, Sanity, Strapi) via APIs.
Build tools generate static HTML based on the templates and content.
Files are deployed to a CDN, such as Netlify or Vercel.
Client-side JavaScript handles interactivity, authentication, and communication with APIs.
4. Benefits of JAMstack

A. Performance
Since content is served statically from a CDN, load times are significantly reduced.
No need to wait for server-side rendering on each request.
B. Security
No server or database to be compromised, reducing the attack surface.
APIs are isolated and secure.
C. Scalability
Easy to scale as static files can be cached globally across multiple CDN nodes.
High traffic won’t overwhelm backend servers.
D. Developer Experience
Use of Git, SSGs, and modern build tools offers a streamlined workflow.
Faster development and deployment cycles.
E. Cost Efficiency
Hosting static files is much cheaper than maintaining server infrastructure.
Serverless computing allows pay-as-you-go pricing for backend logic.
5. Comparison with Traditional Architecture
Feature JAMstack Traditional Web Stack (LAMP, MEAN, etc.)

Architecture Decoupled (Frontend & Backend) Monolithic or Tightly Coupled

Rendering Pre-rendered (Static) Server-side Dynamic

Speed Very Fast (CDN) Slower due to server processing

Scalability High (CDN-based) Needs additional infrastructure


Feature JAMstack Traditional Web Stack (LAMP, MEAN, etc.)

Security More secure (no direct DB) Prone to attacks (SQLi, XSS)

Hosting CDN-based, cheap Requires full stack hosting

Development Git-centric, modern tools Traditional IDEs, manual deployment

6. Use Cases of JAMstack


Static websites (blogs, documentation)
E-commerce (via APIs like Shopify, Snipcart)
Portfolio sites
SaaS applications
Headless CMS-based sites
7. Popular Tools in JAMstack Ecosystem

Static Site Generators (SSGs):


Next.js (React-based, hybrid static and server-side rendering)
Gatsby (React-based, data-layer driven)
Hugo (Go-based, very fast)
Jekyll (Ruby-based, GitHub Pages friendly)
Headless CMS: Contentful Strapi Sanity Ghost Netlify CMS

Deployment Platforms: Netlify Vercel Cloudflare Pages GitHub Pages

Serverless Platforms: AWS Lambda Netlify Functions Azure Functions Google Cloud
Functions

8. Limitations of JAMstack
Build Time Complexity: Large sites may take time to rebuild fully.
Dynamic Content Handling: Requires more setup for real-time updates.
Complexity for Beginners: Understanding decoupled systems and API-based workflows can be
challenging.
9. JAMstack in Action – Example
Let’s say you want to create a blog.
You use Gatsby to generate the site.
Content is stored in Contentful.
Images are optimized using Cloudinary APIs.
You deploy your site on Netlify.
Site is delivered via CDN, ensuring blazing fast speed.
All interactions like comments, user logins, or payments are handled using third-party APIs or
serverless functions.
10. Future of JAMstack
JAMstack is rapidly evolving with frameworks like Next.js supporting Incremental Static
Regeneration (ISR).
More CMSs are becoming "headless", encouraging the JAMstack adoption.
Integration with AI, personalization, and analytics APIs is becoming common. Suited for the
"composable web", where websites are built from modular components and services.

Unit II Node JS
Node.js Debugging Techniques
1. Introduction to Debugging in Node.js
Debugging is the process of identifying and fixing bugs in your code. In Node.js, debugging is
critical due to asynchronous behavior, callbacks, and the event-driven architecture. Node.js
provides both built-in and external tools to simplify the debugging process.
Basic Debugging Techniques
A. Using console.log()
The simplest and most common method for debugging.Helps track values, flow of execution,
and identify where things go wrong.
console.log("Value of x:", x);

Pros:
Easy to implement.
No setup needed.
Cons:
Messy for large apps.
Not ideal for asynchronous code.
B. Using Node.js Built-in Debugger
Start Node with the inspect flag:
node inspect app.js

Common commands:
cont / c: Continue execution
next / n: Step to the next line
step / s: Step into a function
out / o: Step out of the current function
pause: Pause the execution
repl: Open an interactive REPL at the current break point
watch('variable'): Watch a variable’s value
Example:
node inspect index.js

debug> n

C. Breakpoints in Code
You can insert breakpoints manually:
debugger;

This pauses execution at that line when running with:


node inspect script.js

D. Using Chrome DevTools


Node supports Chrome DevTools for debugging:
Run:
node --inspect-brk index.js

Open Chrome and go to:


chrome://inspect

Click on "Open dedicated DevTools for Node"


Features:
Step-through debugging
Variable watching
Call stack
Breakpoints
Console with live REPL
Advanced Debugging Tools
E. VS Code Debugger
Visual Studio Code offers built-in debugging for Node.js.
Create .vscode/launch.json:
json

"version": "0.2.0",

"configurations": [

"type": "node",

"request": "launch",

"name": "Debug App",

"program": "${workspaceFolder}/app.js"

]}

Set breakpoints in the editor.


Press F5 to start debugging.
Features:
Interactive variable inspection
Breakpoints
Watch expressions
Call stack navigation
F. Using the debug Module
Install:
npm install debug

Usage:
js

const debug = require('debug')('app');debug('This is a debug message');


Enable it via environment variable:
DEBUG=app node app.js

Benefits:
Toggle logs without changing code.
Scopes logs for better tracking.
G. Logging with Winston or Bunyan
For better logging with levels, timestamps, etc., use a logging library like:
Winston:
npm install winston

js

CopyEdit

const winston = require('winston');const logger = winston.createLogger({

transports: [new winston.transports.Console()]

});

logger.info("App started");

Bunyan:
npm install bunyan

js

const bunyan = require('bunyan');const log = bunyan.createLogger({name: "myapp"});

log.info("App running");

H. Using Node.js Profiler


To profile performance issues:
node --inspect app.js

Then open Chrome DevTools → Profiler Tab → Capture and analyze performance.
Also, clinic.js tool (by nearForm) can be used:
npm install -g clinic

clinic doctor -- node app.js


Unit III Mongo DB
MongoDB Aggregation Framework
What is Aggregation?
Aggregation in MongoDB is a data processing method used to transform and compute results
from multiple documents in a collection. It is equivalent to SQL’s GROUP BY, JOIN, and
aggregate functions.
Aggregation operations process data records and return computed results.
Aggregation Concepts
Aggregation Pipeline: A sequence of stages where each stage transforms the documents.
Each stage passes its output as input to the next stage.
Common Aggregation Stages
Stage Description

$match Filters documents (like SQL WHERE)

$group Groups by a field and performs accumulations

$project Selects/reshapes fields

$sort Sorts documents

$limit Limits the number of output documents

$skip Skips a number of documents

$unwind Deconstructs arrays into separate documents

$lookup Joins with another collection (like SQL JOIN)

$addFields Adds or updates fields


Common Accumulator Operators (used with $group)
Operator Description

$sum Sums values

$avg Calculates average

$min Minimum value

$max Maximum value

$push Adds value to an array

$first First document in group

$last Last document in group

Example Aggregation Query


js

db.orders.aggregate([

{ $match: { status: "delivered" } },

{ $group: { _id: "$customerId", total: { $sum: "$amount" } } },

{ $sort: { total: -1 } }

])

Explanation:
Filters orders with status = delivered
Groups by customerId, sums their amount
Sorts customers by total spent
Use Cases
Reporting & Analytics
Data transformation
Grouping and summarizing
Joining collections
Restructuring documents
Unit IV Express And Angular
JWT Authentication in Express:
Understanding JWT and Setup in Express
JWT:
JWT (JSON Web Token) is a secure, compact, and self-contained way to transmit information
between parties. It is widely used for authentication and authorization in web applications.
Format: header.payload.signature
JWT Structure
Part Description

Header Contains the signing algorithm (e.g., HS256)

Payload Contains user data (e.g., id, role)

Signature Verifies data hasn’t been tampered with

Installing Required Packages

npm install express jsonwebtoken bcryptjs dotenv

jsonwebtoken: To sign and verify tokens


bcryptjs: To hash passwords
dotenv: To store secrets securely
Basic JWT Authentication Workflow
User logs in with credentials.
Server verifies credentials and signs a token with jwt.sign().
Token is returned to the client and stored (usually in localStorage or cookies).
Client sends token in Authorization header for protected routes.
Server verifies token using jwt.verify().
Sample Express Login & Token Generation
js

const jwt = require('jsonwebtoken');

app.post('/login', (req, res) => {

const user = { id: 1, username: 'john' };


const token = jwt.sign(user, process.env.JWT_SECRET, { expiresIn: '1h' });

res.json({ token });

});

Protecting Routes and Verifying JWT


Creating Middleware to Verify Token
js

function authenticateToken(req, res, next) {

const authHeader = req.headers['authorization'];

const token = authHeader && authHeader.split(' ')[1]; // Bearer <token>

if (!token) return res.sendStatus(401);

jwt.verify(token, process.env.JWT_SECRET, (err, user) => {

if (err) return res.sendStatus(403);

req.user = user;

next();

});

Using Middleware to Protect Routes


jsapp.get('/dashboard', authenticateToken, (req, res) => {

res.send(`Welcome ${req.user.username}`);

});

Secure Practices
Tip Description

Use HTTPS Prevent token sniffing

Store JWTs securely Prefer HttpOnly cookies

Set token expiration Use expiresIn in jwt.sign()


Tip Description

Use strong secrets Store in .env and avoid hardcoding

Handle errors Check for 401 (unauthorized) and 403 (forbidden)

Token Expiration & Refresh Tokens


Tokens usually expire in 15 min – 1 hr.
Use a refresh token to re-authenticate users without login.
Environment File Example
JWT_SECRET=your_super_secret_key

Common JWT Functions


js

// Sign a token

jwt.sign(payload, secret, { expiresIn: '1h' })

// Verify a token

jwt.verify(token, secret, callback)

Error Handling Example


Js

app.use((err, req, res, next) => {

if (err.name === 'UnauthorizedError') {

res.status(401).json({ message: 'Invalid token' });

});

Unit V REACT
React Hooks in Depth
Introduction to React Hooks
React Hooks are functions introduced in React 16.8 that let you “hook into” React state and
lifecycle features from function components.
Hooks do not work inside classes — they let you use React features without classes.
Avoid complex class components.
Reuse stateful logic without HOCs or render props.
Separate concerns in components.
Better code readability and testing.
Basic Hooks
1. useState()
Used to add state to function components.
jsx

const [count, setCount] = useState(0);

useState returns an array: current state and a setter function.


Can hold strings, numbers, arrays, objects.
2. useEffect()
Used to handle side effects (data fetching, subscriptions, timers).
jsx

useEffect(() => {

// Runs after every render

console.log("Component rendered");

return () => {

// Cleanup

console.log("Cleanup function");

};

}, [dependencies]);

If dependency array is empty [], runs only once (componentDidMount).


If dependencies change, it reruns (componentDidUpdate).
Cleanup mimics componentWillUnmount.
3. useContext()
Used to consume values from a React Context.
jsx

const value = useContext(MyContext);

Prevents prop drilling.


Works with createContext.
Additional Hooks
4. useRef()
Used to access DOM nodes or keep mutable values.
jsx

const inputRef = useRef(null);

useEffect(() => {

inputRef.current.focus();

});

Values persist across renders but do not cause re-renders.


5. useMemo()
Used to memoize expensive computations.
jsx

const result = useMemo(() => expensiveFunction(a, b), [a, b]);

Avoids recalculating unless dependencies change.


6. useCallback()
Used to memoize callbacks (functions).
jsx

const memoizedCallback = useCallback(() => {

doSomething(a, b);

}, [a, b]);

Prevents unnecessary re-renders of child components.


7. useReducer()
Alternative to useState for complex state logic (like Redux pattern).
jsx
const [state, dispatch] = useReducer(reducer, initialState);

Accepts a reducer function and an initial state.


8. useLayoutEffect()
Like useEffect, but fires synchronously after all DOM mutations.
jsx

useLayoutEffect(() => {

// Runs before the browser paints

}, []);

Can be used for measuring layout, animations, etc.


9. useImperativeHandle()
Used with forwardRef to expose certain methods from child to parent.
jsx

useImperativeHandle(ref, () => ({

customMethod() {

console.log("Called from parent");

}));

10. useDebugValue()
Used to display custom debug info in React DevTools.
jsx

useDebugValue(value);

Custom Hooks

A custom hook is a JavaScript function that uses one or more React hooks.
jsx

function useCounter(initialValue) {

const [count, setCount] = useState(initialValue);


const increment = () => setCount(c => c + 1);

return [count, increment];

Naming convention: always starts with use.


Can reuse logic across multiple components.
Rules of Hooks
Only call hooks at the top level
No loops, conditions, or nested functions.
Only call hooks from React functions
Functional components or custom hooks.
Use the eslint-plugin-react-hooks to enforce rules.
Comparison to Class Lifecycle Methods
Class Component Hook Equivalent

constructor useState, useReducer

componentDidMount useEffect(..., [])

componentDidUpdate useEffect(..., [deps])

componentWillUnmount Cleanup in useEffect

shouldComponentUpdate React.memo, useMemo

You might also like