0% found this document useful (0 votes)
9 views31 pages

FE-302 PPT Notes

The document outlines a series of sessions focused on Tailwind CSS and related web development topics, including client-side and server-side rendering, routing, navigation, data fetching, authentication, and performance optimization. Each session includes an agenda, challenges with traditional CSS, and practical examples of using Tailwind CSS for responsive design, utility classes, and layout techniques. The sessions also cover installation and configuration of Tailwind CSS, along with best practices for enhancing web security and testing.

Uploaded by

Anusree
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)
9 views31 pages

FE-302 PPT Notes

The document outlines a series of sessions focused on Tailwind CSS and related web development topics, including client-side and server-side rendering, routing, navigation, data fetching, authentication, and performance optimization. Each session includes an agenda, challenges with traditional CSS, and practical examples of using Tailwind CSS for responsive design, utility classes, and layout techniques. The sessions also cover installation and configuration of Tailwind CSS, along with best practices for enhancing web security and testing.

Uploaded by

Anusree
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
You are on page 1/ 31

FE-302 PPT Notes

2 Sep 2024 - Session 1...........................................................................................................2


Tailwind CSS...................................................................................................................... 2
● Agenda...................................................................................................................... 2
● Challenges with Traditional CSS...............................................................................3
● Introduction to Tailwind CSS..................................................................................... 3
● Utility Classes............................................................................................................3
● Responsive Design with Tailwind CSS......................................................................6
● Adding Hover Effects with Tailwind CSS................................................................... 7
● Flexbox, Grid, and Responsive Layouts with Tailwind CSS...................................... 7
● Installing and Configuring Tailwind CSS................................................................... 8
4 Sep 2024 - Session 2...........................................................................................................9
Introduction to Client-Side Rendering and Server Side Rendering.................................... 9
● Agenda...................................................................................................................... 9
● Introduction to Rendering Methods........................................................................... 9
● Comparison: CSR vs. SSR..................................................................................... 10
● Demo.......................................................................................................................10
● Next.js Project Setup...............................................................................................10
● Client and Server Components in Next.js............................................................... 10
● Summary................................................................................................................. 10
6 Sep 2024 - Session 3.........................................................................................................11
Routing............................................................................................................................. 11
● Agenda.................................................................................................................... 11
● Introduction to Routing............................................................................................ 11
● Routing in Next.js.................................................................................................... 11
● Implementation Steps..............................................................................................11
● Summary................................................................................................................. 11
● Takeaway................................................................................................................ 12
9 Sep 2024 - Session 4.........................................................................................................12
Navigation........................................................................................................................ 12
● Agenda.................................................................................................................... 12
● Traditional vs. Next Navigation................................................................................12
● URL Objects............................................................................................................ 13
● Retrieving Route and Query Parameters................................................................ 13
● Navigating Programmatically with useRouter Hook................................................ 14
● Activities.................................................................................................................. 14
● Conclusion.............................................................................................................. 14
12 Sep 2024 - Session 5.......................................................................................................14
Data Fetching................................................................................................................... 14
● Agenda Overview.................................................................................................... 14
● Detailed Breakdown................................................................................................ 15
○ 1. Data Fetching (Client Side vs Server Side)...................................................15
○ 2. Static Site Generation (SSG) using generateStaticParams.......................... 15
○ 3. Data Caching.................................................................................................15
○ 4. Data Revalidation.......................................................................................... 16
● Activities and Solutions........................................................................................... 16
● Final Takeaways......................................................................................................16
13 Sep 2024 - Session 6.......................................................................................................17
Authentication...................................................................................................................17
● Agenda.............................................................................................................. 17
● Authentication Overview....................................................................................17
● Setting Up NextAuth..........................................................................................17
● Summary........................................................................................................... 19
16 Sep 2024 - Session 7.......................................................................................................20
CSS Modules, Global Styles, and Tailwind CSS.............................................................. 20
● Agenda.................................................................................................................... 20
● Activity 1.1: Identify the Issue..................................................................................20
● Debrief:....................................................................................................................20
● Activity 1.2: Using CSS Modules.............................................................................20
● Global Styles........................................................................................................... 21
● Tailwind CSS........................................................................................................... 21
18 Sep 2024 - Session 8.......................................................................................................22
Babel, Bundlers, Webpack, Vite, and Caching.................................................................22
● Agenda:................................................................................................................... 22
● Introduction to Babel............................................................................................... 22
● Introduction to Bundlers.......................................................................................... 23
● Webpack................................................................................................................. 23
● Introduction to Vite.................................................................................................. 24
● Webpack vs Vite Configuration............................................................................... 25
● CDN (Content Delivery Network)............................................................................ 25
● Caching................................................................................................................... 26
● Cache Invalidation...................................................................................................26
● Recap:..................................................................................................................... 26
20 Sep 2024 - Session 9.......................................................................................................27
Optimizing SEO and Performance for React App............................................................ 27
● Agenda.................................................................................................................... 27
● Notes:...................................................................................................................... 27
21 Sep 2024 - Session 10.....................................................................................................29
Enhancing Web Security and Testing Practices...............................................................29
● Agenda.................................................................................................................... 29
● Notes....................................................................................................................... 29
2 Sep 2024 - Session 1
Tailwind CSS
●​ Agenda
○​ Challenges with Traditional CSS
○​ Introduction to Tailwind CSS
○​ Utility Classes
■​ Typography
■​ Sizing and Spacing
■​ Border
○​ Responsive Design
○​ Handling Hover & other pseudo-classes
○​ Layouts
■​ Flex
■​ Grid
○​ Installing & Understanding Base Styles

●​ Challenges with Traditional CSS


○​ Traditional CSS Issues:
■​ Overwriting styles due to specificity: Conflicting styles, like
.header .title {color: blue;} vs. .title {color: red;}, can
cause unexpected behavior. More specific selectors will override
general ones.
■​ Growing complexity: As a project expands, selectors become
redundant, such as defining separate rules for .header .cta-button
and .footer .cta-button.
■​ Difficult maintenance: Managing and updating styles becomes
cumbersome, especially when multiple elements require similar styles.
■​ Unused CSS: Unused classes, like .old-button, increase the file
size, even when elements are removed from HTML.
■​ Multiple CSS files: Managing styles across several CSS files (e.g.,
base, layout, theme) can make troubleshooting harder.
○​ Tailwind CSS Solution:
■​ Instead of writing custom CSS rules, Tailwind allows developers to
style elements directly in HTML using utility classes, reducing
redundancy and avoiding complex CSS files.
■​ Tailwind avoids inline styling while still providing a clean, modular way
to apply styles efficiently.

●​ Introduction to Tailwind CSS


○​ Tailwind CSS: A utility-first framework that provides pre-built utility classes for
designing quickly and consistently.
■​ These classes offer responsive capabilities, design consistency, and
state styling (hover, focus, etc.), making them superior to inline styles.
○​ Tailwind Documentation:
■​ Search bar: Quickly locate specific utility classes.
■​ Navigation menu: Access various categories such as Typography,
Spacing, and Sizing.
■​ Code examples: Pre-built snippets are available to copy, modify, and
implement easily.
○​ Adding Styles: Styles are applied by simply adding utility classes directly to
HTML elements, allowing for a more streamlined development process.

●​ Utility Classes
○​ Utility Classes:
■​ Represent specific CSS properties and allow for direct styling within
HTML.
■​ Example:
<div class="text-center font-bold p-4">your content
here</div>
■​ Equivalent to Vanilla CSS:
.text-center { text-align: center; }​
.font-bold { font-weight: bold; }​
.p-4 { padding: 1rem; } /* 16px */
○​ Types of Utility Classes:
■​ Typography Utility Classes: For text styling.
■​ Spacing Utility Classes: For margin and padding.
■​ Sizing Utility Classes: For height and width.
■​ Border Utility Classes: For border properties.
○​ 1. Typography Utility Classes :
■​ Example:
●​ Tailwind:
<p class="text-xl font-semibold">This is
extra-large, semi-bold text.</p>
●​ Vanilla CSS
.text-xl { font-size: 1.25rem; }​
.font-semibold { font-weight: 600; }
■​ Demo: Using Tailwind Typography utility classes:
●​ Add large text, bold weight, and center-aligned styles.
●​ Example:
<p class="text-xl">This is a large text.</p>​
<p class="font-bold">This text is bold.</p>​
<p class="text-center">This text is centered.</p>
■​ Debrief: After adding the typography utility classes, the text will
display as large, bold, and center-aligned.
○​ 2. Spacing Utility Classes:
■​ Control spacing (margin and padding) with units based on a scale:
●​ 1 unit = 0.25rem (4px), 2 units = 0.5rem (8px), 4 units = 1rem
(16px), etc.
■​ Example:
●​ Tailwind:
<div class="p-6 mt-3">Your content here</div>
●​ Equivalent Vanilla CSS
div { padding: 1.5rem; margin-top: 0.75rem; }

■​ Demo:
●​ Use utility classes for different padding and margin
configurations (e.g., p-4, m-2, pl-8, mb-8).
○​ 3. Sizing Utility Classes:
■​ Set element sizes such as height and width.
■​ Fractional Widths: w-1/2, w-1/3, etc., for relative widths.
■​ Fixed Heights: h-24 corresponds to a height of 6rem.
■​ Example:
●​ Tailwind:
<div class="w-1/2 h-24">Your content here</div>
●​ Equivalent Vanilla CSS:
div { width: 50%; height: 6rem; }

■​ Demo:
●​ Use utility classes like w-1/2, h-24 for widths and heights
with background color adjustments.
■​ Debrief:
●​ Spacing and sizing utility classes allow quick adjustments
without writing custom CSS, ensuring consistency and ease of
use.
○​ 4. Border Utility Classes:
●​ Used to style elements' borders.
●​ Example:
○​ Tailwind:
<div class="border-2 rounded-lg">Your content
here</div>
○​ Equivalent Vanilla CSS:
div { border: 2px solid; border-radius: 0.5rem;
}

■​ Border Classes Scale:


●​ Border Width:
○​ border: 1px solid.
○​ border-2: 2px solid.
○​ border-4: 4px solid.
●​ Border Radius:
○​ rounded: Small rounded corners.
○​ rounded-lg: Large rounded corners (0.5rem or 8px).
○​ rounded-full: Fully rounded corners (circular).
■​ Demo:
●​ Apply different border and rounding configurations:
●​ 1px solid border, 2px solid border, large rounded corners, and
margin adjustments.
■​ Debrief:
●​ Border utility classes offer quick styling of borders and rounded
corners without writing custom CSS.
■​ Activity: Build a Card (Part 2):
●​ Add a 1px gray border, light blue background, bold centered
text (1.25rem font size), and 8px rounded corners.
●​ Responsive Design with Tailwind CSS
○​ Interactive Card Demo:
●​ Code example for creating a responsive card:
○​ <div class="w-full sm:w-64 h-48 p-4
mx-auto border border-gray-400 bg-blue-100
rounded-lg">​
<p class="text-center text-lg sm:text-xl
font-bold">Your content here</p>​
</div>

●​ Mobile-first approach: Tailwind applies styles to the smallest


screen sizes by default. As the screen size increases,
responsive utility classes (e.g., sm:, md:, lg:) adjust the
design.
○​ Responsive Utility Classes:
●​ Example:
○​ <div class="text-base md:text-lg
lg:bg-red-500">Responsive text and
background</div>
●​ Equivalent Vanilla CSS:
○​ div { font-size: 1rem; }​
@media (min-width: 768px) { div {
font-size: 1.125rem; } }​
@media (min-width: 1024px) { div {
background-color: #ef4444; } }

■​ Demo: Applying Responsive Utilities:


●​ Set responsive font sizes, background colors, padding, and
text alignment.
●​ Example:
○​ <div class="text-base md:text-lg
lg:text-xl bg-gray-200 md:bg-blue-400
lg:bg-green-500 p-4 md:p-6 lg:p-8">​
Responsive Design Example​
</div>

■​ Activity: Responsive Typography and Color:


●​ Use utility classes to adjust text color and font size based on
screen size, with text becoming bold on medium screens and
larger.
●​ Example:
○​ <div class="text-gray-500 md:text-blue-500
lg:text-green-500 text-sm md:text-base
lg:text-2xl font-medium md:font-bold">​
Responsive Typography and Color Example​
</div>

■​ Debrief:
●​ Tailwind's responsive utilities allow easy and dynamic
adjustments for different screen sizes, making it a powerful tool
for mobile-first and adaptive designs.
●​ Adding Hover Effects with Tailwind CSS
○​ Hover Effect Demo:
■​ Starter Code:
●​ Create a button with basic styling:
<button class="bg-blue-500 text-white px-4
py-2 rounded">Click Me</button>
○​ Hover Effect with Tailwind:
■​ Updated Code:
●​ Add a hover effect to change the button's background
color:
<div>​
<button class="bg-blue-500 text-white
px-4 py-2 rounded hover:bg-blue-700">Click
Me</button>​
<p class="text-gray-700">This text
changes color when the button is
hovered.</p>​
</div>
■​ The hover:bg-blue-700 class changes the button’s
background color when hovered.
○​ Debrief:
■​ Tailwind allows easy hover effects using the hover: prefix,
making it quick to add interactive styles.
●​ Flexbox, Grid, and Responsive Layouts with Tailwind CSS
○​ Flexbox Utility Classes:
■​ Tailwind provides utility classes for Flexbox properties (flex,
justify-content, align-items).
■​ Example:
<div class="flex justify-between items-center">​
<div>Item 1</div>​
<div>Item 2</div>​
<div>Item 3</div>​
</div>

○​ Flexbox Demo:
■​ Goal: Create a responsive pricing card layout that adapts from
a single-column on small screens to a two-column layout on
medium screens using Flexbox.
○​ Responsive Navbar Activity:
■​ Objective: Build a responsive navbar with a logo and menu
items. Use Tailwind to add hover effects and adapt the layout
for mobile and larger screens.
○​ Grid Utility Classes:
■​ Tailwind includes utility classes for grid properties
(grid-cols, gap, grid-rows).
■​ Example:
<div class="grid grid-cols-3 gap-4">​
<div>Item 1</div>​
<div>Item 2</div>​
<div>Item 3</div>​
</div>
■​
○​ Grid Layout Demo:
■​ Task: Implement a grid that has two columns on small screens
and expands to four columns on larger screens, with uniform
gaps and padding around the grid container.
○​ Grid Gallery Activity:
■​ Objective: Design a grid gallery with images, where:
●​ Images stack in one column on mobile screens.
●​ Transitions to 2-column on small screens and 3-column
on medium screens.
●​ Adds hover effects to change image opacity.
●​ Installing and Configuring Tailwind CSS
○​ Demo: Install Tailwind CSS
■​ Fork Code Sandbox: Track default styles.
■​ Install Tailwind CSS:
●​ npm install -D tailwindcss
■​ Initialize Tailwind Config:
●​ npx tailwindcss init
■​ Update tailwind.config.js:
module.exports = {​
content: ["./src/**/*.{html,js}"],​
// other configurations​
};
■​ Add Tailwind Directives to styles.css:
@tailwind base;​
@tailwind components;​
@tailwind utilities;
■​ Start Tailwind Build Process:
npx tailwindcss -i ./src/styles.css -o
./output.css --watch
■​ Include the Output File in index.html:
<link rel="stylesheet" href="./output.css">
■​ Check if Default Styles Changed: Verify if base styles have
been reset.
○​ Understanding Base Styles
■​ Purpose: Ensure consistent appearance across different
browsers and reset browser inconsistencies.
○​ Demo: Modifying tailwind.config.js
■​ Add Custom Font Family:
module.exports = {​
theme: {​
extend: {​
fontFamily: {​
display: ['Pally', 'Comic Sans MS',
'sans-serif'],​
body: ['Pally', 'Comic Sans MS',
'sans-serif'],​
},​
},​
},​
// other configurations​
};
■​ Apply Custom Font in App.js:
●​ For h1: Use class="font-display"
●​ For p: Use class="font-body"
■​ Ensure Fonts Update: Verify that the fonts have been applied
correctly.

4 Sep 2024 - Session 2


Introduction to Client-Side Rendering and Server Side Rendering
●​ Agenda
○​ Client-Side Rendering (CSR)
○​ Server-Side Rendering (SSR)
○​ Difference between CSR and SSR
○​ Next.js Project Setup and Codebase Walkthrough
○​ Client and Server Components
●​ Introduction to Rendering Methods
○​ Client-Side Rendering (CSR):
■​ Scenario: Cooking food yourself.
■​ Process: The browser downloads HTML and JavaScript. JavaScript
then builds the DOM and renders the page. This is similar to cooking
and serving food yourself; the client (browser) does the processing.
○​ Server-Side Rendering (SSR):
■​ Scenario: Getting a fully prepared meal at a restaurant.
■​ Process: The server prepares and sends a fully rendered HTML
page. This is like ordering a meal where everything is prepared by the
chef before it reaches your table.
●​ Comparison: CSR vs. SSR
○​ Rendering Process:
■​ CSR: Done in the client’s browser.
■​ SSR: Done on the server.
○​ Initial Page Load Time:
■​ CSR: Slower initial load; a blank screen may appear first.
■​ SSR: Faster initial load; the page appears fully rendered.
○​ Server Load:
■​ CSR: Lower server load; most processing is done on the client.
■​ SSR: Higher server load; the server does most of the processing.
●​ Demo
○​ CSR Demo: Show the delayed rendering process where content appears in
stages.
○​ SSR Demo: Show a fully rendered page appearing instantly.
●​ Next.js Project Setup
○​ Create a New Project:
■​ Command: npx create-next-app <project-name>
○​ Project Walkthrough:
■​ Explore the project structure and components.
○​ Activity:
■​ Build a basic UI component with hardcoded values.
■​ Add event listeners to interact with components.
■​ Understand the difference between server and client components.
●​ Client and Server Components in Next.js
○​ Server Components: Rendered on the server, can’t access browser APIs.
○​ Client Components: Rendered on the client, can handle user interactions
and browser-specific APIs.
○​ Converting a Server Component to a Client Component:
○​ Use the 'use client' directive at the top of the component file to make it a
client component.
●​ Summary
○​ CSR: Provides dynamic and interactive content but with a slower initial load.
○​ SSR: Offers faster initial load and better SEO but places more load on the
server.
○​ Client Components: Suitable for interactive features.
○​ Server Components: Ideal for static content and performance optimization.

6 Sep 2024 - Session 3


Routing
●​ Agenda
○​ Routing
○​ App Router
○​ File-based Routing
○​ Link Component
○​ Nested Routes
○​ Dynamic Routes
○​ Nested Dynamic Routes
●​ Introduction to Routing
○​ Scenario: Navigating an airport.
■​ Enter the airport
■​ Go to luggage drop
■​ Proceed to security check
■​ Head to boarding gates
■​ Find your seat on the plane
○​ Analogy: Just as airport signs guide you, routes in a web application guide
users between pages.
●​ Routing in Next.js
○​ App Router: Automatically maps files to routes based on their location in the
app directory.
○​ File-based Routing: URL paths match the file structure in the app directory
(e.g., app/about/page.js corresponds to /about).
●​ Implementation Steps
○​ Building a Mini Blog Application:
■​ Fork Template: Provide a Next.js code sandbox template.
■​ Implement Routes: Create routes according to the provided diagram.
○​ Creating Links:
■​ Using <a> Tags: Results in a full-page reload.
■​ Using <Link> Component: Prevents full-page refresh and improves
navigation efficiency.
○​ Implementing Nested Routes:
■​ Syntax and Implementation: Create nested routes as shown in the
diagram.
○​ Implementing Dynamic Routes:
■​ Dynamic Routing: Handles URL parameters (e.g.,
app/product/[id]/page.js for /product/123).
○​ Implementing Nested Dynamic Routes:
■​ Nested Dynamic Routing: Combines nested and dynamic routes for
multi-level URL parameters (e.g.,
app/category/[category]/product/[id]/page.js for
/category/electronics/product/123).
●​ Summary
○​ Routing: Maps URLs to components or handlers in an application.
○​ App Router: Automatically handles routing based on file structure.
○​ File-based Routing: Matches URL paths to the file structure.
○​ Nested Routing: Organizes routes hierarchically.
○​ Dynamic Routing: Uses URL parameters for dynamic content.
○​ Nested Dynamic Routing: Combines nested and dynamic routes for
complex URL structures.
●​ Takeaway
○​ Understanding: Need for routing in web applications and how to implement it
using Next.js.
○​ Goal: Implement routing and navigation features using Next.js’s App Router,
file-based routing, and dynamic routing.

9 Sep 2024 - Session 4


Navigation
●​ Agenda
○​ Traditional Navigation vs. Next Navigation
○​ URL Objects
○​ Retrieving Route and Query Parameters
○​ Navigating Programmatically using useRouter Hook
○​ Key Methods of useRouter
●​ Traditional vs. Next Navigation
○​ Traditional Navigation:
■​ Scenario: Shopping in separate stores for groceries, clothes, and
shoes.
■​ Anchor Tag (<a>) Navigation:
●​ Causes full page reloads.
●​ Server handles route changes and sends full HTML for each
route.
●​ Example: <a href="/products">View Products</a>
■​ Key Points:
●​ Fetches full page data on every request.
●​ Full page reload occurs.
●​ Server-side routing.
○​ Next Navigation:
■​ Scenario: Shopping in a large supermarket with all items in one place.
■​ <Link> Component:
●​ Avoids full page reloads.
●​ Fetches only new data required to render the page.
●​ Example: import Link from 'next/link'
■​ Key Points:
●​ Fetches only new data.
●​ Implements client-side routing.
●​ Navigation is smoother and faster.
○​ Key Takeaways:
○​ Traditional Routing: Full page reload, server-side routing.
○​ Next.js Navigation: Client-side routing, avoids full page reloads.
●​ URL Objects
○​ Traditional Link Creation:
import Link from 'next/link';​
export default function ProductLink() {​
return <Link
href="/product?sort=name&category=electronics">View
Products</Link>;​
}
○​ Using URL Objects:
import Link from 'next/link';​
export default function ProductLink() {​
const url = {​
pathname: '/product',​
query: { sort: ['name', 'price'], category:
['electronics', 'books'] }​
};​
return <Link href={url}>View Products</Link>;​
}

○​ Benefits:
■​ Cleaner and more flexible code.
■​ Supports query parameters and dynamic link creation.
●​ Retrieving Route and Query Parameters
○​ Using useParams Hook:
import { useParams } from 'next/navigation';​
export default function ProductPage() {​
const params = useParams();​
const pageId = params.pageId;​
return <h1>Product Page: {pageId}</h1>;​
}
○​
○​ Using useSearchParams Hook:
import { useSearchParams } from 'next/navigation';​
export default function Page() {​
const searchParams = useSearchParams();​
const category = searchParams.get('category');​
const sort = searchParams.get('sort');​
return (​
<div>​
<p>Category: {category}</p>​
<p>Sort: {sort}</p>​
</div>​
);​
}
○​
○​ Key Points:
■​ useParams(): Retrieves route parameters.
■​ useSearchParams(): Retrieves query parameters.
■​ Simplifies access to URL data.
●​ Navigating Programmatically with useRouter Hook
○​ Example Usage:
import { useRouter } from 'next/navigation';​
export default function AboutPage() {​
const router = useRouter();​
function handleNavigate() {​
router.push('/about');​
}​
return <button onClick={handleNavigate}>Go to About
Page</button>;​
}
○​
○​ Key Methods:
■​ router.push('/path'): Navigate to a specific route.
■​ router.back(): Go back to the previous page.
■​ router.replace('/path'): Navigate to a route without adding to
history stack.
○​ Difference between router.push() and router.replace():
■​ router.push(): Adds new route to history, allows navigating back.
■​ router.replace(): Replaces the current route in history, prevents
navigating back.
●​ Activities
○​ Create Pages and Implement Navigation:
■​ Implement pages (/, /page1, /page2).
■​ Use router.push() and router.replace() to navigate and
observe differences.
○​ Using useRouter:
■​ Create an "About" page and navigate programmatically from the home
page using buttons.
●​ Conclusion
○​ Understanding Routing: Importance of client-side vs. server-side routing,
and the benefits of Next.js’s navigation methods.
○​ Practical Application: Implementing and using routing methods effectively in
Next.js applications.
12 Sep 2024 - Session 5
Data Fetching
●​ Agenda Overview
○​ Data Fetching (Client Side vs Server Side)
○​ Static Site Generation using generateStaticParams
○​ Data Caching
○​ Data Revalidation
●​ Detailed Breakdown
○​ 1. Data Fetching (Client Side vs Server Side)
■​ Scenario 1 (Client-Side Fetching):
●​ The librarian fetches the book when a visitor asks. This is
analogous to client-side fetching where data is loaded
dynamically on each request, often resulting in longer wait
times and multiple server requests.
●​ Activity: Demonstrate client-side data fetching using React
hooks like useEffect and useState.
■​ Scenario 2 (Server-Side Fetching):
●​ The librarian prepares popular books in advance for visitors.
This is analogous to server-side rendering (SSR) where data is
fetched and rendered on the server, resulting in faster initial
page loads.
●​ Activity: Demonstrate server-side data fetching using
server-side functions.
○​ 2. Static Site Generation (SSG) using generateStaticParams
■​ Scenario: Pages are pre-generated at build time, so when a visitor
requests a page, it’s served quickly without additional server requests.
●​ Activity: Implement generateStaticParams to pre-render
pages at build time, reducing server load and improving load
times.
■​ Code:
export async function generateStaticParams() {​
const posts = await
fetch('https://jsonplaceholder.typicode.com/posts').th
en(res => res.json());​
return posts.map(post => ({ id: post.id.toString()
}));​
}
●​
■​ Debrief: SSG improves performance by pre-rendering pages and
reducing server load during requests.
○​ 3. Data Caching
■​ Activity: Demonstrate caching by changing cache settings and
observing effects on data fetching and loading times.
●​ Code: Change cache settings from no-store to
force-cache to see how data retrieval is affected.
●​ Discussion: Explain how caching improves performance by
storing and reusing previously fetched data, reducing server
load, and speeding up response times.
■​ Concepts:
●​ Request Memoization (In-memory): Temporary caching for
the duration of a request.
●​ Data Cache (Persistent): Long-term caching across multiple
requests.
○​ 4. Data Revalidation
■​ Activity: Implement revalidation to update cached data at specific
intervals.
●​ Code: Add { next: { revalidate: 10 } } to API calls
to revalidate data every 10 seconds.
●​ Discussion: Revalidation ensures that cached data is updated
periodically, maintaining a balance between performance and
data freshness.
●​ Activities and Solutions
○​ Data Fetching (Server Side)
■​ Fetch posts and display them on the homepage.
■​ Implement a post page with individual post details.
■​ Solution: Fork the provided CodeSandbox links for practical
implementation.
○​ Static Site Generation
■​ Pre-generate pages during build time and observe the reduced server
load and improved load times.
■​ Solution: Build the project and inspect the
.next/server/app/post directory for generated pages.
○​ Caching
■​ Change caching settings and compare loading times and data
freshness.
■​ Solution: Refresh the page and check network requests to observe
caching effects.
○​ Data Revalidation
■​ Implement revalidation and observe how data updates at specified
intervals.
■​ Solution: Modify API calls and refresh to see the impact of
revalidation.
●​ Final Takeaways
○​ Client-Side vs Server-Side Fetching: Client-side fetching is dynamic but
slower, while server-side fetching provides faster initial loads.
○​ Static Site Generation: Pre-generates pages at build time, improving
performance and reducing server load.
○​ Caching: Improves performance by storing and reusing data, reducing the
need for repeated server requests.
○​ Revalidation: Keeps cached data up-to-date while maintaining performance
benefits.

13 Sep 2024 - Session 6


Authentication
●​ Agenda
○​ Introduction to Authentication and How It Works
○​ Setting Up NextAuth
○​ Implementing Authentication Providers
○​ Creating Protected Routes
○​ Accessing User Data
○​ Introduction to Middleware
○​ Implementing Authentication Middleware
●​ Authentication Overview
○​ Authentication Definition: Verifying the identity of a user to prevent
unauthorized access to sensitive information and functionalities.
○​ Registration Flow:
■​ Client sends registration data (username, email, password) to the
server.
■​ Server validates data, checks for existing users, hashes the password,
and saves the new user.
■​ Server responds with success or failure.
○​ Login Flow:
■​ Client sends login credentials (username/email, password) to the
server.
■​ Server fetches user data and verifies the password.
■​ On success, a JWT is generated and sent back to the client for future
requests.
○​ Authenticated Requests:
■​ Client includes JWT in the Authorization header of requests.
■​ Server verifies the JWT and responds with requested data or an error
if invalid.
●​ Setting Up NextAuth
○​ 1. Installation:
■​ Install next-auth with: npm install next-auth
○​ 2. Create GitHub OAuth Application:
■​ Set Homepage URL to http://localhost:3000
■​ Set Authorization URL to
http://localhost:3000/api/auth/callback/github
■​ Note Client ID and Client Secret.
○​ 3. Configure Environment Variables:
■​ Create a .env.local file with:
GITHUB_ID=your_github_client_id​
GITHUB_SECRET=your_github_client_secret​
NEXTAUTH_SECRET=your_nextauth_secret

○​ 4. Setup Authentication API Route:


■​ Create app/api/auth/[...nextauth]/route.js:
import NextAuth from "next-auth";​
import GithubProvider from
"next-auth/providers/github";​

const handler = NextAuth({​
providers: [​
GithubProvider({​
clientId: process.env.GITHUB_ID,​
clientSecret: process.env.GITHUB_SECRET,​
}),​
],​
});​

export { handler as GET, handler as POST };

○​ 5. Create SessionProvider Component:


■​ In components/SessionProvider.js:
'use client';​
import { SessionProvider } from "next-auth/react";​

export default function NextAuthSessionProvider({
children }) {​
return
<SessionProvider>{children}</SessionProvider>;​
}

○​ 6. Update Root Layout:


■​ Modify app/layout.js to include NextAuthSessionProvider:
import NextAuthSessionProvider from
'@/components/SessionProvider';​

export default function RootLayout({ children }) {​
return (​
<html lang="en">​
<body>​

<NextAuthSessionProvider>{children}</NextAuthSessionPr
ovider>​
</body>​
</html>​
);​
}
■​
○​ 7. Update Homepage for Authentication:
■​ Modify app/page.js to handle login/logout functionality and display
user info.
○​ 8. Create Protected Route:
■​ Implement app/protected/page.js:
import { getServerSession } from "next-auth/next";​
import { options } from
"../api/auth/[...nextauth]/route";​
oimprt { redirect } from "next/navigation";​
import Link from "next/link";​

export default async function ProtectedPage() {​
const session = await getServerSession(options);​

if (!session) {​

redirect("/api/auth/signin?callbackUrl=/protected");​
}​

return (​
<div>​
<h1>Protected Page</h1>​
<p>Welcome, {session.user.name}!</p>​
<Link href="/">Go to Home</Link>​
</div>​
);​
}
○​
●​ Summary
○​ NextAuth Setup:
■​ Installed and configured NextAuth with GitHub as the authentication
provider.
■​ Set up environment variables and API routes.
■​ Implemented session management with SessionProvider.
○​ Home Page and Protected Routes:
■​ Updated the home page to handle user authentication status.
■​ Created a protected route accessible only to authenticated users.
○​ Middleware and Access Control:
■​ Discussed the basics of implementing middleware for authentication
and access control.




16 Sep 2024 - Session 7
CSS Modules, Global Styles, and Tailwind CSS
●​ Agenda
○​ CSS Modules
○​ Global Styles
○​ Tailwind CSS
●​ Activity 1.1: Identify the Issue
○​ Task: Identify styling issues in the Card and Alert components.
■​ Current View vs. Expected View: The design has color issues.
■​ CSS Files: Alert.css and Card.css both contain the same styles.
■​ Inspection: Colors are not as expected due to CSS cascading and
specificity issues.
●​ Debrief:
○​ Cascading: In CSS, the last imported stylesheet’s rules override earlier ones
if they have the same specificity.
○​ Specificity: If styles have the same specificity, the order of stylesheet imports
determines which styles apply.
●​ Activity 1.2: Using CSS Modules
○​ Rename CSS Files:
■​ Change Alert.css to Alert.module.css and Card.css to
Card.module.css.
○​ Modify Imports:
■​ Import styles as objects in Alert.jsx and Card.jsx.
○​ Example:
import styles from './Alert.module.css';

○​ Apply Styles:
■​ Update the components to use the imported styles object.
○​ Verify UI:
■​ Check that the styles are now applied correctly and class names are
unique, avoiding collisions.
●​ Global Styles
○​ Usage: Place global styles (e.g., font-family, background color) in
globals.css.
○​ Integration: Import globals.css in your main layout or _app.js to apply
styles globally.
○​ Note: Media queries and other global styles should be included here as they
don't work well with module-scoped CSS.
●​ Tailwind CSS
○​ Introduction:
■​ Utility-First Framework: Build designs using predefined utility
classes.
■​ Analogy: Like LEGO blocks, utility classes are used to construct UI
elements quickly.
○​ Integration:
■​ New Next.js App: Use npx create-next-app@latest
my-tailwind-app and select Tailwind CSS during setup.
■​ Existing Next.js App:
○​ Install Tailwind CSS and its dependencies:
npm install -D tailwindcss postcss autoprefixer

○​ Initialize Tailwind:
npx tailwindcss init -p

○​ Update tailwind.config.js:
/** @type {import('tailwindcss').Config} */​
module.exports = {​
content: [​
"./app/**/*.{js,ts,jsx,tsx,mdx}",​
"./pages/**/*.{js,ts,jsx,tsx,mdx}",​
"./components/**/*.{js,ts,jsx,tsx,mdx}",​
"./src/**/*.{js,ts,jsx,tsx,mdx}",​
],​
theme: {​
extend: {},​
},​
plugins: [],​
}
○​ Update global CSS file (app/globals.css):
@tailwind base;​
@tailwind components;​
@tailwind utilities;

○​ Test Integration:
■​ Add a Tailwind CSS test component in app/page.jsx to verify setup:
export default function TailwindTest() {​
return (​
<div className="flex items-center justify-center
min-h-screen bg-teal-600">​
<h1 className="text-3xl font-bold text-white
bg-teal-500 p-4 rounded-lg shadow-md">​
Tailwind CSS is working!​
</h1>​
</div>​
)​
}



18 Sep 2024 - Session 8


Babel, Bundlers, Webpack, Vite, and Caching
●​ Agenda:
○​ Introduction to Babel
○​ Setting up Babel
○​ Introduction to Bundlers
○​ Webpack
○​ Setting up Webpack
○​ Introduction to Vite
○​ Creating a React Vite Project
○​ Webpack vs Vite: Configuration
○​ CDN
○​ Caching
○​ Cache Invalidation
●​ Introduction to Babel
○​ Purpose: Babel transpiles modern JavaScript (ES6+) into older versions
(e.g., ES5) compatible with legacy browsers such as IE11.
○​ Demo: Converted arrow functions and template literals to ES5 syntax.
○​ Activity:
○​ Install Babel packages:​
bash​
Copy code​
npm install --save-dev @babel/core @babel/preset-env
@babel/cli
■​
○​ Configure .babelrc:​
json​
Copy code​
{
○​ "presets": ["@babel/preset-env"]
○​ }
■​
○​ Transpile Code: Create an app.js file, then use Babel CLI:​
bash​
Copy code​
npx babel src --out-dir dist
■​
■​ Result: Transpiled code stored in dist folder shows modern
JavaScript converted to older syntax.
○​ Debrief: Babel transforms modern JavaScript features (e.g., arrow functions,
let/const) into older, compatible syntax (e.g., var, regular functions).
●​ Introduction to Bundlers
○​ Purpose: Bundlers combine and optimize multiple code files into a single
production-ready bundle, managing complex dependency trees and reducing
HTTP requests.
○​ Core Concepts:
■​ Entry Point: Where bundling starts (e.g., src/index.js).
■​ Output: Defines where the bundle will be saved and its filename.
■​ Loaders: Transform files (e.g., Babel loader for JS, CSS loaders).
■​ Plugins: Perform advanced tasks like HTML file generation and code
minification.
●​ Webpack
○​ Setup:
■​ Entry and Output Configuration: Specifies the entry file and the
location of the output bundle.
■​ Loaders: Added JS and CSS loaders to transform and process files.
■​ Plugins: Used HtmlWebpackPlugin to automatically generate HTML
for the app.
○​ Activity:
○​ Install Webpack:​
bash​
Copy code​
npm install --save-dev webpack webpack-cli
■​
○​ Create Webpack Config: In webpack.config.js, configure:​
javascript​
Copy code​
const path = require('path');
○​
○​ module.exports = {
○​ entry: './src/index.js',
○​ output: {
○​ filename: 'bundle.js',
○​ path: path.resolve(__dirname, 'dist'),
○​ },
○​ module: {
○​ rules: [
○​ {
○​ test: /\.js$/,
○​ exclude: /node_modules/,
○​ use: 'babel-loader',
○​ },
○​ ],
○​ },
○​ plugins: [
○​ new HtmlWebpackPlugin({
○​ template: './src/index.html',
○​ }),
○​ ],
○​ };
■​
○​ Run Webpack Build:​
bash​
Copy code​
npx webpack
■​
○​ Debrief: Webpack bundles multiple files into a single optimized file for
production and uses loaders and plugins to handle different file types (CSS,
JS, HTML).
●​ Introduction to Vite
○​ Purpose: Vite is a modern build tool optimized for fast development. Unlike
Webpack, it serves unbundled code during development and leverages
Rollup for production builds.
○​ Features:
■​ esbuild Pre-bundling: Vite uses esbuild for fast pre-bundling of
dependencies.
■​ Native ES Modules: Vite serves unbundled ES modules during
development for fast feedback.
■​ Rollup for Production: For production, Vite switches to Rollup for
advanced optimizations like tree shaking and code splitting.
○​ Activity:
○​ Create React Vite Project:​
bash​
Copy code​
npm create vite@latest my-vite-app -- --template react
○​ cd my-vite-app
○​ npm install
○​ npm run dev
■​
■​ Result: A development server launches with instant hot module
replacement (HMR) and fast build times.
○​ Debrief: Vite simplifies the development workflow with near-instant startup
and optimized production builds using Rollup.
●​ Webpack vs Vite Configuration
○​ Webpack: Detailed configuration with explicit loaders, entry/output settings,
and plugins required.
○​ Vite: Simpler configuration with smart defaults; only requires minimal setup
for plugins (e.g., React plugin).
○​ Comparison Example:​
javascript​
Copy code​
// webpack.config.js
○​ const path = require('path');
○​ module.exports = {
○​ entry: './src/index.js',
○​ output: {
○​ filename: 'bundle.js',
○​ path: path.resolve(__dirname, 'dist'),
○​ },
○​ module: {
○​ rules: [
○​ { test: /\.js$/, exclude: /node_modules/, use:
'babel-loader' },
○​ ],
○​ },
○​ };
○​ javascript​
Copy code​
// vite.config.js
○​ import { defineConfig } from 'vite';
○​ import react from '@vitejs/plugin-react';
○​ export default defineConfig({ plugins: [react()] });
●​ CDN (Content Delivery Network)
○​ Purpose: A CDN is a distributed network of servers that cache and serve
content closer to users, reducing latency and improving load times.
○​ Activity:
■​ Check CDN Usage: Head over to CDN Finder and check if the logo
URL from ZCommerce uses a CDN.
■​ Result: If a CDN is used, content is served from the nearest server,
improving load times globally.
○​ Debrief: A CDN ensures faster content delivery by caching resources on
edge servers distributed worldwide.
●​ Caching
○​ Purpose: Caching stores content (e.g., HTML, CSS, JS) to improve delivery
speed and reduce server load.
○​ Caching Strategies:
■​ Time-based Caching: Content is cached for a set time before it
refreshes.
■​ Purge-based Caching: Manually clears or updates the cache.
■​ Query-based Caching: Changes the cache by appending unique
query strings to URLs when content is updated.
○​ Activity: Explore caching by comparing content load times before and after
caching is applied, noting performance improvements.
●​ Cache Invalidation
○​ Purpose: Ensures that users receive updated content by managing stale
cached data.
○​ Strategies:
■​ Versioned URLs: Append version numbers to assets (e.g.,
style.css?v=2).
■​ Cache-Busting Systems: Change filenames or URLs to trigger
cache refresh.
■​ CDN Purge APIs: Programmatically clear specific cached content on
CDN servers.
○​ Debrief: Proper cache invalidation ensures fresh content is served without
degrading performance by overusing cache refreshes.
●​ Recap:
○​ Babel: Transpiles modern JavaScript for backward compatibility with older
browsers.
○​ Bundlers (Webpack, Vite): Optimize code, reduce file sizes, and manage
dependencies.
○​ Vite: Offers faster development builds and simpler configuration compared to
Webpack.
○​ CDN: Enhances content delivery performance by caching resources closer to
users.
○​ Caching & Cache Invalidation: Improve load times and ensure fresh content
delivery through various strategies.
●​
20 Sep 2024 - Session 9
Optimizing SEO and Performance for React App
●​ Agenda
○​ How Google Crawls and Indexes Web Pages
○​ SEO
○​ Sitemaps
○​ Robots.txt
○​ Lighthouse
○​ Core Web Vitals
○​ Common Fixes for Performance
●​ Notes:
○​ Google Search Scenario
■​ Imagine encountering a bug and using Google to find a solution.
■​ How Google ranks search results.
○​ How Google Crawls and Indexes Web Pages
■​ Crawling: Googlebot explores web pages through links and config
files.
■​ Indexing: Analyzes content, organizes information for quick retrieval.
■​ Ranking: Considers factors like content relevance, quality, page
reputation, and user engagement.
○​ Importance of SEO for React Apps
■​ Optimizes visibility in search engines.
■​ Challenges with single-page applications (SPAs).
■​ Enhances overall visibility and user experience.
○​ Key SEO Elements
■​ Title tags
■​ Meta descriptions
■​ Header tags (H1, H2, H3)
■​ URL structure
■​ Internal linking
■​ Image optimization
○​ Activity: SEO-friendly React Component
■​ Create a reusable React component using React Helmet to set SEO
tags dynamically.
○​ Example Component Structure
import { Helmet } from 'react-helmet';​

const SEOComponent = ({ title, description, keywords }) => (​
<Helmet>​
<title>{title}</title>​
<meta name="description" content={description} />​
<meta name="keywords" content={keywords} />​
</Helmet>​
);
○​ Using the SEO Component
■​ Implement the component in App.jsx.
■​ Inspect the <head> section to verify meta tags.
○​ Sitemaps
■​ XML files that list important pages.
■​ Helps search engines crawl sites effectively.
○​ Components of an XML Sitemap
■​ <urlset>: Root element.
■​ <url>: Parent tag for each URL.
■​ <loc>: Page URL.
■​ <lastmod>: Last modification date.
■​ <changefreq>: Frequency of changes.
■​ <priority>: URL priority.
○​ Types of Sitemaps
■​ XML Sitemaps
■​ Image Sitemaps
■​ Video Sitemaps
■​ News Sitemaps
○​ Robots.txt
■​ Text file that instructs search engines on how to crawl the site.
■​ Example Structure:​
makefile​
Copy code​
User-agent: *
■​ Allow: /
■​ Sitemap: https://yoursite.com/sitemap.xml
○​
○​ Lighthouse
■​ Open-source tool for auditing web page quality.
■​ Features: Performance, Accessibility, SEO, Best Practices.
■​ Integrated into Chrome DevTools.
○​ Core Web Vitals
■​ Metrics for user experience:
●​ LCP: Loading performance.
●​ INP: Interactivity.
●​ CLS: Visual stability.
○​ Optimizing Core Web Vitals
■​ LCP Optimization: Improve loading time for main content.
■​ INP Optimization: Enhance responsiveness of interactions.
■​ CLS Optimization: Maintain visual stability during page load.
○​ Common Fixes for Performance
■​ Compress Images: Reduce file sizes without quality loss.
■​ Minify CSS/JS: Remove unnecessary characters from code.
■​ Implement Lazy Loading: Load non-critical resources when needed.
■​ Use a CDN: Improve asset delivery and reduce server load.
○​ Recap
■​ Covered Google crawling and indexing, SEO strategies, key elements,
tools (Sitemaps, Robots.txt, Lighthouse), and Core Web Vitals.
■​ Discussed common performance fixes.
●​

21 Sep 2024 - Session 10


Enhancing Web Security and Testing Practices
●​ Agenda
○​ HTTPS
○​ SSL Certificate
○​ SQL Injection
○​ Unit Testing
○​ Test Structure
○​ Assertions
○​ Browser Storage
○​ Best Practices
●​ Notes
○​ Scenario: Secure Connection Importance
■​ Preference: Secure connection for payment over insecure.
○​ Introduction to HTTPS
■​ Definition: Hypertext Transfer Protocol Secure (HTTPS = HTTP +
Security).
■​ Benefits: Confidentiality, Integrity, Authentication.
■​ Problem with HTTP: Sends data in plain text, vulnerable to attacks.
○​ HTTP Vulnerability
■​ Issues: Eavesdropping, tampering, impersonation.
■​ Graphic Explanation: Attackers can manipulate HTTP
communications.
○​ HTTP vs. HTTPS Analogy
■​ HTTP: Like sending a postcard (readable by anyone).
■​ HTTPS: Like sending a sealed letter (encrypted).
○​ Key Differences
Feature HTTP

Encryption No

Authentication No

Vulnerability Yes

○​ Activity: Spot the Difference


■​ Task: Compare HTTP and HTTPS response headers in browser tools.
○​ How HTTPS Works
■​ SSL Certificate: Authenticates server identity and encrypts data.
○​ Introduction to SSL Certificate
■​ Purpose: Encrypts data, authenticates website, enables HTTPS.
■​ Analogy: Digital passport for websites.
○​ Components of SSL Certificate
■​ Public Key
■​ Private Key
■​ Certificate Authority (CA)
○​ Types of SSL Certificates
■​ Domain Validated (DV)
■​ Organization Validated (OV)
■​ Extended Validation (EV)
○​ Obtaining an SSL Certificate
■​ Choose a Certificate Authority
■​ Generate Certificate Signing Request (CSR)
■​ CA verifies domain ownership
■​ Install certificate on web server
○​ SQL Injection Scenario
■​ Example: Logging into a website with injected SQL statement.
○​ Introduction to SQL Injection
■​ Definition: Manipulating database queries via unsanitized inputs.
○​ Common Injection Attack Vectors
■​ User input fields
■​ URL parameters
■​ HTTP headers
○​ Prevention Techniques
■​ Input Validation: Check input type/format.
■​ Input Sanitization: Escape special characters, use parameterized
queries.
○​ Demo: SQL Injection Attack
■​ Task: Log in with SQL injection and observe vulnerabilities.
○​ Unit Testing Overview
■​ Definition: Testing individual pieces of code.
■​ Test-Driven Development (TDD): Write tests before code.
○​ Introduction to Jest
■​ Definition: JavaScript testing framework.
■​ Key Features: Built-in assertions, zero configuration, snapshot
testing.
○​ Test Structure in Jest
■​ Structure: Use describe to group tests; it/test to define cases.
○​ Assertions in Jest
■​ Types:
●​ toBe: Strict equality.
●​ toEqual: Deep equality.
●​ toContain: Array/string inclusion.
○​ Demo: Unit Testing a Function
■​ Task: Write and run tests in CodeSandBox.
○​ Browser Storage Overview
■​ Types: Cookies, localStorage, sessionStorage.
○​ Storage Mechanisms Analogy
■​ localStorage: Permanent storage (home safe).
■​ sessionStorage: Temporary storage (hotel safe).
■​ Cookies: Portable but limited (wallet).
○​ When to Use Each
■​ localStorage: Long-term, non-sensitive data.
■​ sessionStorage: Temporary, non-sensitive data.
■​ Cookies: Small, portable data (e.g., authentication tokens).
○​ Code Organization Principles
■​ Code Modularity: Easier maintenance and reusability.
■​ Single Responsibility Principle: Each module should have one
responsibility.
■​ DRY Principle: Avoid repeating code.
○​ Organizing React Projects
■​ Feature-based: Group by feature.
■​ Component-based: Group by components.
○​ Recap
■​ Discussed HTTPS, SSL certificates, SQL injection prevention, unit
testing, browser storage, and code organization best practices.

You might also like