<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Vikash Kumar</title>
    <description>The latest articles on Forem by Vikash Kumar (@ervikash).</description>
    <link>https://forem.com/ervikash</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3729042%2F04110595-f507-4aa0-ac5b-e22cf1691c2a.png</url>
      <title>Forem: Vikash Kumar</title>
      <link>https://forem.com/ervikash</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/ervikash"/>
    <language>en</language>
    <item>
      <title>The “Proving” Trap: How Positioning Myself as a Strategic Architect Changed My Career</title>
      <dc:creator>Vikash Kumar</dc:creator>
      <pubDate>Fri, 23 Jan 2026 17:19:00 +0000</pubDate>
      <link>https://forem.com/ervikash/the-proving-trap-how-positioning-myself-as-a-strategic-architect-changed-my-career-1f7g</link>
      <guid>https://forem.com/ervikash/the-proving-trap-how-positioning-myself-as-a-strategic-architect-changed-my-career-1f7g</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzt82pvpxwg41byew6diz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzt82pvpxwg41byew6diz.png" width="800" height="422"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;For a long time, I operated on a clear, effective algorithm: &lt;strong&gt;Value = Technical Depth + Execution Speed.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In the first half of my career, this was my North Star. I took pride in being the person who could solve any bug, refactor any legacy mess, and out-code the room. I thought leadership was the natural reward for being the most technically capable person on the team. I was “proving” my worth through sheer output.&lt;/p&gt;

&lt;p&gt;But as I moved toward the role of a Technical Architect, I realized that the skills that made me a great Senior Engineer were only half of the equation. To truly lead, I had to stop &lt;strong&gt;proving&lt;/strong&gt; my technical brilliance and start &lt;strong&gt;positioning&lt;/strong&gt; my impact.&lt;/p&gt;

&lt;p&gt;Here is how I evolved my working style and thought process to bridge the gap between code and leadership.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. From “How” to “Why”: Evolving the Mindset
&lt;/h3&gt;

&lt;p&gt;In my earlier years, my focus was almost entirely on the &lt;em&gt;How&lt;/em&gt;. I obsessed over the “perfect” implementation, the most elegant design patterns, and the latest frameworks. This was necessary for building a strong foundation, but leadership requires a wider lens.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;The Evolution:&lt;/strong&gt; I shifted my focus from technical mechanics to business intent. Before looking at a single line of code for a new feature, I began asking: &lt;em&gt;“What user behavior are we trying to change?”&lt;/em&gt; and &lt;em&gt;“Is this the most efficient path to that outcome?”&lt;/em&gt; *&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The Result:&lt;/strong&gt; I moved from being a “resource” who executed a roadmap to a partner who helped define it. By understanding the &lt;em&gt;Why&lt;/em&gt;, I could offer technical solutions that were more aligned with the company’s long-term goals.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  2. Shifting the Lens from Depth to Impact
&lt;/h3&gt;

&lt;p&gt;Earlier in my career, I advocated for technical health by citing “cyclomatic complexity” or “clean code.” While those metrics were technically accurate, they didn’t always resonate outside of the engineering department.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;The Evolution:&lt;/strong&gt; I stopped acting as a translator and started acting as a &lt;strong&gt;bridge&lt;/strong&gt;. I began discussing technical debt and architecture in terms of &lt;strong&gt;velocity&lt;/strong&gt; and &lt;strong&gt;risk&lt;/strong&gt;. I stopped saying “The code is messy” and started saying, “Investing in this stabilization now ensures we can launch three new features next quarter without a performance hit.”&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The Result:&lt;/strong&gt; By aligning technical expertise with the business’s heartbeat, I didn’t have to “ask” for a seat at the table. I was already vital to the conversation because I was speaking the language of outcomes.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  3. Scaling Influence: From Gatekeeper to Force Multiplier
&lt;/h3&gt;

&lt;p&gt;There is a certain satisfaction in being the “hero” who saves the day during a production outage. But a leader’s success isn’t measured by their own output; it’s measured by the output of their team.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;The Evolution:&lt;/strong&gt; I moved from being the “Review Police” to becoming a &lt;strong&gt;Force Multiplier&lt;/strong&gt;. Instead of rewriting code to match my personal preferences, I focused on creating Architecture Decision Records (ADRs) and clear system diagrams. I focused on giving the team the context they needed to make high-quality decisions autonomously.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The Result:&lt;/strong&gt; The team’s velocity increased because I was no longer a bottleneck. My influence scaled not because I was doing more, but because I was enabling others to do their best work.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  The Takeaway
&lt;/h3&gt;

&lt;p&gt;The transition from Senior Engineer to Technical Architect isn’t just a change in title; it’s an evolution of perspective.&lt;/p&gt;

&lt;p&gt;When you focus on &lt;strong&gt;proving&lt;/strong&gt; , you are being reactive — you are justifying your place. When you focus on &lt;strong&gt;positioning&lt;/strong&gt; , you are being proactive — you are placing yourself at the intersection of technology and business value.&lt;/p&gt;

&lt;p&gt;I didn’t get the Architect title because I wrote the most code that year. I got it because I stopped acting like a Senior Developer on steroids and started acting like a leader who happens to know how to code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Stop trying to win the argument. Start trying to win the outcome.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;“Have you ever felt the ‘proving’ trap in your own career? How did you break out of it?”&lt;/p&gt;

</description>
      <category>leadershipdevelopmen</category>
      <category>leadership</category>
      <category>techstrategy</category>
      <category>vikashgyan</category>
    </item>
    <item>
      <title>React 101: Quick Start Guide</title>
      <dc:creator>Vikash Kumar</dc:creator>
      <pubDate>Tue, 20 Jan 2026 17:07:53 +0000</pubDate>
      <link>https://forem.com/ervikash/react-101-quick-start-guide-1b73</link>
      <guid>https://forem.com/ervikash/react-101-quick-start-guide-1b73</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzt82pvpxwg41byew6diz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzt82pvpxwg41byew6diz.png" width="800" height="422"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  What is React?
&lt;/h3&gt;

&lt;p&gt;React is a JavaScript library for building user interfaces, developed by Facebook. It allows you to create reusable UI components and efficiently update the DOM when data changes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Features:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Component-Based&lt;/strong&gt; : Build encapsulated components that manage their own state&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Declarative&lt;/strong&gt; : Design simple views for each state, React efficiently updates and renders components&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Learn Once, Write Anywhere&lt;/strong&gt; : Create web apps, mobile apps (React Native), and more&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Setup &amp;amp; Installation
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Create a new React app
npx create-react-app my-app

# Navigate to the project
cd my-app
# Start development server
npm start
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Project Structure:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my-app/
├── node_modules/
├── public/
│ └── index.html
├── src/
│ ├── App.js # Main component
│ ├── App.css # Styles
│ ├── index.js # Entry point
│ └── index.css
└── package.json
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  JSX Syntax
&lt;/h3&gt;

&lt;p&gt;JSX (JavaScript XML) allows you to write HTML-like code in JavaScript.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// JSX Example
const element = &amp;lt;h1&amp;gt;Hello, World!&amp;lt;/h1&amp;gt;;

---

// JSX with expressions
const name = "John";
const greeting = &amp;lt;h1&amp;gt;Hello, {name}!&amp;lt;/h1&amp;gt;;
// JSX with attributes
const image = &amp;lt;img src="photo.jpg" alt="Profile" /&amp;gt;;
// JSX with multiple elements (must have one parent)
const card = (
  &amp;lt;div className="card"&amp;gt;
    &amp;lt;h2&amp;gt;Title&amp;lt;/h2&amp;gt;
    &amp;lt;p&amp;gt;Description&amp;lt;/p&amp;gt;
  &amp;lt;/div&amp;gt;
);
// JSX Rules:
// - Use className instead of class
// - Use camelCase for attributes (onClick, onChange)
// - Close all tags (&amp;lt;img /&amp;gt;, &amp;lt;input /&amp;gt;)
// - Use {} for JavaScript expressions
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Components
&lt;/h3&gt;

&lt;p&gt;Components are the building blocks of React applications. They come in two types: &lt;strong&gt;Functional&lt;/strong&gt; and &lt;strong&gt;Class&lt;/strong&gt; components (modern React favors functional components).&lt;/p&gt;

&lt;h4&gt;
  
  
  Functional Component
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Simple functional component
function Welcome() {
  return &amp;lt;h1&amp;gt;Welcome to React!&amp;lt;/h1&amp;gt;;
}

// Arrow function component
const Greeting = () =&amp;gt; {
  return &amp;lt;h1&amp;gt;Hello!&amp;lt;/h1&amp;gt;;
};
// Component with JavaScript logic
function UserCard() {
  const user = {
    name: "Alice",
    age: 25
  };
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h2&amp;gt;{user.name}&amp;lt;/h2&amp;gt;
      &amp;lt;p&amp;gt;Age: {user.age}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Class Component (Legacy)
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component } from 'react';

class Welcome extends Component {
  render() {
    return &amp;lt;h1&amp;gt;Welcome to React!&amp;lt;/h1&amp;gt;;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Props
&lt;/h3&gt;

&lt;p&gt;Props (properties) allow you to pass data from parent to child components. They are &lt;strong&gt;read-only&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Parent component passing props
function App() {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;Greeting name="Alice" age={25} /&amp;gt;
      &amp;lt;Greeting name="Bob" age={30} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

// Child component receiving props
function Greeting(props) {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h2&amp;gt;Hello, {props.name}!&amp;lt;/h2&amp;gt;
      &amp;lt;p&amp;gt;Age: {props.age}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
// Using destructuring (cleaner)
function Greeting({ name, age }) {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h2&amp;gt;Hello, {name}!&amp;lt;/h2&amp;gt;
      &amp;lt;p&amp;gt;Age: {age}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
// Default props
function Greeting({ name = "Guest", age = 0 }) {
  return &amp;lt;h2&amp;gt;Hello, {name}! Age: {age}&amp;lt;/h2&amp;gt;;
}
// Props children
function Card({ children }) {
  return &amp;lt;div className="card"&amp;gt;{children}&amp;lt;/div&amp;gt;;
}
// Usage
&amp;lt;Card&amp;gt;
  &amp;lt;h2&amp;gt;Title&amp;lt;/h2&amp;gt;
  &amp;lt;p&amp;gt;Content here&amp;lt;/p&amp;gt;
&amp;lt;/Card&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  State
&lt;/h3&gt;

&lt;p&gt;State is data that changes over time within a component. Use the useState hook to manage state in functional components.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState } from 'react';

function Counter() {
  // Declare state variable
  const [count, setCount] = useState(0);
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;Count: {count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; setCount(count + 1)}&amp;gt;Increment&amp;lt;/button&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; setCount(count - 1)}&amp;gt;Decrement&amp;lt;/button&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; setCount(0)}&amp;gt;Reset&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
// Multiple state variables
function UserForm() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [age, setAge] = useState(0);
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;input 
        value={name} 
        onChange={(e) =&amp;gt; setName(e.target.value)} 
        placeholder="Name"
      /&amp;gt;
      &amp;lt;input 
        value={email} 
        onChange={(e) =&amp;gt; setEmail(e.target.value)} 
        placeholder="Email"
      /&amp;gt;
      &amp;lt;input 
        type="number"
        value={age} 
        onChange={(e) =&amp;gt; setAge(e.target.value)} 
        placeholder="Age"
      /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
// State with objects
function UserProfile() {
  const [user, setUser] = useState({
    name: 'Alice',
    age: 25,
    email: 'alice@example.com'
  });
  const updateName = (newName) =&amp;gt; {
    setUser({ ...user, name: newName }); // Spread operator to maintain other properties
  };
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h2&amp;gt;{user.name}&amp;lt;/h2&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; updateName('Bob')}&amp;gt;Change Name&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Event Handling
&lt;/h3&gt;

&lt;p&gt;React events are named using camelCase and pass functions as handlers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function EventExamples() {
  // Click event
  const handleClick = () =&amp;gt; {
    alert('Button clicked!');
  };

 // Event with parameter
  const greet = (name) =&amp;gt; {
    alert(`Hello, ${name}!`);
  };
  // Form submission
  const handleSubmit = (e) =&amp;gt; {
    e.preventDefault(); // Prevent page reload
    console.log('Form submitted');
  };
  // Input change
  const handleChange = (e) =&amp;gt; {
    console.log('Input value:', e.target.value);
  };
  // Mouse events
  const handleMouseEnter = () =&amp;gt; {
    console.log('Mouse entered!');
  };
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;button onClick={handleClick}&amp;gt;Click Me&amp;lt;/button&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; greet('Alice')}&amp;gt;Greet Alice&amp;lt;/button&amp;gt;

      &amp;lt;form onSubmit={handleSubmit}&amp;gt;
        &amp;lt;input onChange={handleChange} /&amp;gt;
        &amp;lt;button type="submit"&amp;gt;Submit&amp;lt;/button&amp;gt;
      &amp;lt;/form&amp;gt;
      &amp;lt;div 
        onMouseEnter={handleMouseEnter}
        onMouseLeave={() =&amp;gt; console.log('Mouse left!')}
      &amp;gt;
        Hover over me
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
// Common Events:
// onClick, onChange, onSubmit, onFocus, onBlur
// onMouseEnter, onMouseLeave, onKeyDown, onKeyUp
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Conditional Rendering
&lt;/h3&gt;

&lt;p&gt;Render components based on conditions using JavaScript operators.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function LoginStatus({ isLoggedIn }) {
  // Using if-else
  if (isLoggedIn) {
    return &amp;lt;h1&amp;gt;Welcome back!&amp;lt;/h1&amp;gt;;
  } else {
    return &amp;lt;h1&amp;gt;Please sign in&amp;lt;/h1&amp;gt;;
  }
}

// Using ternary operator
function Greeting({ isLoggedIn }) {
  return (
    &amp;lt;div&amp;gt;
      {isLoggedIn ? &amp;lt;h1&amp;gt;Welcome!&amp;lt;/h1&amp;gt; : &amp;lt;h1&amp;gt;Please log in&amp;lt;/h1&amp;gt;}
    &amp;lt;/div&amp;gt;
  );
}
// Using &amp;amp;&amp;amp; operator (for single condition)
function Notification({ hasMessages }) {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;Dashboard&amp;lt;/h1&amp;gt;
      {hasMessages &amp;amp;&amp;amp; &amp;lt;p&amp;gt;You have new messages!&amp;lt;/p&amp;gt;}
    &amp;lt;/div&amp;gt;
  );
}
// Conditional rendering with multiple conditions
function UserPanel({ user, isAdmin }) {
  return (
    &amp;lt;div&amp;gt;
      {user ? (
        &amp;lt;div&amp;gt;
          &amp;lt;h2&amp;gt;{user.name}&amp;lt;/h2&amp;gt;
          {isAdmin &amp;amp;&amp;amp; &amp;lt;button&amp;gt;Admin Panel&amp;lt;/button&amp;gt;}
        &amp;lt;/div&amp;gt;
      ) : (
        &amp;lt;button&amp;gt;Login&amp;lt;/button&amp;gt;
      )}
    &amp;lt;/div&amp;gt;
  );
}
// Switch-case alternative
function StatusMessage({ status }) {
  const getMessage = () =&amp;gt; {
    switch(status) {
      case 'loading': return 'Loading...';
      case 'success': return 'Success!';
      case 'error': return 'Error occurred';
      default: return 'Unknown status';
    }
  };
  return &amp;lt;p&amp;gt;{getMessage()}&amp;lt;/p&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Lists &amp;amp; Keys
&lt;/h3&gt;

&lt;p&gt;Render arrays of data using map() and assign unique keys to list items.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function TodoList() {
  const todos = [
    { id: 1, text: 'Learn React', completed: false },
    { id: 2, text: 'Build a project', completed: false },
    { id: 3, text: 'Deploy app', completed: true }
  ];

return (
    &amp;lt;ul&amp;gt;
      {todos.map((todo) =&amp;gt; (
        &amp;lt;li key={todo.id}&amp;gt;
          {todo.text} {todo.completed &amp;amp;&amp;amp; '✓'}
        &amp;lt;/li&amp;gt;
      ))}
    &amp;lt;/ul&amp;gt;
  );
}
// Keys help React identify which items have changed
// Use unique IDs, not array indexes (when possible)
// More complex example
function UserList() {
  const users = [
    { id: 1, name: 'Alice', role: 'Admin' },
    { id: 2, name: 'Bob', role: 'User' },
    { id: 3, name: 'Charlie', role: 'User' }
  ];
  return (
    &amp;lt;div&amp;gt;
      {users.map((user) =&amp;gt; (
        &amp;lt;div key={user.id} className="user-card"&amp;gt;
          &amp;lt;h3&amp;gt;{user.name}&amp;lt;/h3&amp;gt;
          &amp;lt;span&amp;gt;{user.role}&amp;lt;/span&amp;gt;
        &amp;lt;/div&amp;gt;
      ))}
    &amp;lt;/div&amp;gt;
  );
}
// Filtering lists
function ProductList() {
  const products = [
    { id: 1, name: 'Laptop', price: 999, inStock: true },
    { id: 2, name: 'Phone', price: 699, inStock: false },
    { id: 3, name: 'Tablet', price: 499, inStock: true }
  ];
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h2&amp;gt;Available Products&amp;lt;/h2&amp;gt;
      {products
        .filter(product =&amp;gt; product.inStock)
        .map(product =&amp;gt; (
          &amp;lt;div key={product.id}&amp;gt;
            &amp;lt;h3&amp;gt;{product.name}&amp;lt;/h3&amp;gt;
            &amp;lt;p&amp;gt;${product.price}&amp;lt;/p&amp;gt;
          &amp;lt;/div&amp;gt;
        ))}
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Hooks Overview
&lt;/h3&gt;

&lt;p&gt;Hooks let you use state and other React features in functional components.&lt;/p&gt;

&lt;h4&gt;
  
  
  Common Hooks:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;useState&lt;/strong&gt; : Manage state&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;useEffect&lt;/strong&gt; : Side effects (API calls, subscriptions)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;useContext&lt;/strong&gt; : Access context values&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;useRef&lt;/strong&gt; : Access DOM elements or persist values&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;useMemo&lt;/strong&gt; : Memoize expensive calculations&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;useCallback&lt;/strong&gt; : Memoize functions
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState, useEffect, useRef, useMemo } from 'react';

// useState - covered in State section
const [count, setCount] = useState(0);
// useRef - Access DOM elements
function TextInput() {
  const inputRef = useRef(null);
  const focusInput = () =&amp;gt; {
    inputRef.current.focus();
  };
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;input ref={inputRef} /&amp;gt;
      &amp;lt;button onClick={focusInput}&amp;gt;Focus Input&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
// useMemo - Optimize performance
function ExpensiveComponent({ numbers }) {
  const sum = useMemo(() =&amp;gt; {
    console.log('Calculating sum...');
    return numbers.reduce((a, b) =&amp;gt; a + b, 0);
  }, [numbers]); // Only recalculate when numbers change
  return &amp;lt;div&amp;gt;Sum: {sum}&amp;lt;/div&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  useEffect Hook
&lt;/h4&gt;

&lt;p&gt;useEffect handles side effects like data fetching, subscriptions, and DOM manipulation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState, useEffect } from 'react';

// Run on every render
function Example1() {
  useEffect(() =&amp;gt; {
    console.log('Component rendered');
  });
}
// Run once on mount (empty dependency array)
function Example2() {
  useEffect(() =&amp;gt; {
    console.log('Component mounted');
  }, []);
}
// Run when specific values change
function Example3() {
  const [count, setCount] = useState(0);
  useEffect(() =&amp;gt; {
    console.log('Count changed:', count);
  }, [count]); // Only runs when count changes
}
// Cleanup function
function Example4() {
  useEffect(() =&amp;gt; {
    const timer = setInterval(() =&amp;gt; {
      console.log('Tick');
    }, 1000);
    // Cleanup when component unmounts
    return () =&amp;gt; {
      clearInterval(timer);
    };
  }, []);
}
// Practical example: Fetch data from API
function UserProfile({ userId }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  useEffect(() =&amp;gt; {
    setLoading(true);

    fetch(`https://api.example.com/users/${userId}`)
      .then(response =&amp;gt; response.json())
      .then(data =&amp;gt; {
        setUser(data);
        setLoading(false);
      })
      .catch(err =&amp;gt; {
        setError(err.message);
        setLoading(false);
      });
  }, [userId]); // Re-fetch when userId changes
  if (loading) return &amp;lt;div&amp;gt;Loading...&amp;lt;/div&amp;gt;;
  if (error) return &amp;lt;div&amp;gt;Error: {error}&amp;lt;/div&amp;gt;;
  if (!user) return &amp;lt;div&amp;gt;No user found&amp;lt;/div&amp;gt;;
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h2&amp;gt;{user.name}&amp;lt;/h2&amp;gt;
      &amp;lt;p&amp;gt;{user.email}&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
// Document title update
function PageTitle() {
  const [count, setCount] = useState(0);
  useEffect(() =&amp;gt; {
    document.title = `Count: ${count}`;
  }, [count]);
  return (
    &amp;lt;button onClick={() =&amp;gt; setCount(count + 1)}&amp;gt;
      Clicked {count} times
    &amp;lt;/button&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Forms &amp;amp; Controlled Components
&lt;/h3&gt;

&lt;p&gt;In React, form elements are controlled by component state.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState } from 'react';

// Simple form
function LoginForm() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const handleSubmit = (e) =&amp;gt; {
    e.preventDefault();
    console.log('Login:', { username, password });
    // API call here
  };
  return (
    &amp;lt;form onSubmit={handleSubmit}&amp;gt;
      &amp;lt;input
        type="text"
        value={username}
        onChange={(e) =&amp;gt; setUsername(e.target.value)}
        placeholder="Username"
      /&amp;gt;
      &amp;lt;input
        type="password"
        value={password}
        onChange={(e) =&amp;gt; setPassword(e.target.value)}
        placeholder="Password"
      /&amp;gt;
      &amp;lt;button type="submit"&amp;gt;Login&amp;lt;/button&amp;gt;
    &amp;lt;/form&amp;gt;
  );
}
// Complex form with validation
function RegistrationForm() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    age: '',
    country: 'USA',
    subscribe: false
  });
  const [errors, setErrors] = useState({});
  const handleChange = (e) =&amp;gt; {
    const { name, value, type, checked } = e.target;
    setFormData({
      ...formData,
      [name]: type === 'checkbox' ? checked : value
    });
  };
  const validate = () =&amp;gt; {
    const newErrors = {};

    if (!formData.name) newErrors.name = 'Name is required';
    if (!formData.email) newErrors.email = 'Email is required';
    if (formData.age &amp;lt; 18) newErrors.age = 'Must be 18 or older';

    return newErrors;
  };
  const handleSubmit = (e) =&amp;gt; {
    e.preventDefault();
    const newErrors = validate();

    if (Object.keys(newErrors).length === 0) {
      console.log('Form submitted:', formData);
      // Submit to API
    } else {
      setErrors(newErrors);
    }
  };
  return (
    &amp;lt;form onSubmit={handleSubmit}&amp;gt;
      &amp;lt;div&amp;gt;
        &amp;lt;input
          name="name"
          value={formData.name}
          onChange={handleChange}
          placeholder="Name"
        /&amp;gt;
        {errors.name &amp;amp;&amp;amp; &amp;lt;span className="error"&amp;gt;{errors.name}&amp;lt;/span&amp;gt;}
      &amp;lt;/div&amp;gt;
      &amp;lt;div&amp;gt;
        &amp;lt;input
          name="email"
          type="email"
          value={formData.email}
          onChange={handleChange}
          placeholder="Email"
        /&amp;gt;
        {errors.email &amp;amp;&amp;amp; &amp;lt;span className="error"&amp;gt;{errors.email}&amp;lt;/span&amp;gt;}
      &amp;lt;/div&amp;gt;
      &amp;lt;div&amp;gt;
        &amp;lt;input
          name="age"
          type="number"
          value={formData.age}
          onChange={handleChange}
          placeholder="Age"
        /&amp;gt;
        {errors.age &amp;amp;&amp;amp; &amp;lt;span className="error"&amp;gt;{errors.age}&amp;lt;/span&amp;gt;}
      &amp;lt;/div&amp;gt;
      &amp;lt;div&amp;gt;
        &amp;lt;select name="country" value={formData.country} onChange={handleChange}&amp;gt;
          &amp;lt;option value="USA"&amp;gt;USA&amp;lt;/option&amp;gt;
          &amp;lt;option value="UK"&amp;gt;UK&amp;lt;/option&amp;gt;
          &amp;lt;option value="Canada"&amp;gt;Canada&amp;lt;/option&amp;gt;
        &amp;lt;/select&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;div&amp;gt;
        &amp;lt;label&amp;gt;
          &amp;lt;input
            name="subscribe"
            type="checkbox"
            checked={formData.subscribe}
            onChange={handleChange}
          /&amp;gt;
          Subscribe to newsletter
        &amp;lt;/label&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;button type="submit"&amp;gt;Register&amp;lt;/button&amp;gt;
    &amp;lt;/form&amp;gt;
  );
}
// Textarea example
function CommentForm() {
  const [comment, setComment] = useState('');
  return (
    &amp;lt;form&amp;gt;
      &amp;lt;textarea
        value={comment}
        onChange={(e) =&amp;gt; setComment(e.target.value)}
        placeholder="Write a comment..."
        rows="4"
      /&amp;gt;
      &amp;lt;p&amp;gt;Character count: {comment.length}&amp;lt;/p&amp;gt;
    &amp;lt;/form&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Component Lifecycle
&lt;/h3&gt;

&lt;p&gt;Understanding when components mount, update, and unmount.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState, useEffect } from 'react';

function LifecycleDemo() {
  const [count, setCount] = useState(0);
  // 1. Component Mounts (runs once)
  useEffect(() =&amp;gt; {
    console.log('Component mounted');

    // Cleanup when component unmounts
    return () =&amp;gt; {
      console.log('Component will unmount');
    };
  }, []);
  // 2. Component Updates (runs when count changes)
  useEffect(() =&amp;gt; {
    console.log('Count updated:', count);
  }, [count]);
  // 3. Every render
  useEffect(() =&amp;gt; {
    console.log('Component rendered');
  });
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;Count: {count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; setCount(count + 1)}&amp;gt;Increment&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
// Lifecycle phases:
// 1. Mounting: Component is created and inserted into the DOM
// 2. Updating: Component re-renders due to state/props changes
// 3. Unmounting: Component is removed from the DOM
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Quick Reference
&lt;/h3&gt;

&lt;h3&gt;
  
  
  Component Structure
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState, useEffect } from 'react';

function MyComponent({ prop1, prop2 }) {
  // 1. Hooks (at the top)
  const [state, setState] = useState(initialValue);

  useEffect(() =&amp;gt; {
    // Side effects
  }, [dependencies]);
  // 2. Event handlers
  const handleClick = () =&amp;gt; {
    // Handle event
  };
  // 3. Helper functions
  const calculateSomething = () =&amp;gt; {
    // Logic
  };
  // 4. Return JSX
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;{prop1}&amp;lt;/h1&amp;gt;
      &amp;lt;button onClick={handleClick}&amp;gt;Click&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
export default MyComponent;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Common Patterns
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;1. Toggle State&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [isOpen, setIsOpen] = useState(false);
const toggle = () =&amp;gt; setIsOpen(!isOpen);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Update Object State&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [user, setUser] = useState({ name: '', age: 0 });
setUser({ ...user, name: 'Alice' });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Update Array State&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [items, setItems] = useState([]);
setItems([...items, newItem]); // Add
setItems(items.filter(item =&amp;gt; item.id !== id)); // Remove
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. Conditional Class&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div className={isActive ? 'active' : 'inactive'}&amp;gt;Content&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;5. Inline Styles&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div style={{ color: 'red', fontSize: '20px' }}&amp;gt;Text&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Best Practices
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Component Names&lt;/strong&gt; : Use PascalCase (MyComponent)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Props Naming&lt;/strong&gt; : Use camelCase (onClick, userName)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;State Updates&lt;/strong&gt; : Never mutate state directly, use setter functions&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Keys in Lists&lt;/strong&gt; : Use unique IDs, not array indexes (when possible)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Event Handlers&lt;/strong&gt; : Use arrow functions or bind methods&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Component Size&lt;/strong&gt; : Keep components small and focused&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;File Organization&lt;/strong&gt; : One component per file&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Prop Types&lt;/strong&gt; : Use TypeScript or PropTypes for type checking&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Useful Snippets
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Loading State&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Modal Toggle&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [showModal, setShowModal] = useState(false);
const openModal = () =&amp;gt; setShowModal(true);
const closeModal = () =&amp;gt; setShowModal(false);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Form Input Handler&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const handleChange = (e) =&amp;gt; {
  const { name, value } = e.target;
  setFormData({ ...formData, [name]: value });
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Complete Mini-App Example
&lt;/h3&gt;

&lt;p&gt;Here’s a complete todo app demonstrating multiple concepts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState } from 'react';

function TodoApp() {
  const [todos, setTodos] = useState([]);
  const [input, setInput] = useState('');
  const [filter, setFilter] = useState('all'); // all, active, completed
  // Add todo
  const addTodo = (e) =&amp;gt; {
    e.preventDefault();
    if (input.trim()) {
      setTodos([
        ...todos,
        { id: Date.now(), text: input, completed: false }
      ]);
      setInput('');
    }
  };
  // Toggle todo completion
  const toggleTodo = (id) =&amp;gt; {
    setTodos(
      todos.map(todo =&amp;gt;
        todo.id === id ? { ...todo, completed: !todo.completed } : todo
      )
    );
  };
  // Delete todo
  const deleteTodo = (id) =&amp;gt; {
    setTodos(todos.filter(todo =&amp;gt; todo.id !== id));
  };
  // Filter todos
  const getFilteredTodos = () =&amp;gt; {
    switch(filter) {
      case 'active':
        return todos.filter(todo =&amp;gt; !todo.completed);
      case 'completed':
        return todos.filter(todo =&amp;gt; todo.completed);
      default:
        return todos;
    }
  };
  const filteredTodos = getFilteredTodos();
  const activeCount = todos.filter(t =&amp;gt; !t.completed).length;
  return (
    &amp;lt;div className="todo-app"&amp;gt;
      &amp;lt;h1&amp;gt;Todo List&amp;lt;/h1&amp;gt;
      {/* Add Todo Form */}
      &amp;lt;form onSubmit={addTodo}&amp;gt;
        &amp;lt;input
          type="text"
          value={input}
          onChange={(e) =&amp;gt; setInput(e.target.value)}
          placeholder="What needs to be done?"
        /&amp;gt;
        &amp;lt;button type="submit"&amp;gt;Add&amp;lt;/button&amp;gt;
      &amp;lt;/form&amp;gt;
      {/* Filter Buttons */}
      &amp;lt;div className="filters"&amp;gt;
        &amp;lt;button 
          onClick={() =&amp;gt; setFilter('all')}
          className={filter === 'all' ? 'active' : ''}
        &amp;gt;
          All
        &amp;lt;/button&amp;gt;
        &amp;lt;button 
          onClick={() =&amp;gt; setFilter('active')}
          className={filter === 'active' ? 'active' : ''}
        &amp;gt;
          Active
        &amp;lt;/button&amp;gt;
        &amp;lt;button 
          onClick={() =&amp;gt; setFilter('completed')}
          className={filter === 'completed' ? 'active' : ''}
        &amp;gt;
          Completed
        &amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
      {/* Todo List */}
      &amp;lt;ul className="todo-list"&amp;gt;
        {filteredTodos.length === 0 ? (
          &amp;lt;li className="empty"&amp;gt;No todos to display&amp;lt;/li&amp;gt;
        ) : (
          filteredTodos.map(todo =&amp;gt; (
            &amp;lt;li key={todo.id} className={todo.completed ? 'completed' : ''}&amp;gt;
              &amp;lt;input
                type="checkbox"
                checked={todo.completed}
                onChange={() =&amp;gt; toggleTodo(todo.id)}
              /&amp;gt;
              &amp;lt;span&amp;gt;{todo.text}&amp;lt;/span&amp;gt;
              &amp;lt;button onClick={() =&amp;gt; deleteTodo(todo.id)}&amp;gt;Delete&amp;lt;/button&amp;gt;
            &amp;lt;/li&amp;gt;
          ))
        )}
      &amp;lt;/ul&amp;gt;
      {/* Footer */}
      &amp;lt;div className="footer"&amp;gt;
        &amp;lt;span&amp;gt;{activeCount} items left&amp;lt;/span&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
export default TodoApp;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Next Steps
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;After mastering these basics:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;React Router&lt;/strong&gt;  — Navigation and routing&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Context API&lt;/strong&gt;  — Global state management&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Redux/Zustand&lt;/strong&gt;  — Advanced state management&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Custom Hooks&lt;/strong&gt;  — Reusable logic&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Performance Optimization&lt;/strong&gt;  — memo, useMemo, useCallback&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;TypeScript&lt;/strong&gt;  — Type safety&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Testing&lt;/strong&gt;  — Jest and React Testing Library&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;API Integration&lt;/strong&gt;  — Axios, Fetch API, React Query&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Styling&lt;/strong&gt;  — CSS Modules, Styled Components, Tailwind&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Build Tools&lt;/strong&gt;  — Vite, Webpack&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Resources:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://react.dev" rel="noopener noreferrer"&gt;Official React Docs&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://beta.reactjs.org" rel="noopener noreferrer"&gt;React Beta Docs&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://reactpatterns.com" rel="noopener noreferrer"&gt;React Patterns&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Happy Coding! 🚀&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Last Updated: January 17, 2026&lt;/em&gt;&lt;/p&gt;

</description>
      <category>vikashgyan</category>
      <category>reactbootstrap</category>
      <category>react101</category>
      <category>basics</category>
    </item>
    <item>
      <title>React + Redux Toolkit QuickStart Guide</title>
      <dc:creator>Vikash Kumar</dc:creator>
      <pubDate>Wed, 31 Dec 2025 03:31:09 +0000</pubDate>
      <link>https://forem.com/ervikash/react-redux-toolkit-quickstart-guide-2pi7</link>
      <guid>https://forem.com/ervikash/react-redux-toolkit-quickstart-guide-2pi7</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8ok6banolvmygb698r25.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8ok6banolvmygb698r25.png" width="760" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This guide gives you a concise Redux overview, a fresh React app setup, and practical examples of using Redux Toolkit in React — including installation steps.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why Redux (and why Redux Toolkit)
&lt;/h3&gt;

&lt;p&gt;Redux is a predictable state container for Typescript/JavaScript apps. It centralizes shared state in a single store and uses pure reducers to handle updates.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Core pieces&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Store: the single source of truth for app state&lt;/li&gt;
&lt;li&gt;Actions: plain objects describing “what happened”&lt;/li&gt;
&lt;li&gt;Reducers: pure functions that update state based on actions&lt;/li&gt;
&lt;li&gt;Dispatch: sends actions to the store&lt;/li&gt;
&lt;li&gt;Selectors: read from the store (often memoized)&lt;/li&gt;
&lt;li&gt;Middleware: intercept actions for side effects (logging, async, etc.)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Redux Toolkit (RTK) is the official, recommended way to write Redux logic:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;APIs included: configureStore, createSlice, createAsyncThunk&lt;/li&gt;
&lt;li&gt;Eliminates boilerplate and enforces good defaults&lt;/li&gt;
&lt;li&gt;Uses Immer under the hood for safe immutable updates with mutable-looking code&lt;/li&gt;
&lt;li&gt;Built-in dev tools compatibility&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;When to use Redux:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You have shared state across many components (auth, user prefs, cached lists)&lt;/li&gt;
&lt;li&gt;You need predictable state transitions and time-travel debugging&lt;/li&gt;
&lt;li&gt;You want a single place for async data fetching/caching and error handling&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If your app is small or state is mostly local, React state or Context might be enough. For server data, consider RTK Query (Redux Toolkit’s data fetching solution).&lt;/p&gt;

&lt;h3&gt;
  
  
  Set up a sample React application
&lt;/h3&gt;

&lt;p&gt;Prerequisites&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Node.js 18+ (recommended)&lt;/li&gt;
&lt;li&gt;npm 9+ (or yarn/pnpm)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Create a new project with Vite
&lt;/h3&gt;

&lt;p&gt;TypeScript (recommended):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm create vite@latest my-redux-app -- --template react-ts
cd my-redux-app
npm install
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;JavaScript:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm create vite@latest my-redux-app -- --template react
cd my-redux-app
npm install
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Install Redux Toolkit and React Redux:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install @reduxjs/toolkit react-redux
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Start the dev server:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm run dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Open the URL printed in the terminal (typically &lt;a href="http://localhost:5173" rel="noopener noreferrer"&gt;http://localhost:5173).&lt;/a&gt;.)&lt;/p&gt;

&lt;h3&gt;
  
  
  Using Redux Toolkit in React
&lt;/h3&gt;

&lt;p&gt;Below are minimal, production-ready patterns using Redux Toolkit.&lt;/p&gt;

&lt;h3&gt;
  
  
  1) Create a slice (src/features/counter/counterSlice.ts or .js)
&lt;/h3&gt;

&lt;p&gt;TypeScript version:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit';

// Example async thunk
export const fetchInitial = createAsyncThunk&amp;lt;number&amp;gt;(
  'counter/fetchInitial',
  async () =&amp;gt; {
    // Mock API call; replace with real endpoint
    await new Promise((r) =&amp;gt; setTimeout(r, 300));
    return 5;
  }
);
export interface CounterState {
  value: number;
  status: 'idle' | 'loading' | 'succeeded' | 'failed';
  error?: string;
}
const initialState: CounterState = {
  value: 0,
  status: 'idle',
};
const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment(state) {
      state.value += 1; // safe with Immer
    },
    decrement(state) {
      state.value -= 1;
    },
    addByAmount(state, action: PayloadAction&amp;lt;number&amp;gt;) {
      state.value += action.payload;
    },
    reset(state) {
      state.value = 0;
    },
  },
  extraReducers: (builder) =&amp;gt; {
    builder
      .addCase(fetchInitial.pending, (state) =&amp;gt; {
        state.status = 'loading';
        state.error = undefined;
      })
      .addCase(fetchInitial.fulfilled, (state, action) =&amp;gt; {
        state.status = 'succeeded';
        state.value = action.payload;
      })
      .addCase(fetchInitial.rejected, (state, action) =&amp;gt; {
        state.status = 'failed';
        state.error = action.error.message;
      });
  },
});
export const { increment, decrement, addByAmount, reset } = counterSlice.actions;
export default counterSlice.reducer;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;JavaScript version:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

export const fetchInitial = createAsyncThunk('counter/fetchInitial', async () =&amp;gt; {
  await new Promise((r) =&amp;gt; setTimeout(r, 300));
  return 5;
});
const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0, status: 'idle' },
  reducers: {
    increment: (state) =&amp;gt; { state.value += 1; },
    decrement: (state) =&amp;gt; { state.value -= 1; },
    addByAmount: (state, action) =&amp;gt; { state.value += action.payload; },
    reset: (state) =&amp;gt; { state.value = 0; },
  },
  extraReducers: (builder) =&amp;gt; {
    builder
      .addCase(fetchInitial.pending, (state) =&amp;gt; { state.status = 'loading'; })
      .addCase(fetchInitial.fulfilled, (state, action) =&amp;gt; {
        state.status = 'succeeded';
        state.value = action.payload;
      })
      .addCase(fetchInitial.rejected, (state, action) =&amp;gt; {
        state.status = 'failed';
      });
  },
});
export const { increment, decrement, addByAmount, reset } = counterSlice.actions;
export default counterSlice.reducer;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2) Configure the store (src/store.ts or .js)
&lt;/h3&gt;

&lt;p&gt;TypeScript:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './features/counter/counterSlice';

export const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
});
// Infer types
export type RootState = ReturnType&amp;lt;typeof store.getState&amp;gt;;
export type AppDispatch = typeof store.dispatch;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;JavaScript:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './features/counter/counterSlice';

export const store = configureStore({
  reducer: { counter: counterReducer },
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3) Typed hooks (optional but recommended for TS)
&lt;/h3&gt;

&lt;p&gt;src/hooks.ts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from './store';

export const useAppDispatch: () =&amp;gt; AppDispatch = useDispatch;
export const useAppSelector: TypedUseSelectorHook&amp;lt;RootState&amp;gt; = useSelector;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4) Wrap your app with the Provider (src/main.tsx)
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import { store } from './store';
import App from './App';

ReactDOM.createRoot(document.getElementById('root')!).render(
  &amp;lt;React.StrictMode&amp;gt;
    &amp;lt;Provider store={store}&amp;gt;
      &amp;lt;App /&amp;gt;
    &amp;lt;/Provider&amp;gt;
  &amp;lt;/React.StrictMode&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;JavaScript (main.jsx) is similar.&lt;/p&gt;

&lt;h3&gt;
  
  
  5) Use Redux in a component (src/features/counter/Counter.tsx)
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useState } from 'react';
import { useAppDispatch, useAppSelector } from '../../hooks';
import { increment, decrement, addByAmount, reset, fetchInitial } from './counterSlice';

export default function Counter() {
  const value = useAppSelector((state) =&amp;gt; state.counter.value);
  const status = useAppSelector((state) =&amp;gt; state.counter.status);
  const dispatch = useAppDispatch();
  const [amount, setAmount] = useState('3');
  return (
    &amp;lt;div style={{ fontFamily: 'system-ui', lineHeight: 1.6 }}&amp;gt;
      &amp;lt;h2&amp;gt;Counter: {value}&amp;lt;/h2&amp;gt;
      &amp;lt;p&amp;gt;Status: {status}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; dispatch(increment())}&amp;gt;+1&amp;lt;/button&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; dispatch(decrement())} style={{ marginLeft: 8 }}&amp;gt;-1&amp;lt;/button&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; dispatch(reset())} style={{ marginLeft: 8 }}&amp;gt;Reset&amp;lt;/button&amp;gt;
      &amp;lt;div style={{ marginTop: 12 }}&amp;gt;
        &amp;lt;input
          value={amount}
          onChange={(e) =&amp;gt; setAmount(e.target.value)}
          style={{ width: 60 }}
        /&amp;gt;
        &amp;lt;button onClick={() =&amp;gt; dispatch(addByAmount(Number(amount) || 0))} style={{ marginLeft: 8 }}&amp;gt;
          Add by amount
        &amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;div style={{ marginTop: 12 }}&amp;gt;
        &amp;lt;button onClick={() =&amp;gt; dispatch(fetchInitial())}&amp;gt;Fetch initial&amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Add&lt;/strong&gt;  &lt;strong&gt; to **&lt;/strong&gt; App.tsx:**&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Counter from './features/counter/Counter';

export default function App() {
  return (
    &amp;lt;main style={{ padding: 24 }}&amp;gt;
      &amp;lt;h1&amp;gt;My Redux App&amp;lt;/h1&amp;gt;
      &amp;lt;Counter /&amp;gt;
    &amp;lt;/main&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Async example: fetching posts with createAsyncThunk
&lt;/h3&gt;

&lt;p&gt;src/features/posts/postsSlice.ts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

export const fetchPosts = createAsyncThunk('posts/fetch', async () =&amp;gt; {
  const res = await fetch('https://server.vikash.com/posts?_limit=5');
  if (!res.ok) throw new Error('Failed to fetch');
  return (await res.json()) as Array&amp;lt;{ id: number; title: string }&amp;gt;;
});
const postsSlice = createSlice({
  name: 'posts',
  initialState: { items: [], status: 'idle', error: undefined } as {
    items: Array&amp;lt;{ id: number; title: string }&amp;gt;;
    status: 'idle' | 'loading' | 'succeeded' | 'failed';
    error?: string;
  },
  reducers: {},
  extraReducers: (builder) =&amp;gt; {
    builder
      .addCase(fetchPosts.pending, (state) =&amp;gt; { state.status = 'loading'; state.error = undefined; })
      .addCase(fetchPosts.fulfilled, (state, action) =&amp;gt; { state.status = 'succeeded'; state.items = action.payload; })
      .addCase(fetchPosts.rejected, (state, action) =&amp;gt; { state.status = 'failed'; state.error = action.error.message; });
  },
});
export default postsSlice.reducer;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Add to store:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import postsReducer from './features/posts/postsSlice';

export const store = configureStore({
  reducer: {
    counter: counterReducer,
    posts: postsReducer,
  },
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Use in a component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useAppDispatch, useAppSelector } from '../../hooks';
import { fetchPosts } from './postsSlice';

export default function Posts() {
  const { items, status, error } = useAppSelector((s) =&amp;gt; s.posts);
  const dispatch = useAppDispatch();
  return (
    &amp;lt;section&amp;gt;
      &amp;lt;h2&amp;gt;Posts&amp;lt;/h2&amp;gt;
      &amp;lt;button disabled={status === 'loading'} onClick={() =&amp;gt; dispatch(fetchPosts())}&amp;gt;
        {status === 'loading' ? 'Loading...' : 'Load posts'}
      &amp;lt;/button&amp;gt;
      {error &amp;amp;&amp;amp; &amp;lt;p style={{ color: 'crimson' }}&amp;gt;{error}&amp;lt;/p&amp;gt;}
      &amp;lt;ul&amp;gt;
        {items.map((p) =&amp;gt; (
          &amp;lt;li key={p.id}&amp;gt;{p.title}&amp;lt;/li&amp;gt;
        ))}
      &amp;lt;/ul&amp;gt;
    &amp;lt;/section&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Testing a slice quickly (Vitest)
&lt;/h3&gt;

&lt;p&gt;With Vite, Vitest is easy to add:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install -D vitest @testing-library/react @testing-library/jest-dom
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Example test src/features/counter/counterSlice.test.ts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import reducer, { increment, decrement, addByAmount } from './counterSlice';

test('counter reducers', () =&amp;gt; {
  const s = { value: 0, status: 'idle' };
  expect(reducer(s, increment())).toMatchObject({ value: 1 });
  expect(reducer(s, decrement())).toMatchObject({ value: -1 });
  expect(reducer(s, addByAmount(10))).toMatchObject({ value: 10 });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run tests:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx vitest run
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Common pitfalls &amp;amp; troubleshooting
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;State appears unchanged: ensure you used reducers from createSlice and dispatched the correct action.&lt;/li&gt;
&lt;li&gt;useSelector returns undefined: verify the reducer key in configureStore matches usage (e.g., state.counter).&lt;/li&gt;
&lt;li&gt;Async thunk “pending” forever: check network errors and ensure you return a value from the thunk.&lt;/li&gt;
&lt;li&gt;DevTools not showing actions: confirm you’re using configureStore (it enables Redux DevTools by default in dev).&lt;/li&gt;
&lt;li&gt;TypeScript types not inferred: export RootState and AppDispatch, and use typed hooks.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Next steps
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;RTK Query for data fetching/caching with normalized state and auto hooks.&lt;/li&gt;
&lt;li&gt;Persisted state (redux-persist) for auth/session.&lt;/li&gt;
&lt;li&gt;Feature-based folder structure (src/features/*) to keep slices and components together.&lt;/li&gt;
&lt;li&gt;Advanced selectors with Reselect for derived state.&lt;/li&gt;
&lt;li&gt;Add ESLint + Prettier for consistent code quality.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Quick reference
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Install: npm i @reduxjs/toolkit react-redux&lt;/li&gt;
&lt;li&gt;Slice: createSlice({ name, initialState, reducers })&lt;/li&gt;
&lt;li&gt;Async: createAsyncThunk(type, asyncFn)&lt;/li&gt;
&lt;li&gt;Store: configureStore({ reducer })&lt;/li&gt;
&lt;li&gt;Provider: &lt;/li&gt;
&lt;li&gt;Hooks: useSelector, useDispatch (typed variants recommended)&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>basics</category>
      <category>redux</category>
      <category>reactredux</category>
      <category>vikashgyan</category>
    </item>
    <item>
      <title>Time and Space Complexity — Not so complex</title>
      <dc:creator>Vikash Kumar</dc:creator>
      <pubDate>Sun, 21 Dec 2025 18:39:15 +0000</pubDate>
      <link>https://forem.com/ervikash/time-and-space-complexity-not-so-complex-3998</link>
      <guid>https://forem.com/ervikash/time-and-space-complexity-not-so-complex-3998</guid>
      <description>&lt;h3&gt;
  
  
  Time and Space Complexity — Not so complex
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8ok6banolvmygb698r25.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8ok6banolvmygb698r25.png" width="760" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Overview
&lt;/h3&gt;

&lt;p&gt;Time and space complexity are measures used to analyze the efficiency of algorithms. They help us understand how an algorithm’s resource usage grows as the input size increases.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why Is This Important?
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Performance:&lt;/strong&gt; Efficient algorithms run faster and use less memory.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Scalability:&lt;/strong&gt; Good complexity ensures programs work well with large inputs.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Optimization:&lt;/strong&gt; Helps choose the best algorithm for a problem.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Predictability:&lt;/strong&gt; Allows estimation of resource needs before deployment.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Time Complexity
&lt;/h3&gt;

&lt;p&gt;Time complexity describes how the runtime of an algorithm increases with input size (n). It is commonly expressed using Big O notation.&lt;/p&gt;

&lt;h3&gt;
  
  
  Common Time Complexities
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;O(1):&lt;/strong&gt; Constant time (e.g., accessing an array element)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;O(log n):&lt;/strong&gt; Logarithmic time (e.g., binary search)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;O(n):&lt;/strong&gt; Linear time (e.g., traversing a list)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;O(n log n):&lt;/strong&gt; Linearithmic time (e.g., merge sort)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;O(n²):&lt;/strong&gt; Quadratic time (e.g., bubble sort)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;O(2^n):&lt;/strong&gt; Exponential time (e.g., recursive Fibonacci)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Example: Linear Search
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public boolean linearSearch(int[] arr, int target) {
    for (int i : arr) {
        if (i == target) {
            return true;
        }
    }
    return false;
}
// Time Complexity: O(n)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Example: Binary Search
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public boolean binarySearch(int[] arr, int target) {
    int left = 0, right = arr.length - 1;
    while (left &amp;lt;= right) {
        int mid = left + (right - left) / 2;
        if (arr[mid] == target) {
            return true;
        } else if (arr[mid] &amp;lt; target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return false;
}
// Time Complexity: O(log n)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Space Complexity
&lt;/h3&gt;

&lt;p&gt;Space complexity measures the amount of memory an algorithm uses as input size grows.&lt;/p&gt;

&lt;h3&gt;
  
  
  Common Space Complexities
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;O(1):&lt;/strong&gt; Constant space (e.g., variable assignment)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;O(n):&lt;/strong&gt; Linear space (e.g., storing an array)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;O(n²):&lt;/strong&gt; Quadratic space (e.g., 2D matrix)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Example: Storing Results
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public int[] storeResults(int[] arr) {
    int[] results = new int[arr.length];
    for (int i = 0; i &amp;lt; arr.length; i++) {
        results[i] = arr[i] * 2;
    }
    return results;
}
// Space Complexity: O(n)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Big O Notation Summary Table
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F286srwgfcqebbbdj68yy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F286srwgfcqebbbdj68yy.png" width="800" height="341"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Visual Guide
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8j4dsef0lzlg4evxcn22.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8j4dsef0lzlg4evxcn22.png" width="800" height="329"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;This table shows how different complexities grow as input size increases&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3bgp5yhr32zpm5otz14x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3bgp5yhr32zpm5otz14x.png" width="800" height="125"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;This flowchart visually compares how different Big O complexities grow as input size increases.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;Understanding time and space complexity helps you write efficient, scalable, and reliable code. Use Big O notation to compare algorithms and make informed decisions.&lt;/p&gt;

</description>
      <category>timeandspacecomplexi</category>
      <category>basics</category>
      <category>vikashgyan</category>
      <category>timecomplexity</category>
    </item>
    <item>
      <title>QPID — A simple story</title>
      <dc:creator>Vikash Kumar</dc:creator>
      <pubDate>Thu, 04 Dec 2025 19:50:16 +0000</pubDate>
      <link>https://forem.com/ervikash/qpid-a-simple-story-255h</link>
      <guid>https://forem.com/ervikash/qpid-a-simple-story-255h</guid>
      <description>&lt;h3&gt;
  
  
  QPID — A simple story
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi7hrucc3c1tmjr0p1yoo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi7hrucc3c1tmjr0p1yoo.png" width="760" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  What is QPID?
&lt;/h3&gt;

&lt;p&gt;Apache Qpid is an open-source messaging system that implements the Advanced Message Queuing Protocol (AMQP). It enables applications to communicate by sending messages between distributed systems, supporting reliable, asynchronous, and scalable messaging.&lt;/p&gt;

&lt;h3&gt;
  
  
  Usage of QPID
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Enterprise Messaging:&lt;/strong&gt; Integrate applications across platforms using message queues.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Event-Driven Architectures:&lt;/strong&gt; Decouple producers and consumers for scalable event processing.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Microservices Communication:&lt;/strong&gt; Enable reliable communication between microservices.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Data Streaming:&lt;/strong&gt; Transport data streams between services or systems.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Basic Setup of QPID
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Install Qpid Broker:&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;Download from &lt;a href="https://qpid.apache.org/" rel="noopener noreferrer"&gt;Apache Qpid website&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Install using package manager or binaries.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. Start the Broker:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Run the broker service (e.g., qpid-server or qpidd).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;3. Configure Broker:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Edit configuration files for ports, authentication, and queues.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Validate Setup
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Check broker status: systemctl status qpidd or ps aux | grep qpidd&lt;/li&gt;
&lt;li&gt;Connect using Qpid client tools or AMQP libraries.&lt;/li&gt;
&lt;li&gt;Send and receive a test message.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  How to Use QPID
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Use AMQP client libraries (Java, Python, C++, etc.) to connect to the broker.&lt;/li&gt;
&lt;li&gt;Create queues and topics for message routing.&lt;/li&gt;
&lt;li&gt;Publish and consume messages using the client API.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Example Use Case: Order Processing System
&lt;/h3&gt;

&lt;h3&gt;
  
  
  Scenario
&lt;/h3&gt;

&lt;p&gt;An e-commerce platform uses QPID to manage order processing. When a customer places an order, the order service publishes a message to a QPID queue. Multiple backend services (inventory, payment, shipping) consume messages from this queue to process the order asynchronously and reliably.&lt;/p&gt;

&lt;h3&gt;
  
  
  QPID Broker Configuration Example
&lt;/h3&gt;

&lt;p&gt;qpid.conf (sample)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;auth=yes
port=5672
log-enable=info+
queue-pattern=order-queue;max-count=10000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Python Producer Example
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import qpid.messaging

connection = qpid.messaging.Connection("localhost:5672")
connection.open()
session = connection.session()
sender = session.sender("order-queue")
order = {"order_id": 123, "item": "Laptop", "quantity": 1}
sender.send(qpid.messaging.Message(content=str(order)))
connection.close()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Python Consumer Example
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import qpid.messaging

connection = qpid.messaging.Connection("localhost:5672")
connection.open()
session = connection.session()
receiver = session.receiver("order-queue")
message = receiver.fetch(timeout=10)
print("Received order:", message.content)
connection.close()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Real World Benefits
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Scalability:&lt;/strong&gt; Multiple consumers can process orders in parallel.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Reliability:&lt;/strong&gt; Orders are not lost if a service is temporarily unavailable.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Decoupling:&lt;/strong&gt; Services operate independently, improving maintainability.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Auditability:&lt;/strong&gt; Message logs provide a trace of all processed orders.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  QPID Order Processing Flow Diagram
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhbvo3o9z2i7nbr647pit.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhbvo3o9z2i7nbr647pit.png" width="800" height="168"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Legend:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The Order Service publishes messages to the QPID Broker.&lt;/li&gt;
&lt;li&gt;Multiple backend services consume messages from the broker and process them independently.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Best Practices
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Secure Communication:&lt;/strong&gt; Use TLS/SSL for broker connections.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Authentication:&lt;/strong&gt; Enable user authentication and access control.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Queue Management:&lt;/strong&gt; Monitor and manage queue sizes to prevent overflow.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Error Handling:&lt;/strong&gt; Implement robust error handling and message retries.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Resource Monitoring:&lt;/strong&gt; Track broker performance and resource usage.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Version Compatibility:&lt;/strong&gt; Ensure client and broker versions are compatible.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For more details, visit the &lt;a href="https://qpid.apache.org/" rel="noopener noreferrer"&gt;Apache Qpid documentation&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>apacheqpid</category>
      <category>beginners</category>
      <category>vikashgyan</category>
      <category>qpid</category>
    </item>
    <item>
      <title>Spring Boot Quick Start Guide</title>
      <dc:creator>Vikash Kumar</dc:creator>
      <pubDate>Mon, 24 Nov 2025 02:21:10 +0000</pubDate>
      <link>https://forem.com/ervikash/spring-boot-quick-start-guide-3p41</link>
      <guid>https://forem.com/ervikash/spring-boot-quick-start-guide-3p41</guid>
      <description>&lt;p&gt;A practical guide to building a production-ready Spring Boot REST API with CRUD operations, database integration, monitoring, and deployment.&lt;/p&gt;

&lt;h3&gt;
  
  
  Table of Contents
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Project Setup&lt;/li&gt;
&lt;li&gt;REST CRUD Implementation&lt;/li&gt;
&lt;li&gt;Database Layer with JPA&lt;/li&gt;
&lt;li&gt;Actuator APIs&lt;/li&gt;
&lt;li&gt;Logging &amp;amp; Configuration&lt;/li&gt;
&lt;li&gt;Deploy &amp;amp; Test&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  1. Project Setup
&lt;/h3&gt;

&lt;h3&gt;
  
  
  Using Spring Initializr
&lt;/h3&gt;

&lt;p&gt;Visit &lt;a href="https://start.spring.io" rel="noopener noreferrer"&gt;start.spring.io&lt;/a&gt; or use CLI:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;curl https://start.spring.io/starter.tgz \
  -d dependencies=web,data-jpa,h2,actuator,validation,lombok \
  -d type=maven-project \
  -d javaVersion=21 \
  -d bootVersion=3.2.0 \
  -d groupId=com.gyan \
  -d artifactId=education-app \
  -d name=EducationApp \
  -d packageName=com.gyan.education | tar -xzvf -
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Project Structure
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;education-app/
├── src/main/java/com/gyan/education/
│ ├── EducationAppApplication.java
│ ├── controller/
│ │ └── StudentController.java
│ ├── model/
│ │ └── Student.java
│ ├── repository/
│ │ └── StudentRepository.java
│ ├── service/
│ │ ├── StudentService.java
│ │ └── StudentServiceImpl.java
│ └── exception/
│ ├── ResourceNotFoundException.java
│ └── GlobalExceptionHandler.java
├── src/main/resources/
│ ├── application.yml
│ └── logback-spring.xml
└── pom.xml
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Key Dependencies (pom.xml)
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dependencies&amp;gt;
    &amp;lt;!-- Spring Boot Starters --&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;spring-boot-starter-web&amp;lt;/artifactId&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;spring-boot-starter-data-jpa&amp;lt;/artifactId&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;spring-boot-starter-actuator&amp;lt;/artifactId&amp;gt;
    &amp;lt;/dependency&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;spring-boot-starter-validation&amp;lt;/artifactId&amp;gt;
    &amp;lt;/dependency&amp;gt;

    &amp;lt;!-- Database --&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;com.h2database&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;h2&amp;lt;/artifactId&amp;gt;
        &amp;lt;scope&amp;gt;runtime&amp;lt;/scope&amp;gt;
    &amp;lt;/dependency&amp;gt;

    &amp;lt;!-- Utils --&amp;gt;
    &amp;lt;dependency&amp;gt;
        &amp;lt;groupId&amp;gt;org.projectlombok&amp;lt;/groupId&amp;gt;
        &amp;lt;artifactId&amp;gt;lombok&amp;lt;/artifactId&amp;gt;
        &amp;lt;optional&amp;gt;true&amp;lt;/optional&amp;gt;
    &amp;lt;/dependency&amp;gt;
&amp;lt;/dependencies&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. REST CRUD Implementation
&lt;/h3&gt;

&lt;h3&gt;
  
  
  Entity Model
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.gyan.education.model;

import jakarta.persistence.*;
import jakarta.validation.constraints.*;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import java.time.LocalDateTime;

@Entity
@Table(name = "students")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank(message = "Name is required")
    @Size(min = 2, max = 100)
    private String name;

    @Email(message = "Invalid email format")
    @NotBlank(message = "Email is required")
    @Column(unique = true)
    private String email;

    @NotNull(message = "Grade is required")
    @Min(value = 1, message = "Grade must be between 1 and 12")
    @Max(value = 12, message = "Grade must be between 1 and 12")
    private Integer grade;

    @Column(name = "enrollment_date")
    private LocalDateTime enrollmentDate;

    @CreationTimestamp
    @Column(name = "created_at", updatable = false)
    private LocalDateTime createdAt;

    @UpdateTimestamp
    @Column(name = "updated_at")
    private LocalDateTime updatedAt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Repository Layer
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.gyan.education.repository;

import com.gyan.education.model.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;

@Repository
public interface StudentRepository extends JpaRepository&amp;lt;Student, Long&amp;gt; {
    Optional&amp;lt;Student&amp;gt; findByEmail(String email);
    List&amp;lt;Student&amp;gt; findByGrade(Integer grade);
    boolean existsByEmail(String email);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Service Layer
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.gyan.education.service;

import com.gyan.education.model.Student;
import java.util.List;

public interface StudentService {
    Student createStudent(Student student);
    Student getStudentById(Long id);
    List&amp;lt;Student&amp;gt; getAllStudents();
    Student updateStudent(Long id, Student student);
    void deleteStudent(Long id);
    List&amp;lt;Student&amp;gt; getStudentsByGrade(Integer grade);
}

package com.gyan.education.service;

import com.gyan.education.exception.ResourceNotFoundException;
import com.gyan.education.model.Student;
import com.gyan.education.repository.StudentRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
@Transactional
public class StudentServiceImpl implements StudentService {

    private final StudentRepository studentRepository;

    @Override
    public Student createStudent(Student student) {
        log.info("Creating student with email: {}", student.getEmail());

        if (studentRepository.existsByEmail(student.getEmail())) {
            throw new IllegalArgumentException("Email already exists: " + student.getEmail());
        }

        student.setEnrollmentDate(LocalDateTime.now());
        Student savedStudent = studentRepository.save(student);

        log.info("Student created successfully with ID: {}", savedStudent.getId());
        return savedStudent;
    }

    @Override
    @Transactional(readOnly = true)
    public Student getStudentById(Long id) {
        log.debug("Fetching student with ID: {}", id);
        return studentRepository.findById(id)
                .orElseThrow(() -&amp;gt; new ResourceNotFoundException("Student not found with ID: " + id));
    }

    @Override
    @Transactional(readOnly = true)
    public List&amp;lt;Student&amp;gt; getAllStudents() {
        log.debug("Fetching all students");
        return studentRepository.findAll();
    }

    @Override
    public Student updateStudent(Long id, Student student) {
        log.info("Updating student with ID: {}", id);

        Student existingStudent = getStudentById(id);
        existingStudent.setName(student.getName());
        existingStudent.setEmail(student.getEmail());
        existingStudent.setGrade(student.getGrade());

        Student updatedStudent = studentRepository.save(existingStudent);
        log.info("Student updated successfully with ID: {}", id);

        return updatedStudent;
    }

    @Override
    public void deleteStudent(Long id) {
        log.info("Deleting student with ID: {}", id);

        Student student = getStudentById(id);
        studentRepository.delete(student);

        log.info("Student deleted successfully with ID: {}", id);
    }

    @Override
    @Transactional(readOnly = true)
    public List&amp;lt;Student&amp;gt; getStudentsByGrade(Integer grade) {
        log.debug("Fetching students by grade: {}", grade);
        return studentRepository.findByGrade(grade);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Controller Layer
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.gyan.education.controller;

import com.gyan.education.model.Student;
import com.gyan.education.service.StudentService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/v1/students")
@RequiredArgsConstructor
@Slf4j
public class StudentController {

    private final StudentService studentService;

    @PostMapping
    public ResponseEntity&amp;lt;Student&amp;gt; createStudent(@Valid @RequestBody Student student) {
        log.info("POST /api/v1/students - Creating student");
        Student created = studentService.createStudent(student);
        return ResponseEntity.status(HttpStatus.CREATED).body(created);
    }

    @GetMapping("/{id}")
    public ResponseEntity&amp;lt;Student&amp;gt; getStudent(@PathVariable Long id) {
        log.debug("GET /api/v1/students/{}", id);
        Student student = studentService.getStudentById(id);
        return ResponseEntity.ok(student);
    }

    @GetMapping
    public ResponseEntity&amp;lt;List&amp;lt;Student&amp;gt;&amp;gt; getAllStudents(
            @RequestParam(required = false) Integer grade) {
        log.debug("GET /api/v1/students - grade filter: {}", grade);

        List&amp;lt;Student&amp;gt; students = grade != null 
                ? studentService.getStudentsByGrade(grade)
                : studentService.getAllStudents();

        return ResponseEntity.ok(students);
    }

    @PutMapping("/{id}")
    public ResponseEntity&amp;lt;Student&amp;gt; updateStudent(
            @PathVariable Long id,
            @Valid @RequestBody Student student) {
        log.info("PUT /api/v1/students/{}", id);
        Student updated = studentService.updateStudent(id, student);
        return ResponseEntity.ok(updated);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity&amp;lt;Void&amp;gt; deleteStudent(@PathVariable Long id) {
        log.info("DELETE /api/v1/students/{}", id);
        studentService.deleteStudent(id);
        return ResponseEntity.noContent().build();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Exception Handling
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.gyan.education.exception;

public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException(String message) {
        super(message);
    }
}

package com.gyan.education.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity&amp;lt;ErrorResponse&amp;gt; handleResourceNotFound(ResourceNotFoundException ex) {
        log.error("Resource not found: {}", ex.getMessage());

        ErrorResponse error = ErrorResponse.builder()
                .timestamp(LocalDateTime.now())
                .status(HttpStatus.NOT_FOUND.value())
                .error("Not Found")
                .message(ex.getMessage())
                .build();

        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity&amp;lt;Map&amp;lt;String, String&amp;gt;&amp;gt; handleValidationErrors(
            MethodArgumentNotValidException ex) {
        log.error("Validation failed: {}", ex.getMessage());

        Map&amp;lt;String, String&amp;gt; errors = new HashMap&amp;lt;&amp;gt;();
        ex.getBindingResult().getAllErrors().forEach(error -&amp;gt; {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });

        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity&amp;lt;ErrorResponse&amp;gt; handleIllegalArgument(IllegalArgumentException ex) {
        log.error("Invalid argument: {}", ex.getMessage());

        ErrorResponse error = ErrorResponse.builder()
                .timestamp(LocalDateTime.now())
                .status(HttpStatus.BAD_REQUEST.value())
                .error("Bad Request")
                .message(ex.getMessage())
                .build();

        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);
    }

    @lombok.Data
    @lombok.Builder
    static class ErrorResponse {
        private LocalDateTime timestamp;
        private int status;
        private String error;
        private String message;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. Database Layer with JPA
&lt;/h3&gt;

&lt;h3&gt;
  
  
  Configuration (application.yml)
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;spring:
  application:
    name: education-app

  datasource:
    url: jdbc:h2:mem:educationdb
    driver-class-name: org.h2.Driver
    username: sa
    password: 

  h2:
    console:
      enabled: true
      path: /h2-console

  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate:
      ddl-auto: update
    show-sql: true
    properties:
      hibernate:
        format_sql: true
        use_sql_comments: true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Initial Data (Optional — data.sql)
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- src/main/resources/data.sql
INSERT INTO students (name, email, grade, enrollment_date, created_at, updated_at) 
VALUES 
    ('Rishi S', 'rishi@gyan.com', 4, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
    ('Vedika K', 'vedika@gyan.com', 2, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
    ('Shiva R', 'shiva@gyan.com', 7, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  JPA Key Features Used
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Entity Relationships&lt;/strong&gt; : @OneToMany, @ManyToOne, @ManyToMany (expandable)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Auditing&lt;/strong&gt; : @CreationTimestamp, @UpdateTimestamp&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Validation&lt;/strong&gt; : @NotNull, @Email, @Size, &lt;a class="mentioned-user" href="https://dev.to/min"&gt;@min&lt;/a&gt;, &lt;a class="mentioned-user" href="https://dev.to/max"&gt;@max&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Queries&lt;/strong&gt; : Custom query methods (findByEmail, findByGrade)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Transactions&lt;/strong&gt; : @Transactional for data consistency&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  4. Actuator APIs
&lt;/h3&gt;

&lt;h3&gt;
  
  
  Configuration
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics,env,loggers,httptrace
      base-path: /actuator
  endpoint:
    health:
      show-details: always
  info:
    env:
      enabled: true

info:
  app:
    name: Education App
    description: Student Management System
    version: 1.0.0
    author: Vikash Kumar
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Key Actuator Endpoints
&lt;/h3&gt;

&lt;p&gt;EndpointPurposeURL &lt;strong&gt;Health&lt;/strong&gt; Application health statusGET /actuator/health &lt;strong&gt;Info&lt;/strong&gt; Application informationGET /actuator/info &lt;strong&gt;Metrics&lt;/strong&gt; Performance metricsGET /actuator/metrics &lt;strong&gt;Env&lt;/strong&gt; Environment propertiesGET /actuator/env &lt;strong&gt;Loggers&lt;/strong&gt; View/modify log levelsGET /actuator/loggers&lt;/p&gt;

&lt;h3&gt;
  
  
  Custom Health Indicator (Optional)
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.gyan.education.config;

import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class DatabaseHealthIndicator implements HealthIndicator {

    @Override
    public Health health() {
        // Add custom health check logic
        boolean databaseIsUp = checkDatabase();

        if (databaseIsUp) {
            return Health.up()
                    .withDetail("database", "Available")
                    .build();
        }
        return Health.down()
                .withDetail("database", "Unavailable")
                .build();
    }

    private boolean checkDatabase() {
        // Implement actual health check
        return true;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  5. Logging &amp;amp; Configuration
&lt;/h3&gt;

&lt;h3&gt;
  
  
  Logback Configuration (logback-spring.xml)
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;configuration&amp;gt;

    &amp;lt;property name="LOGS" value="./logs" /&amp;gt;

    &amp;lt;!-- Console Appender --&amp;gt;
    &amp;lt;appender name="Console" class="ch.qos.logback.core.ConsoleAppender"&amp;gt;
        &amp;lt;encoder&amp;gt;
            &amp;lt;pattern&amp;gt;%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n&amp;lt;/pattern&amp;gt;
        &amp;lt;/encoder&amp;gt;
    &amp;lt;/appender&amp;gt;

    &amp;lt;!-- File Appender --&amp;gt;
    &amp;lt;appender name="RollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender"&amp;gt;
        &amp;lt;file&amp;gt;${LOGS}/education-app.log&amp;lt;/file&amp;gt;
        &amp;lt;encoder&amp;gt;
            &amp;lt;pattern&amp;gt;%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n&amp;lt;/pattern&amp;gt;
        &amp;lt;/encoder&amp;gt;

        &amp;lt;rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"&amp;gt;
            &amp;lt;fileNamePattern&amp;gt;${LOGS}/archived/education-app-%d{yyyy-MM-dd}.%i.log&amp;lt;/fileNamePattern&amp;gt;
            &amp;lt;timeBasedFileNamingAndTriggeringPolicy 
                class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"&amp;gt;
                &amp;lt;maxFileSize&amp;gt;10MB&amp;lt;/maxFileSize&amp;gt;
            &amp;lt;/timeBasedFileNamingAndTriggeringPolicy&amp;gt;
            &amp;lt;maxHistory&amp;gt;30&amp;lt;/maxHistory&amp;gt;
        &amp;lt;/rollingPolicy&amp;gt;
    &amp;lt;/appender&amp;gt;

    &amp;lt;!-- Package-specific logging --&amp;gt;
    &amp;lt;logger name="com.gyan.education" level="DEBUG" /&amp;gt;
    &amp;lt;logger name="org.springframework.web" level="INFO" /&amp;gt;
    &amp;lt;logger name="org.hibernate" level="INFO" /&amp;gt;

    &amp;lt;root level="INFO"&amp;gt;
        &amp;lt;appender-ref ref="Console" /&amp;gt;
        &amp;lt;appender-ref ref="RollingFile" /&amp;gt;
    &amp;lt;/root&amp;gt;

&amp;lt;/configuration&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Application Profiles
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;application-dev.yml&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;spring:
  jpa:
    show-sql: true
    properties:
      hibernate:
        format_sql: true

logging:
  level:
    com.gyan.education: DEBUG
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;application-prod.yml&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;spring:
  jpa:
    show-sql: false

logging:
  level:
    com.gyan.education: INFO

management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Running with Profiles
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Development
./mvnw spring-boot:run -Dspring-boot.run.profiles=dev

# Production
java -jar target/education-app-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  6. Deploy &amp;amp; Test
&lt;/h3&gt;

&lt;h3&gt;
  
  
  Build the Application
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Maven
./mvnw clean package

# Gradle
./gradlew build
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Run Locally
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Using Maven
./mvnw spring-boot:run

# Using JAR
java -jar target/education-app-0.0.1-SNAPSHOT.jar
# Access at: http://localhost:8080
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Test with cURL
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Create a student
curl -X POST http://localhost:8080/api/v1/students \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe",
    "email": "john@gyan.com",
    "grade": 4
  }'

# Get all students
curl http://localhost:8080/api/v1/students

# Get student by ID
curl http://localhost:8080/api/v1/students/1

# Get students by grade
curl http://localhost:8080/api/v1/students?grade=4

# Update student
curl -X PUT http://localhost:8080/api/v1/students/1 \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Updated",
    "email": "john.updated@school.com",
    "grade": 11
  }'

# Delete student
curl -X DELETE http://localhost:8080/api/v1/students/1

# Check health
curl http://localhost:8080/actuator/health

# View metrics
curl http://localhost:8080/actuator/metrics
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Docker Deployment
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Dockerfile&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;FROM eclipse-temurin:21-jdk-alpine
WORKDIR /app
COPY target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Build and Run&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Build Docker image
docker build -t education-app:1.0 .

# Run container
docker run -p 8080:8080 education-app:1.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Unit Testing Example
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.gyan.education.service;

import com.gyan.education.exception.ResourceNotFoundException;
import com.gyan.education.model.Student;
import com.gyan.education.repository.StudentRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
class StudentServiceImplTest {

    @Mock
    private StudentRepository studentRepository;

    @InjectMocks
    private StudentServiceImpl studentService;

    @Test
    void createStudent_Success() {
        Student student = Student.builder()
                .name("Test Student")
                .email("test@school.com")
                .grade(10)
                .build();

        when(studentRepository.existsByEmail(anyString())).thenReturn(false);
        when(studentRepository.save(any(Student.class))).thenReturn(student);

        Student created = studentService.createStudent(student);

        assertNotNull(created);
        assertEquals("Test Student", created.getName());
        verify(studentRepository).save(any(Student.class));
    }

    @Test
    void getStudentById_NotFound() {
        when(studentRepository.findById(1L)).thenReturn(Optional.empty());

        assertThrows(ResourceNotFoundException.class, 
                () -&amp;gt; studentService.getStudentById(1L));
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Quick Reference
&lt;/h3&gt;

&lt;h3&gt;
  
  
  Project Checklist
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;✅ Spring Boot 3.x with Java 21&lt;/li&gt;
&lt;li&gt;✅ RESTful CRUD endpoints&lt;/li&gt;
&lt;li&gt;✅ JPA/Hibernate with H2 database&lt;/li&gt;
&lt;li&gt;✅ Request validation&lt;/li&gt;
&lt;li&gt;✅ Exception handling&lt;/li&gt;
&lt;li&gt;✅ Actuator for monitoring&lt;/li&gt;
&lt;li&gt;✅ Structured logging&lt;/li&gt;
&lt;li&gt;✅ Profile-based configuration&lt;/li&gt;
&lt;li&gt;✅ Docker support&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Next Steps
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Security&lt;/strong&gt; : Add Spring Security for authentication/authorization&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Swagger&lt;/strong&gt; : Integrate OpenAPI documentation&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Caching&lt;/strong&gt; : Implement Redis/Caffeine caching&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Testing&lt;/strong&gt; : Add integration tests with TestContainers&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Production DB&lt;/strong&gt; : Switch to PostgreSQL/MySQL&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Cloud&lt;/strong&gt; : Deploy to AWS/Azure/GCP&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Happy Coding! 🚀&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>springstarter</category>
      <category>springboot</category>
      <category>beginners</category>
      <category>vikashgyan</category>
    </item>
    <item>
      <title>PostgreSQL Complete Guide</title>
      <dc:creator>Vikash Kumar</dc:creator>
      <pubDate>Sun, 09 Nov 2025 03:16:15 +0000</pubDate>
      <link>https://forem.com/ervikash/postgresql-complete-guide-1ean</link>
      <guid>https://forem.com/ervikash/postgresql-complete-guide-1ean</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi7hrucc3c1tmjr0p1yoo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi7hrucc3c1tmjr0p1yoo.png" width="760" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  📖 What is PostgreSQL?
&lt;/h3&gt;

&lt;p&gt;PostgreSQL (often called "Postgres") is a powerful, open-source object-relational database management system (ORDBMS) that has been in active development for over 35 years. It's known for its reliability, feature robustness, and performance.&lt;/p&gt;

&lt;h3&gt;
  
  
  Key Characteristics:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;ACID Compliance&lt;/strong&gt; : Ensures data integrity through Atomicity, Consistency, Isolation, and Durability&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Extensible&lt;/strong&gt; : Supports custom functions, data types, and operators&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Standards Compliant&lt;/strong&gt; : Follows SQL standards with advanced features&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Multi-Platform&lt;/strong&gt; : Runs on all major operating systems&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Open Source&lt;/strong&gt; : Free to use with a permissive license&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Architecture Overview:
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;┌─────────────────┐
│ Applications │
├─────────────────┤
│ PostgreSQL │
│ Server │
├─────────────────┤
│ File System │
└─────────────────┘
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  🎯 Why PostgreSQL and Where to Use It?
&lt;/h3&gt;

&lt;h3&gt;
  
  
  Why Choose PostgreSQL?
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Advanced Data Types&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;JSON/JSONB for document storage&lt;/li&gt;
&lt;li&gt;Arrays, UUIDs, geometric types&lt;/li&gt;
&lt;li&gt;Custom composite types&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. Performance &amp;amp; Scalability&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Sophisticated query planner&lt;/li&gt;
&lt;li&gt;Parallel query execution&lt;/li&gt;
&lt;li&gt;Advanced indexing (B-tree, Hash, GiST, SP-GiST, GIN, BRIN)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;3. Reliability &amp;amp; Data Integrity&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;MVCC (Multi-Version Concurrency Control)&lt;/li&gt;
&lt;li&gt;Point-in-time recovery&lt;/li&gt;
&lt;li&gt;Streaming replication&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;4. Extensibility&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Custom functions in multiple languages&lt;/li&gt;
&lt;li&gt;Extensions ecosystem&lt;/li&gt;
&lt;li&gt;Foreign data wrappers&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Use Cases
&lt;/h3&gt;

&lt;h4&gt;
  
  
  🏥 Healthcare &amp;amp; Medical Systems
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Patient management with complex data relationships
-- Medical records with HIPAA compliance
-- Real-time monitoring systems
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Examples&lt;/strong&gt; : Electronic Health Records (EHR), Medical IoT devices, Clinical trial management&lt;/p&gt;

&lt;h4&gt;
  
  
  💰 Financial Services
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Transaction processing with ACID guarantees
-- Risk management and compliance
-- Real-time fraud detection
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Examples&lt;/strong&gt; : Banking systems, Payment processors, Trading platforms, Cryptocurrency exchanges&lt;/p&gt;

&lt;h4&gt;
  
  
  🛒 E-commerce &amp;amp; Retail
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Product catalogs with complex attributes
-- Inventory management across locations
-- Customer behavior analytics
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Examples&lt;/strong&gt; : Online marketplaces, Inventory systems, Recommendation engines&lt;/p&gt;

&lt;h4&gt;
  
  
  🌐 Web Applications
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- User management and authentication
-- Content management systems
-- Social media platforms
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Examples&lt;/strong&gt; : SaaS applications, Content platforms, Social networks&lt;/p&gt;

&lt;h4&gt;
  
  
  📊 Analytics &amp;amp; Business Intelligence
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Data warehousing solutions
-- Real-time analytics dashboards
-- Time-series data analysis
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Examples&lt;/strong&gt; : Business intelligence, IoT data processing, Log analysis&lt;/p&gt;

&lt;h4&gt;
  
  
  🎮 Gaming &amp;amp; Entertainment
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Player profiles and game state
-- Leaderboards and achievements
-- Real-time multiplayer data
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Examples&lt;/strong&gt; : Online games, Streaming platforms, Entertainment apps&lt;/p&gt;

&lt;h3&gt;
  
  
  🛠️ Installation and Setup
&lt;/h3&gt;

&lt;h3&gt;
  
  
  Prerequisites
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# System requirements
- RAM: Minimum 1GB (4GB+ recommended)
- Disk: 512MB minimum installation
- OS: Linux, Windows, macOS, BSD
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Installation Methods
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Option 1: Official Installer (Recommended for beginners)
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Download from https://www.postgresql.org/download/
# Follow GUI installation wizard
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Option 2: Package Manager
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Ubuntu/Debian
sudo apt update
sudo apt install postgresql postgresql-contrib

# CentOS/RHEL/Fedora
sudo yum install postgresql-server postgresql-contrib
# or
sudo dnf install postgresql-server postgresql-contrib

# macOS (Homebrew)
brew install postgresql@15

# Windows (Chocolatey)
choco install postgresql
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Option 3: Docker (Recommended for development)
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Pull and run PostgreSQL container
docker run --name postgres-dev \
  -e POSTGRES_PASSWORD=mypassword \
  -e POSTGRES_DB=mydatabase \
  -p 5432:5432 \
  -d postgres:15-alpine

# Connect to container
docker exec -it postgres-dev psql -U postgres -d mydatabase
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Initial Configuration
&lt;/h3&gt;

&lt;h4&gt;
  
  
  1. Initialize Database (Linux/Unix)
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Initialize database cluster
sudo -u postgres initdb -D /var/lib/pgsql/data

# Start PostgreSQL service
sudo systemctl start postgresql
sudo systemctl enable postgresql

# Create initial user
sudo -u postgres createuser --interactive
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  2. Basic Configuration Files
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Main configuration file
/var/lib/pgsql/data/postgresql.conf

# Client authentication
/var/lib/pgsql/data/pg_hba.conf
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  3. Essential Configuration Settings
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- postgresql.conf key settings
listen_addresses = 'localhost' # or '*' for all interfaces
port = 5432
max_connections = 100
shared_buffers = 128MB # 25% of RAM typically
effective_cache_size = 4GB # 50-75% of RAM
work_mem = 4MB
maintenance_work_mem = 64MB
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  🏗️ Database Setup Example: Health &amp;amp; Trends Microservice
&lt;/h3&gt;

&lt;p&gt;Let's create a complete database setup for a health and wellness tracking microservice.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Create Database and User
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Connect as superuser (postgres)
psql -U postgres

-- Create database
CREATE DATABASE health_trends_db 
WITH 
    ENCODING = 'UTF8'
    LC_COLLATE = 'en_US.UTF-8'
    LC_CTYPE = 'en_US.UTF-8'
    TEMPLATE = template0;

-- Create application user
CREATE USER health_app_user WITH PASSWORD 'SecureP@ssw0rd123';

-- Grant privileges
GRANT CONNECT ON DATABASE health_trends_db TO health_app_user;
GRANT USAGE, CREATE ON SCHEMA public TO health_app_user;

-- Connect to the new database
\c health_trends_db
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2. Create Schemas for Organization
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Create schemas for different domains
CREATE SCHEMA IF NOT EXISTS user_management;
CREATE SCHEMA IF NOT EXISTS health_data;
CREATE SCHEMA IF NOT EXISTS analytics;
CREATE SCHEMA IF NOT EXISTS audit;

-- Grant schema permissions
GRANT USAGE, CREATE ON SCHEMA user_management TO health_app_user;
GRANT USAGE, CREATE ON SCHEMA health_data TO health_app_user;
GRANT USAGE, CREATE ON SCHEMA analytics TO health_app_user;
GRANT USAGE ON SCHEMA audit TO health_app_user; -- Read-only for audit
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3. Create Tables
&lt;/h3&gt;

&lt;h4&gt;
  
  
  User Management Schema
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- User profiles table
CREATE TABLE user_management.users (
    user_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    email VARCHAR(255) UNIQUE NOT NULL,
    username VARCHAR(100) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    first_name VARCHAR(100),
    last_name VARCHAR(100),
    date_of_birth DATE,
    gender VARCHAR(20),
    height_cm INTEGER CHECK (height_cm &amp;gt; 0 AND height_cm &amp;lt; 300),
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    is_active BOOLEAN DEFAULT true,
    last_login TIMESTAMP WITH TIME ZONE,
    profile_data JSONB DEFAULT '{}'
);

-- User preferences
CREATE TABLE user_management.user_preferences (
    preference_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES user_management.users(user_id) ON DELETE CASCADE,
    notification_enabled BOOLEAN DEFAULT true,
    data_sharing_consent BOOLEAN DEFAULT false,
    preferred_units JSONB DEFAULT '{"weight": "kg", "distance": "km", "temperature": "celsius"}',
    privacy_settings JSONB DEFAULT '{}',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Health Data Schema
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Health metrics table
CREATE TABLE health_data.health_metrics (
    metric_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES user_management.users(user_id) ON DELETE CASCADE,
    metric_type VARCHAR(50) NOT NULL, -- 'weight', 'blood_pressure', 'heart_rate', etc.
    value DECIMAL(10,2) NOT NULL,
    unit VARCHAR(20) NOT NULL,
    recorded_at TIMESTAMP WITH TIME ZONE NOT NULL,
    source VARCHAR(50) DEFAULT 'manual', -- 'manual', 'device', 'app'
    device_info JSONB DEFAULT '{}',
    notes TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- Activity tracking
CREATE TABLE health_data.activities (
    activity_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES user_management.users(user_id) ON DELETE CASCADE,
    activity_type VARCHAR(50) NOT NULL, -- 'walking', 'running', 'cycling', etc.
    duration_minutes INTEGER NOT NULL CHECK (duration_minutes &amp;gt; 0),
    calories_burned DECIMAL(7,2),
    distance_km DECIMAL(8,3),
    average_heart_rate INTEGER,
    max_heart_rate INTEGER,
    started_at TIMESTAMP WITH TIME ZONE NOT NULL,
    ended_at TIMESTAMP WITH TIME ZONE NOT NULL,
    gps_data JSONB DEFAULT '{}', -- Store route information
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT valid_duration CHECK (ended_at &amp;gt; started_at)
);

-- Sleep tracking
CREATE TABLE health_data.sleep_records (
    sleep_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES user_management.users(user_id) ON DELETE CASCADE,
    sleep_date DATE NOT NULL,
    bedtime TIMESTAMP WITH TIME ZONE NOT NULL,
    wake_time TIMESTAMP WITH TIME ZONE NOT NULL,
    total_sleep_minutes INTEGER NOT NULL,
    deep_sleep_minutes INTEGER DEFAULT 0,
    light_sleep_minutes INTEGER DEFAULT 0,
    rem_sleep_minutes INTEGER DEFAULT 0,
    sleep_quality_score INTEGER CHECK (sleep_quality_score BETWEEN 1 AND 10),
    sleep_phases JSONB DEFAULT '[]', -- Detailed sleep phase data
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT valid_sleep_duration CHECK (wake_time &amp;gt; bedtime),
    CONSTRAINT valid_sleep_total CHECK (
        total_sleep_minutes = COALESCE(deep_sleep_minutes, 0) + 
                             COALESCE(light_sleep_minutes, 0) + 
                             COALESCE(rem_sleep_minutes, 0)
    )
);

-- Nutrition tracking
CREATE TABLE health_data.nutrition_logs (
    log_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES user_management.users(user_id) ON DELETE CASCADE,
    meal_type VARCHAR(20) NOT NULL, -- 'breakfast', 'lunch', 'dinner', 'snack'
    food_item VARCHAR(255) NOT NULL,
    quantity DECIMAL(8,2) NOT NULL,
    unit VARCHAR(20) NOT NULL, -- 'grams', 'pieces', 'cups', etc.
    calories DECIMAL(7,2),
    protein_g DECIMAL(6,2),
    carbs_g DECIMAL(6,2),
    fat_g DECIMAL(6,2),
    fiber_g DECIMAL(6,2),
    sugar_g DECIMAL(6,2),
    sodium_mg DECIMAL(8,2),
    logged_at TIMESTAMP WITH TIME ZONE NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Analytics Schema
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Health trends and analytics
CREATE TABLE analytics.health_trends (
    trend_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES user_management.users(user_id) ON DELETE CASCADE,
    metric_type VARCHAR(50) NOT NULL,
    period_type VARCHAR(20) NOT NULL, -- 'daily', 'weekly', 'monthly'
    period_start DATE NOT NULL,
    period_end DATE NOT NULL,
    avg_value DECIMAL(10,2),
    min_value DECIMAL(10,2),
    max_value DECIMAL(10,2),
    trend_direction VARCHAR(10), -- 'up', 'down', 'stable'
    trend_strength DECIMAL(3,2), -- Correlation coefficient
    calculated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,

    UNIQUE(user_id, metric_type, period_type, period_start)
);

-- Goal tracking
CREATE TABLE analytics.user_goals (
    goal_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES user_management.users(user_id) ON DELETE CASCADE,
    goal_type VARCHAR(50) NOT NULL, -- 'weight_loss', 'step_count', 'exercise_frequency'
    target_value DECIMAL(10,2) NOT NULL,
    current_value DECIMAL(10,2) DEFAULT 0,
    unit VARCHAR(20) NOT NULL,
    target_date DATE,
    status VARCHAR(20) DEFAULT 'active', -- 'active', 'completed', 'paused', 'abandoned'
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Audit Schema
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Audit trail for all data changes
CREATE TABLE audit.data_changes (
    audit_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    table_name VARCHAR(100) NOT NULL,
    operation VARCHAR(10) NOT NULL, -- 'INSERT', 'UPDATE', 'DELETE'
    user_id UUID,
    old_values JSONB,
    new_values JSONB,
    changed_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    changed_by VARCHAR(100) -- Application user or system process
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4. Create Indexes for Performance
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- User management indexes
CREATE INDEX idx_users_email ON user_management.users(email);
CREATE INDEX idx_users_username ON user_management.users(username);
CREATE INDEX idx_users_active ON user_management.users(is_active);

-- Health data indexes
CREATE INDEX idx_health_metrics_user_type ON health_data.health_metrics(user_id, metric_type);
CREATE INDEX idx_health_metrics_recorded_at ON health_data.health_metrics(recorded_at);
CREATE INDEX idx_activities_user_started ON health_data.activities(user_id, started_at);
CREATE INDEX idx_sleep_user_date ON health_data.sleep_records(user_id, sleep_date);
CREATE INDEX idx_nutrition_user_logged ON health_data.nutrition_logs(user_id, logged_at);

-- Analytics indexes
CREATE INDEX idx_trends_user_metric ON analytics.health_trends(user_id, metric_type, period_type);
CREATE INDEX idx_goals_user_status ON analytics.user_goals(user_id, status);

-- Audit indexes
CREATE INDEX idx_audit_table_changed ON audit.data_changes(table_name, changed_at);
CREATE INDEX idx_audit_user ON audit.data_changes(user_id);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  5. Create Views for Common Queries
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Latest health metrics per user
CREATE VIEW analytics.latest_health_metrics AS
SELECT DISTINCT ON (user_id, metric_type)
    user_id,
    metric_type,
    value,
    unit,
    recorded_at
FROM health_data.health_metrics
ORDER BY user_id, metric_type, recorded_at DESC;

-- User health summary
CREATE VIEW analytics.user_health_summary AS
SELECT 
    u.user_id,
    u.username,
    u.first_name,
    u.last_name,
    COUNT(DISTINCT hm.metric_id) as total_health_records,
    COUNT(DISTINCT a.activity_id) as total_activities,
    COUNT(DISTINCT sr.sleep_id) as total_sleep_records,
    MAX(hm.recorded_at) as last_health_update,
    MAX(a.started_at) as last_activity,
    MAX(sr.sleep_date) as last_sleep_record
FROM user_management.users u
LEFT JOIN health_data.health_metrics hm ON u.user_id = hm.user_id
LEFT JOIN health_data.activities a ON u.user_id = a.user_id
LEFT JOIN health_data.sleep_records sr ON u.user_id = sr.user_id
WHERE u.is_active = true
GROUP BY u.user_id, u.username, u.first_name, u.last_name;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  6. Create Functions and Triggers
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Function to update timestamps
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Apply to relevant tables
CREATE TRIGGER update_users_updated_at 
    BEFORE UPDATE ON user_management.users 
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

CREATE TRIGGER update_preferences_updated_at 
    BEFORE UPDATE ON user_management.user_preferences 
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

-- Audit trigger function
CREATE OR REPLACE FUNCTION audit_trigger_function()
RETURNS TRIGGER AS $$
BEGIN
    IF TG_OP = 'DELETE' THEN
        INSERT INTO audit.data_changes (table_name, operation, user_id, old_values, changed_by)
        VALUES (TG_TABLE_NAME, TG_OP, OLD.user_id, to_jsonb(OLD), current_user);
        RETURN OLD;
    ELSIF TG_OP = 'UPDATE' THEN
        INSERT INTO audit.data_changes (table_name, operation, user_id, old_values, new_values, changed_by)
        VALUES (TG_TABLE_NAME, TG_OP, NEW.user_id, to_jsonb(OLD), to_jsonb(NEW), current_user);
        RETURN NEW;
    ELSIF TG_OP = 'INSERT' THEN
        INSERT INTO audit.data_changes (table_name, operation, user_id, new_values, changed_by)
        VALUES (TG_TABLE_NAME, TG_OP, NEW.user_id, to_jsonb(NEW), current_user);
        RETURN NEW;
    END IF;
    RETURN NULL;
END;
$$ LANGUAGE plpgsql;

-- Apply audit triggers to sensitive tables
CREATE TRIGGER audit_users_trigger
    AFTER INSERT OR UPDATE OR DELETE ON user_management.users
    FOR EACH ROW EXECUTE FUNCTION audit_trigger_function();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  7. Sample Data and Usage
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Insert sample user
INSERT INTO user_management.users (email, username, first_name, last_name, date_of_birth, gender, height_cm)
VALUES ('john.doe@example.com', 'johndoe', 'John', 'Doe', '1990-05-15', 'male', 175);

-- Get the user_id for further operations
-- In a real application, you'd typically get this from your authentication system

-- Insert health metrics
INSERT INTO health_data.health_metrics (user_id, metric_type, value, unit, recorded_at)
VALUES 
    ((SELECT user_id FROM user_management.users WHERE username = 'johndoe'), 'weight', 75.5, 'kg', CURRENT_TIMESTAMP),
    ((SELECT user_id FROM user_management.users WHERE username = 'johndoe'), 'blood_pressure_systolic', 120, 'mmHg', CURRENT_TIMESTAMP),
    ((SELECT user_id FROM user_management.users WHERE username = 'johndoe'), 'blood_pressure_diastolic', 80, 'mmHg', CURRENT_TIMESTAMP);

-- Insert activity
INSERT INTO health_data.activities (user_id, activity_type, duration_minutes, calories_burned, distance_km, started_at, ended_at)
VALUES (
    (SELECT user_id FROM user_management.users WHERE username = 'johndoe'),
    'running',
    30,
    300,
    5.2,
    CURRENT_TIMESTAMP - INTERVAL '2 hours',
    CURRENT_TIMESTAMP - INTERVAL '90 minutes'
);

-- Query user's health summary
SELECT * FROM analytics.user_health_summary WHERE username = 'johndoe';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  ✅ Do's and Don'ts
&lt;/h3&gt;

&lt;h3&gt;
  
  
  ✅ DO's
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Database Design
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;✅ Use appropriate data types&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Good: Use specific types 
CREATE TABLE products (  
   price DECIMAL(10,2), -- Not FLOAT for money     
   created_at TIMESTAMPTZ, -- Not VARCHAR for timestamps     
   is_active BOOLEAN -- Not INTEGER for flags 
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;✅ Implement proper constraints&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Good: Add meaningful constraints 
CREATE TABLE users (     
  email VARCHAR(255) UNIQUE NOT NULL,     
  age INTEGER CHECK (age &amp;gt;= 0 AND age &amp;lt;= 150),     
  status VARCHAR(20) CHECK (status IN ('active', 'inactive', 'pending')) 
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;✅ Use transactions for data consistency&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;BEGIN;     
  UPDATE accounts SET balance = balance - 100 WHERE id = 1;     
  UPDATE accounts SET balance = balance + 100 WHERE id = 2;     
  INSERT INTO transactions (from_account, to_account, amount) VALUES (1, 2, 100); 
COMMIT;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;✅ Create appropriate indexes&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Create indexes on frequently queried columns
CREATE INDEX idx_orders_customer_date ON orders(customer_id, order_date);
CREATE INDEX idx_products_category ON products(category_id) WHERE active = true;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Performance
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;✅ Use EXPLAIN ANALYZE to optimize queries&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;EXPLAIN ANALYZE SELECT * FROM large_table WHERE indexed_column = 'value';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;✅ Use connection pooling&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Configure connection pooling in application 
-- Example with pgBouncer or application-level pooling
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;✅ Regular maintenance&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Regular VACUUM and ANALYZE VACUUM ANALYZE table_name;  
-- Monitor table bloat 
SELECT schemaname, tablename, n_dead_tup, n_live_tup  
FROM pg_stat_user_tables;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Security
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;✅ Use least privilege principle&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Create role-based access
CREATE ROLE readonly_user;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly_user;

CREATE ROLE app_user;
GRANT SELECT, INSERT, UPDATE ON specific_tables TO app_user;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;✅ Use prepared statements&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Good: Using prepared statements (Python example)
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  ❌ DON’Ts
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Database Design
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;**❌ Don’t use SELECT ***
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Bad: Selecting all columns
SELECT * FROM large_table;

-- Good: Select only needed columns
SELECT id, name, email FROM users WHERE active = true;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;❌ Don’t ignore normalization rules&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Bad: Denormalized data with redundancy
CREATE TABLE orders (
    id INTEGER,
    customer_name VARCHAR(100),
    customer_email VARCHAR(100),
    customer_address TEXT,
    product_name VARCHAR(100),
    product_price DECIMAL(10,2)
);

-- Good: Properly normalized
CREATE TABLE customers (id INTEGER PRIMARY KEY, name VARCHAR(100), email VARCHAR(100));
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER REFERENCES customers(id));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;❌ Don’t use generic column names&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Bad: Generic names
CREATE TABLE data (
    id INTEGER,
    value1 TEXT,
    value2 INTEGER,
    flag BOOLEAN
);

-- Good: Descriptive names
CREATE TABLE user_profiles (
    user_id INTEGER,
    full_name TEXT,
    age INTEGER,
    is_active BOOLEAN
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Performance
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;❌ Don’t create unnecessary indexes&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Bad: Too many indexes on small, rarely-queried tables
CREATE INDEX idx1 ON small_table(col1);
CREATE INDEX idx2 ON small_table(col2);
CREATE INDEX idx3 ON small_table(col3);
-- ... etc
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;❌ Don’t use functions in WHERE clauses on large tables&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Bad: Function in WHERE clause prevents index usage
SELECT * FROM orders WHERE EXTRACT(YEAR FROM order_date) = 2023;

-- Good: Use range conditions
SELECT * FROM orders WHERE order_date &amp;gt;= '2023-01-01' AND order_date &amp;lt; '2024-01-01';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Security
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;❌ Never store plain text passwords&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Bad: Plain text password
CREATE TABLE users (
    username VARCHAR(50),
    password VARCHAR(50) -- NEVER DO THIS
);

-- Good: Store hashed passwords
CREATE TABLE users (
    username VARCHAR(50),
    password_hash VARCHAR(255) -- Store bcrypt or similar hash
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;❌ Don’t use string concatenation for queries&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Bad: SQL injection risk
query = f"SELECT * FROM users WHERE name = '{user_input}'"

# Good: Use parameterized queries
cursor.execute("SELECT * FROM users WHERE name = %s", (user_input,))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  💡 Helpful Tips and Best Practices
&lt;/h3&gt;

&lt;h3&gt;
  
  
  Performance Optimization
&lt;/h3&gt;

&lt;h4&gt;
  
  
  1. Query Optimization
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Use EXPLAIN to understand query plans
EXPLAIN (ANALYZE, BUFFERS) SELECT u.name, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at &amp;gt; '2023-01-01'
GROUP BY u.id, u.name;

-- Use window functions instead of subqueries when possible
-- Bad: Correlated subquery
SELECT id, name, (SELECT COUNT(*) FROM orders WHERE user_id = u.id) as order_count
FROM users u;

-- Good: Window function
SELECT DISTINCT u.id, u.name, COUNT(o.id) OVER (PARTITION BY u.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  2. Index Strategies
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Composite indexes: order matters
CREATE INDEX idx_orders_status_date ON orders(status, created_at); -- Good for queries filtering by status first
CREATE INDEX idx_orders_date_status ON orders(created_at, status); -- Good for queries filtering by date first

-- Partial indexes for specific conditions
CREATE INDEX idx_active_users ON users(email) WHERE active = true;
-- Functional indexes
CREATE INDEX idx_users_lower_email ON users(lower(email));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  3. Configuration Tuning
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Key postgresql.conf parameters
shared_buffers = '256MB' -- 25% of RAM
effective_cache_size = '1GB' -- 50-75% of RAM
work_mem = '16MB' -- Per operation memory
maintenance_work_mem = '256MB' -- Maintenance operations
random_page_cost = 1.1 -- For SSDs
effective_io_concurrency = 200 -- For SSDs
max_worker_processes = 8 -- Number of CPU cores
max_parallel_workers_per_gather = 4 -- Parallel query workers
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Monitoring and Maintenance
&lt;/h3&gt;

&lt;h4&gt;
  
  
  1. Health Checks
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Check database size
SELECT 
    datname,
    pg_size_pretty(pg_database_size(datname)) as size
FROM pg_database
ORDER BY pg_database_size(datname) DESC;

-- Check table sizes
SELECT 
    schemaname,
    tablename,
    pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) as size,
    pg_size_pretty(pg_relation_size(schemaname||'.'||tablename)) as table_size,
    pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename) - pg_relation_size(schemaname||'.'||tablename)) as index_size
FROM pg_tables
ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC;

-- Check for bloated tables
SELECT 
    schemaname,
    tablename,
    n_dead_tup,
    n_live_tup,
    round((n_dead_tup::float / NULLIF(n_live_tup::float, 0)) * 100, 2) as bloat_ratio
FROM pg_stat_user_tables
WHERE n_dead_tup &amp;gt; 1000
ORDER BY bloat_ratio DESC;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  2. Performance Monitoring
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Long running queries
SELECT 
    pid,
    now() - pg_stat_activity.query_start AS duration,
    query,
    state
FROM pg_stat_activity
WHERE (now() - pg_stat_activity.query_start) &amp;gt; interval '5 minutes'
ORDER BY duration DESC;

-- Index usage statistics
SELECT 
    schemaname,
    tablename,
    indexname,
    idx_scan,
    idx_tup_read,
    idx_tup_fetch
FROM pg_stat_user_indexes
ORDER BY idx_scan DESC;

-- Cache hit ratio
SELECT 
    'database' as type,
    round((sum(blks_hit) * 100.0) / (sum(blks_hit) + sum(blks_read)), 2) as cache_hit_ratio
FROM pg_stat_database
UNION ALL
SELECT 
    'tables' as type,
    round((sum(heap_blks_hit) * 100.0) / (sum(heap_blks_hit) + sum(heap_blks_read)), 2) as cache_hit_ratio
FROM pg_statio_user_tables;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Backup and Recovery
&lt;/h3&gt;

&lt;h4&gt;
  
  
  1. Backup Strategies
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Full database backup
pg_dump -h localhost -U username -d database_name &amp;gt; backup_$(date +%Y%m%d_%H%M%S).sql

# Compressed backup
pg_dump -h localhost -U username -d database_name | gzip &amp;gt; backup_$(date +%Y%m%d_%H%M%S).sql.gz

# Directory format backup (parallel)
pg_dump -h localhost -U username -d database_name -Fd -j 4 -f backup_directory/

# Point-in-time recovery setup
# Enable WAL archiving in postgresql.conf:
# wal_level = replica
# archive_mode = on
# archive_command = 'cp %p /path/to/wal/archive/%f'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  2. Recovery Examples
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Restore from SQL dump
psql -h localhost -U username -d database_name &amp;lt; backup_20231108_143022.sql

# Restore from compressed dump
gunzip -c backup_20231108_143022.sql.gz | psql -h localhost -U username -d database_name

# Restore from directory format
pg_restore -h localhost -U username -d database_name -j 4 backup_directory/
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Advanced Features
&lt;/h3&gt;

&lt;h4&gt;
  
  
  1. JSON Operations
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- JSONB operations
CREATE TABLE user_profiles (
    id SERIAL PRIMARY KEY,
    user_data JSONB
);

-- Insert JSON data
INSERT INTO user_profiles (user_data) VALUES 
('{"name": "John", "age": 30, "preferences": {"theme": "dark", "language": "en"}}');

-- Query JSON data
SELECT * FROM user_profiles WHERE user_data-&amp;gt;&amp;gt;'name' = 'John';
SELECT * FROM user_profiles WHERE user_data-&amp;gt;'preferences'-&amp;gt;&amp;gt;'theme' = 'dark';
SELECT * FROM user_profiles WHERE user_data @&amp;gt; '{"age": 30}';

-- Update JSON data
UPDATE user_profiles 
SET user_data = jsonb_set(user_data, '{preferences,theme}', '"light"')
WHERE user_data-&amp;gt;&amp;gt;'name' = 'John';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  2. Full Text Search
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Create full text search
CREATE TABLE articles (
    id SERIAL PRIMARY KEY,
    title TEXT,
    content TEXT,
    search_vector tsvector
);

-- Update search vector
UPDATE articles SET search_vector = 
    setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
    setweight(to_tsvector('english', coalesce(content, '')), 'B');

-- Create index for search
CREATE INDEX idx_articles_search ON articles USING GIN(search_vector);

-- Search query
SELECT title, ts_rank(search_vector, query) AS rank
FROM articles, plainto_tsquery('english', 'search terms') query
WHERE search_vector @@ query
ORDER BY rank DESC;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  📚 References and Resources
&lt;/h3&gt;

&lt;h3&gt;
  
  
  Official Documentation
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://www.postgresql.org/docs/" rel="noopener noreferrer"&gt;&lt;strong&gt;PostgreSQL Official Documentation&lt;/strong&gt;&lt;/a&gt; — Comprehensive official docs&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://wiki.postgresql.org/" rel="noopener noreferrer"&gt;&lt;strong&gt;PostgreSQL Wiki&lt;/strong&gt;&lt;/a&gt; — Community-maintained wiki&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.postgresqltutorial.com/" rel="noopener noreferrer"&gt;&lt;strong&gt;PostgreSQL Tutorial&lt;/strong&gt;&lt;/a&gt; — Step-by-step tutorials&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Performance and Optimization
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://pgtune.leopard.in.ua/" rel="noopener noreferrer"&gt;&lt;strong&gt;PgTune&lt;/strong&gt;&lt;/a&gt; — PostgreSQL configuration tuner&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://explain.depesz.com/" rel="noopener noreferrer"&gt;&lt;strong&gt;Explain.depesz.com&lt;/strong&gt;&lt;/a&gt; — EXPLAIN plan analyzer&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://wiki.postgresql.org/wiki/Performance_Optimization" rel="noopener noreferrer"&gt;&lt;strong&gt;PostgreSQL Performance Optimization&lt;/strong&gt;&lt;/a&gt; — Performance guide&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Tools and Extensions
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://dev.to/scottw/pgadmin---postgresql-tools-5ejk"&gt;&lt;strong&gt;pgAdmin&lt;/strong&gt;&lt;/a&gt; — Web-based administration tool&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://dbeaver.io/" rel="noopener noreferrer"&gt;&lt;strong&gt;DBeaver&lt;/strong&gt;&lt;/a&gt; — Universal database client&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://postgrest.org/" rel="noopener noreferrer"&gt;&lt;strong&gt;PostgREST&lt;/strong&gt;&lt;/a&gt; — Auto-generated REST API&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.timescale.com/" rel="noopener noreferrer"&gt;&lt;strong&gt;TimescaleDB&lt;/strong&gt;&lt;/a&gt; — Time-series extension&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://postgis.net/" rel="noopener noreferrer"&gt;&lt;strong&gt;PostGIS&lt;/strong&gt;&lt;/a&gt; — Spatial database extension&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Monitoring and Management
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://www.postgresql.org/docs/current/pgstatstatements.html" rel="noopener noreferrer"&gt;&lt;strong&gt;pg_stat_statements&lt;/strong&gt;&lt;/a&gt; — Query statistics&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.pgbouncer.org/" rel="noopener noreferrer"&gt;&lt;strong&gt;pgBouncer&lt;/strong&gt;&lt;/a&gt; — Connection pooler&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/prometheus-community/postgres_exporter" rel="noopener noreferrer"&gt;&lt;strong&gt;Prometheus PostgreSQL Exporter&lt;/strong&gt;&lt;/a&gt; — Metrics collection&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Learning Resources
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://pgexercises.com/" rel="noopener noreferrer"&gt;&lt;strong&gt;PostgreSQL Exercises&lt;/strong&gt;&lt;/a&gt; — Interactive SQL exercises&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://use-the-index-luke.com/" rel="noopener noreferrer"&gt;&lt;strong&gt;Use The Index, Luke!&lt;/strong&gt;&lt;/a&gt; — SQL indexing guide&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://planet.postgresql.org/" rel="noopener noreferrer"&gt;&lt;strong&gt;PostgreSQL Planet&lt;/strong&gt;&lt;/a&gt; — Community blogs and articles&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Books (Recommended Reading)
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;“PostgreSQL: Up and Running”&lt;/strong&gt; by Regina Obe and Leo Hsu&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;“The Art of PostgreSQL”&lt;/strong&gt; by Dimitri Fontaine&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;“PostgreSQL High Performance”&lt;/strong&gt; by Gregory Smith&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;“Mastering PostgreSQL”&lt;/strong&gt; by Hans-Jürgen Schönig&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Community and Support
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://www.postgresql.org/list/" rel="noopener noreferrer"&gt;&lt;strong&gt;PostgreSQL Mailing Lists&lt;/strong&gt;&lt;/a&gt; — Official support lists&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://pgsql-slack.herokuapp.com/" rel="noopener noreferrer"&gt;&lt;strong&gt;PostgreSQL Slack&lt;/strong&gt;&lt;/a&gt; — Community chat&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://stackoverflow.com/questions/tagged/postgresql" rel="noopener noreferrer"&gt;&lt;strong&gt;Stack Overflow PostgreSQL&lt;/strong&gt;&lt;/a&gt; — Q&amp;amp;A platform&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.reddit.com/r/PostgreSQL/" rel="noopener noreferrer"&gt;&lt;strong&gt;Reddit r/PostgreSQL&lt;/strong&gt;&lt;/a&gt; — Community discussions&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Cloud Services
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://aws.amazon.com/rds/postgresql/" rel="noopener noreferrer"&gt;&lt;strong&gt;Amazon RDS for PostgreSQL&lt;/strong&gt;&lt;/a&gt; — Managed PostgreSQL on AWS&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://cloud.google.com/sql/docs/postgres" rel="noopener noreferrer"&gt;&lt;strong&gt;Google Cloud SQL for PostgreSQL&lt;/strong&gt;&lt;/a&gt; — Managed PostgreSQL on GCP&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://azure.microsoft.com/en-us/services/postgresql/" rel="noopener noreferrer"&gt;&lt;strong&gt;Azure Database for PostgreSQL&lt;/strong&gt;&lt;/a&gt; — Managed PostgreSQL on Azure&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.heroku.com/postgres" rel="noopener noreferrer"&gt;&lt;strong&gt;Heroku Postgres&lt;/strong&gt;&lt;/a&gt; — PostgreSQL as a service&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  🎯 Quick Reference Commands
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Connection and basic info
\l -- List databases
\c database_name -- Connect to database
\dt -- List tables
\d table_name -- Describe table
\du -- List users
\q -- Quit psql

-- Useful queries
SELECT version(); -- PostgreSQL version
SELECT current_database(); -- Current database
SELECT current_user; -- Current user
SELECT pg_size_pretty(pg_database_size('dbname')); -- Database size
SELECT NOW(); -- Current timestamp

-- Performance queries
SELECT * FROM pg_stat_activity WHERE state = 'active'; -- Active queries
SELECT * FROM pg_stat_user_tables; -- Table statistics
SELECT * FROM pg_stat_user_indexes; -- Index statistics
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Remember&lt;/strong&gt; : PostgreSQL is a powerful tool that rewards understanding and proper usage. Start with the basics, follow best practices, and gradually explore advanced features as your needs grow! 🚀&lt;/p&gt;

</description>
      <category>postgres</category>
      <category>postgresqldatabase</category>
      <category>database</category>
      <category>learnpostgresql</category>
    </item>
    <item>
      <title>Complete Guide: Implementing Azure Entra ID SSO in Angular Standalone Applications</title>
      <dc:creator>Vikash Kumar</dc:creator>
      <pubDate>Thu, 30 Oct 2025 19:48:01 +0000</pubDate>
      <link>https://forem.com/ervikash/complete-guide-implementing-azure-entra-id-sso-in-angular-standalone-applications-5fpo</link>
      <guid>https://forem.com/ervikash/complete-guide-implementing-azure-entra-id-sso-in-angular-standalone-applications-5fpo</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe81d00vwi1klq9ec5jub.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe81d00vwi1klq9ec5jub.png" width="600" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Introduction
&lt;/h3&gt;

&lt;p&gt;Single Sign-On (SSO) has become essential for modern web applications, providing users with seamless authentication experiences across multiple applications. Azure Entra ID (formerly Azure Active Directory) offers robust identity and access management capabilities that integrate perfectly with Angular applications.&lt;/p&gt;

&lt;p&gt;This comprehensive guide walks you through implementing Azure Entra ID SSO in an Angular standalone application using Microsoft Authentication Library (MSAL). By the end of this tutorial, you’ll have a fully functional SSO implementation that provides secure, user-friendly authentication.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What You’ll Build:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Secure Angular application with Azure Entra ID authentication&lt;/li&gt;
&lt;li&gt;Automatic login redirects and token management&lt;/li&gt;
&lt;li&gt;Protected routes and authentication guards&lt;/li&gt;
&lt;li&gt;Clean user interface with login/logout functionality&lt;/li&gt;
&lt;li&gt;Error handling and user feedback systems&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Prerequisites
&lt;/h3&gt;

&lt;p&gt;Before starting this implementation, ensure you have:&lt;/p&gt;

&lt;h4&gt;
  
  
  Technical Requirements
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Node.js&lt;/strong&gt; (version 16 or higher)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Angular CLI&lt;/strong&gt; (version 15 or higher)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Azure subscription&lt;/strong&gt; with administrative access&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Basic knowledge&lt;/strong&gt; of Angular, TypeScript, and Azure services&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Development Environment
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Verify your setup
node --version
npm --version
ng version
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Azure Permissions
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Azure Entra ID administrative access&lt;/li&gt;
&lt;li&gt;Ability to register applications in Azure portal&lt;/li&gt;
&lt;li&gt;Permission to configure app registrations&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Azure Entra ID Configuration
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Step 1: Access Azure Portal
&lt;/h4&gt;

&lt;ol&gt;
&lt;li&gt;Navigate to &lt;a href="https://portal.azure.com" rel="noopener noreferrer"&gt;Azure Portal&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Sign in with your administrative account&lt;/li&gt;
&lt;li&gt;Search for “Azure Active Directory” or “Entra ID”&lt;/li&gt;
&lt;li&gt;Select &lt;strong&gt;Azure Active Directory&lt;/strong&gt; from the results&lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;
  
  
  Step 2: Register Your Application
&lt;/h4&gt;

&lt;ol&gt;
&lt;li&gt;In the Azure AD overview, click &lt;strong&gt;App registrations&lt;/strong&gt; in the left menu&lt;/li&gt;
&lt;li&gt;Click &lt;strong&gt;+ New registration&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Fill out the registration form as below:&lt;/li&gt;
&lt;li&gt;Click &lt;strong&gt;Register&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Name: MyAngularSSOApp
Supported account types: Accounts in this organizational directory only
Redirect URI:  
- Platform: Single-page application (SPA) 
- URI: http://localhost:4200
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Step 3: Configure Authentication Settings
&lt;/h4&gt;

&lt;p&gt;After registration, you’ll be redirected to your app’s overview page:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Note your Application (client) ID&lt;/strong&gt; — you’ll need this later&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Note your Directory (tenant) ID&lt;/strong&gt; — also required for configuration&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Navigate to &lt;strong&gt;Authentication&lt;/strong&gt; in the left menu:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Under &lt;strong&gt;Platform configurations&lt;/strong&gt; , verify your SPA redirect URI&lt;/li&gt;
&lt;li&gt;Add additional redirect URIs for different environments:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Development: http://localhost:4200 
Staging: https://your-staging-domain.com 
Production: https://your-production-domain.com
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Under &lt;strong&gt;Implicit grant and hybrid flows&lt;/strong&gt; , ensure:&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;✅ &lt;strong&gt;Access tokens&lt;/strong&gt; (for implicit flows)&lt;/li&gt;
&lt;li&gt;✅ &lt;strong&gt;ID tokens&lt;/strong&gt; (for implicit and hybrid flows)&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;Under &lt;strong&gt;Advanced settings&lt;/strong&gt; :&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;✅ &lt;strong&gt;Allow public client flows&lt;/strong&gt; : Yes&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Supported account types&lt;/strong&gt; : Verify correct setting&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Step 4: Configure API Permissions (Optional)
&lt;/h4&gt;

&lt;p&gt;If your application needs to access Microsoft Graph or other APIs:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Go to &lt;strong&gt;API permissions&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Click &lt;strong&gt;+ Add a permission&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Select &lt;strong&gt;Microsoft Graph&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Choose &lt;strong&gt;Delegated permissions&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Add permissions like:&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;User.Read (basic profile info)&lt;/li&gt;
&lt;li&gt;email (email address)&lt;/li&gt;
&lt;li&gt;profile (basic profile)&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;Click &lt;strong&gt;Grant admin consent&lt;/strong&gt; if required&lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;
  
  
  Step 5: Note Configuration Values
&lt;/h4&gt;

&lt;p&gt;Save these values for your Angular configuration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// You'll need these in your Angular app
const azureConfig = {
  clientId: "your-application-client-id",
  authority: "https://login.microsoftonline.com/your-tenant-id",
  redirectUri: "http://localhost:4200"
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Angular Project Setup
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Step 1: Create New Angular Project
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Create a new Angular project
ng new angular-sso-app --routing --style=css --standalone

# Navigate to project directory
cd angular-sso-app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Step 2: Install MSAL Dependencies
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Install Microsoft Authentication Library for Angular
npm install @azure/msal-browser @azure/msal-angular

# Install additional dependencies for HTTP and routing
npm install @angular/common @angular/router @angular/animations
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Step 3: Project Structure Setup
&lt;/h4&gt;

&lt;p&gt;Create the following directory structure:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;src/
├── app/
│ ├── components/
│ │ ├── login/
│ │ ├── home/
│ │ └── profile/
│ ├── guards/
│ ├── services/
│ └── config/

# Create components
ng generate component components/login
ng generate component components/home
ng generate component components/profile

# Create directories
mkdir -p src/app/guards
mkdir -p src/app/services
mkdir -p src/app/config
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  MSAL Implementation
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Step 1: Create MSAL Configuration
&lt;/h4&gt;

&lt;p&gt;Create src/app/config/msal.config.ts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Configuration, BrowserCacheLocation } from '@azure/msal-browser';
export const msalConfig: Configuration = {
  auth: {
    clientId: 'your-application-client-id', // Replace with your client ID
    authority: 'https://login.microsoftonline.com/your-tenant-id', // Replace with your tenant ID
    redirectUri: 'http://localhost:4200',
    postLogoutRedirectUri: 'http://localhost:4200'
  },
  cache: {
    cacheLocation: BrowserCacheLocation.SessionStorage,
    storeAuthStateInCookie: false
  },
  system: {
    loggerOptions: {
      loggerCallback: (level, message, containsPii) =&amp;gt; {
        if (containsPii) return;
        console.log(`MSAL [${level}]: ${message}`);
      },
      piiLoggingEnabled: false
    }
  }
};
export const loginRequest = {
  scopes: ['openid', 'profile', 'User.Read']
};
export const graphConfig = {
  graphMeEndpoint: 'https://graph.microsoft.com/v1.0/me'
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Step 2: Configure Main Application
&lt;/h4&gt;

&lt;p&gt;Update src/main.ts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import 'zone.js';
import { bootstrapApplication } from '@angular/platform-browser';
import { importProvidersFrom } from '@angular/core';
import { RouterModule } from '@angular/router';
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import {
  MsalModule,
  MsalService,
  MsalGuard,
  MsalInterceptor,
  MsalBroadcastService,
  MsalRedirectComponent
} from '@azure/msal-angular';
import { PublicClientApplication, InteractionType } from '@azure/msal-browser';
import { AppComponent } from './app/app';
import { routes } from './app/app.routes';
import { msalConfig, loginRequest } from './app/config/msal.config';

const msalInstance = new PublicClientApplication(msalConfig);

// Initialize MSAL instance before bootstrapping the application
msalInstance.initialize().then(() =&amp;gt; {
  // Handle redirect promise to process any pending redirects
  return msalInstance.handleRedirectPromise();
}).then(() =&amp;gt; {
  bootstrapApplication(AppComponent, {
    providers: [
      importProvidersFrom(
        RouterModule.forRoot(routes),
        HttpClientModule,
        BrowserAnimationsModule,
        MsalModule.forRoot(
          msalInstance,
          {
            interactionType: InteractionType.Redirect,
            authRequest: loginRequest
          },
          {
            interactionType: InteractionType.Redirect,
            protectedResourceMap: new Map([
              ['https://graph.microsoft.com/v1.0/me', ['User.Read']]
            ])
          }
        )
      ),
      {
        provide: HTTP_INTERCEPTORS,
        useClass: MsalInterceptor,
        multi: true
      },
      MsalService,
      MsalGuard,
      MsalBroadcastService
    ]
  }).catch(err =&amp;gt; console.error(err));
}).catch(err =&amp;gt; {
  console.error('MSAL initialization failed:', err);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Step 3: Update App Component
&lt;/h4&gt;

&lt;p&gt;Update src/app/app.ts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Component, OnInit, OnDestroy, Inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet, Router } from '@angular/router';
import { Subject, filter, takeUntil } from 'rxjs';

import {
  MsalService,
  MsalBroadcastService,
  MSAL_GUARD_CONFIG,
  MsalGuardConfiguration,
  MsalRedirectComponent
} from '@azure/msal-angular';
import {
  InteractionStatus,
  PopupRequest,
  RedirectRequest,
  AuthenticationResult,
  EventMessage,
  EventType
} from '@azure/msal-browser';
@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, RouterOutlet],
  template: `
    &amp;lt;div class="app-container"&amp;gt;
      &amp;lt;main class="main-content"&amp;gt;
        &amp;lt;div *ngIf="isLoading" class="loading-spinner"&amp;gt;
          &amp;lt;div class="spinner"&amp;gt;&amp;lt;/div&amp;gt;
          &amp;lt;p&amp;gt;Loading...&amp;lt;/p&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;router-outlet *ngIf="!isLoading"&amp;gt;&amp;lt;/router-outlet&amp;gt;
      &amp;lt;/main&amp;gt;
    &amp;lt;/div&amp;gt;
  `,
  styleUrls: ['./app.css']
})
export class AppComponent implements OnInit, OnDestroy {
  title = 'Angular SSO App';
  isLoggedIn = false;
  userName = '';
  isLoading = true;
  private readonly _destroying$ = new Subject&amp;lt;void&amp;gt;();
  constructor(
    @Inject(MSAL_GUARD_CONFIG) private msalGuardConfig: MsalGuardConfiguration,
    private msalService: MsalService,
    private msalBroadcastService: MsalBroadcastService,
    private router: Router
  ) {}
  ngOnInit(): void {
    this.initializeApp();
    this.setLoginDisplay();
    this.setupEventListeners();

    // Fallback: Clear loading state after 5 seconds if MSAL doesn't respond
    setTimeout(() =&amp;gt; {
      if (this.isLoading) {
        console.log('Timeout reached, clearing loading state');
        this.isLoading = false;
      }
    }, 5000);
  }
  ngOnDestroy(): void {
    this._destroying$.next(undefined);
    this._destroying$.complete();
  }
  private initializeApp(): void {
    console.log('Initializing app...');
    this.msalBroadcastService.inProgress$
      .pipe(
        filter((status: InteractionStatus) =&amp;gt; {
          console.log('MSAL Interaction Status:', status);
          return status === InteractionStatus.None;
        }),
        takeUntil(this._destroying$)
      )
      .subscribe(() =&amp;gt; {
        console.log('MSAL interaction completed, setting loading to false');
        this.setLoginDisplay();
        this.checkAndSetActiveAccount();
        this.isLoading = false;
      });
  }
  private setupEventListeners(): void {
    this.msalBroadcastService.msalSubject$
      .pipe(
        filter((msg: EventMessage) =&amp;gt; msg.eventType === EventType.LOGIN_SUCCESS),
        takeUntil(this._destroying$)
      )
      .subscribe((result: EventMessage) =&amp;gt; {
        console.log('Login successful');
        this.checkAndSetActiveAccount();
      });
  }
  private setLoginDisplay(): void {
    this.isLoggedIn = this.msalService.instance.getAllAccounts().length &amp;gt; 0;
    if (this.isLoggedIn) {
      const account = this.msalService.instance.getAllAccounts()[0];
      this.userName = account.name || account.username || 'User';
    }
  }
  private checkAndSetActiveAccount(): void {
    const accounts = this.msalService.instance.getAllAccounts();
    if (accounts.length === 0) {
      return;
    }

    if (accounts.length &amp;gt; 1) {
      const currentAccounts = accounts.filter(account =&amp;gt;
        account.homeAccountId.toUpperCase().includes('B2C_1_SUSI'.toUpperCase()) ||
        account.homeAccountId.toUpperCase().includes('B2C_1_EDIT_PROFILE'.toUpperCase())
      );
      if (currentAccounts.length &amp;gt; 1) {
        this.msalService.instance.setActiveAccount(currentAccounts[0]);
      } else if (currentAccounts.length === 1) {
        this.msalService.instance.setActiveAccount(currentAccounts[0]);
      } else {
        this.msalService.instance.setActiveAccount(accounts[0]);
      }
    } else {
      this.msalService.instance.setActiveAccount(accounts[0]);
    }
  }
  login(): void {
    if (this.msalGuardConfig.authRequest) {
      this.msalService.loginRedirect({
        ...this.msalGuardConfig.authRequest
      } as RedirectRequest);
    } else {
      this.msalService.loginRedirect();
    }
  }
  logout(): void {
    this.msalService.logoutRedirect({
      postLogoutRedirectUri: 'http://localhost:4200'
    });
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Authentication Service
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Step 1: Create Authentication Service
&lt;/h4&gt;

&lt;p&gt;Create src/app/services/auth.service.ts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable, Inject } from '@angular/core';
import { Observable, BehaviorSubject, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

import {
  MsalService,
  MsalBroadcastService,
  MSAL_GUARD_CONFIG,
  MsalGuardConfiguration
} from '@azure/msal-angular';
import {
  AccountInfo,
  AuthenticationResult,
  PopupRequest,
  RedirectRequest,
  SilentRequest,
  InteractionStatus
} from '@azure/msal-browser';
import { graphConfig } from '../config/msal.config';
export interface UserProfile {
  id: string;
  name: string;
  email: string;
  jobTitle?: string;
  department?: string;
}
@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private userProfileSubject = new BehaviorSubject&amp;lt;UserProfile | null&amp;gt;(null);
  public userProfile$ = this.userProfileSubject.asObservable();
  constructor(
    @Inject(MSAL_GUARD_CONFIG) private msalGuardConfig: MsalGuardConfiguration,
    private msalService: MsalService,
    private msalBroadcastService: MsalBroadcastService,
    private http: HttpClient
  ) {
    this.initializeUser();
  }
  private initializeUser(): void {
    const account = this.msalService.instance.getActiveAccount();
    if (account) {
      this.fetchUserProfile().subscribe();
    }
  }
  /**
   * Check if user is currently authenticated
   */
  isAuthenticated(): boolean {
    return this.msalService.instance.getAllAccounts().length &amp;gt; 0;
  }
  /**
   * Get current user account information
   */
  getCurrentUser(): AccountInfo | null {
    return this.msalService.instance.getActiveAccount();
  }
  /**
   * Check if an interaction is currently in progress
   */
  private isInteractionInProgress(): boolean {
    try {
      // Try to get the interaction status from MSAL's internal state
      const interactionStatus = this.msalService.instance.getActiveAccount();
      // Check if there's an ongoing interaction by looking for interaction-related cache entries
      return false; // For now, let the MSAL service handle the check
    } catch (error) {
      return false;
    }
  }

  /**
   * Perform login using redirect
   */
  loginRedirect(): void {
    try {
      if (this.msalGuardConfig.authRequest) {
        this.msalService.loginRedirect({
          ...this.msalGuardConfig.authRequest
        } as RedirectRequest);
      } else {
        this.msalService.loginRedirect();
      }
    } catch (error: any) {
      if (error.name === 'BrowserAuthError' &amp;amp;&amp;amp; error.errorCode === 'interaction_in_progress') {
        console.log('Login interaction already in progress, please wait...');
        return;
      }
      console.error('Login failed:', error);
      throw error;
    }
  }
  /**
   * Perform login using popup
   */
  loginPopup(): Observable&amp;lt;AuthenticationResult&amp;gt; {
    if (this.msalGuardConfig.authRequest) {
      return this.msalService.loginPopup({
        ...this.msalGuardConfig.authRequest
      } as PopupRequest);
    } else {
      return this.msalService.loginPopup();
    }
  }
  /**
   * Perform logout
   */
  logout(): void {
    this.userProfileSubject.next(null);
    this.msalService.logoutRedirect({
      postLogoutRedirectUri: 'http://localhost:4200'
    });
  }
  /**
   * Get access token silently
   */
  getAccessToken(): Observable&amp;lt;string&amp;gt; {
    const account = this.msalService.instance.getActiveAccount();
    if (!account) {
      return of('');
    }
    const request: SilentRequest = {
      scopes: ['User.Read'],
      account: account
    };
    return this.msalService.acquireTokenSilent(request).pipe(
      map(result =&amp;gt; result.accessToken),
      catchError(error =&amp;gt; {
        console.error('Token acquisition failed:', error);
        return of('');
      })
    );
  }
  /**
   * Fetch user profile from Microsoft Graph
   */
  fetchUserProfile(): Observable&amp;lt;UserProfile | null&amp;gt; {
    if (!this.isAuthenticated()) {
      return of(null);
    }
    return this.http.get(graphConfig.graphMeEndpoint).pipe(
      map((profile: any) =&amp;gt; {
        const userProfile: UserProfile = {
          id: profile.id,
          name: profile.displayName || profile.name,
          email: profile.mail || profile.userPrincipalName,
          jobTitle: profile.jobTitle,
          department: profile.department
        };
        this.userProfileSubject.next(userProfile);
        return userProfile;
      }),
      catchError(error =&amp;gt; {
        console.error('Failed to fetch user profile:', error);
        return of(null);
      })
    );
  }
  /**
   * Check if user has specific roles or permissions
   */
  hasRole(role: string): boolean {
    const account = this.getCurrentUser();
    if (!account || !account.idTokenClaims) {
      return false;
    }

    // Implement role checking logic based on your token claims
    const roles = (account.idTokenClaims as any)?.roles || [];
    return roles.includes(role);
  }
  /**
   * Get user's groups from token claims
   */
  getUserGroups(): string[] {
    const account = this.getCurrentUser();
    if (!account || !account.idTokenClaims) {
      return [];
    }

    return (account.idTokenClaims as any)?.groups || [];
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Route Protection
&lt;/h4&gt;

&lt;h4&gt;
  
  
  Step 1: Create Authentication Guard
&lt;/h4&gt;

&lt;p&gt;Create src/app/guards/auth.guard.ts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { map, take } from 'rxjs/operators';

import { MsalService, MsalBroadcastService } from '@azure/msal-angular';
import { InteractionStatus } from '@azure/msal-browser';
@Injectable({
  providedIn: 'root'
})
export class AuthGuard {
  constructor(
    private msalService: MsalService,
    private msalBroadcastService: MsalBroadcastService,
    private router: Router
  ) {}
  canActivate(): Observable&amp;lt;boolean&amp;gt; | boolean {
    return this.msalBroadcastService.inProgress$.pipe(
      map((status: InteractionStatus) =&amp;gt; {
        if (status === InteractionStatus.None) {
          const isAuthenticated = this.msalService.instance.getAllAccounts().length &amp;gt; 0;

          if (!isAuthenticated) {
            // Redirect to login
            this.msalService.loginRedirect();
            return false;
          }

          return true;
        }

        // Still processing authentication
        return false;
      }),
      take(1)
    );
  }
  canActivateChild(): Observable&amp;lt;boolean&amp;gt; | boolean {
    return this.canActivate();
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Step 2: Create Role-Based Guard
&lt;/h4&gt;

&lt;p&gt;Create src/app/guards/role.guard.ts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable } from '@angular/core';
import { Router, ActivatedRouteSnapshot } from '@angular/router';
import { Observable, of } from 'rxjs';

import { AuthService } from '../services/auth.service';
@Injectable({
  providedIn: 'root'
})
export class RoleGuard {
  constructor(
    private authService: AuthService,
    private router: Router
  ) {}
  canActivate(route: ActivatedRouteSnapshot): Observable&amp;lt;boolean&amp;gt; | boolean {
    const requiredRoles = route.data['roles'] as string[];

    if (!requiredRoles || requiredRoles.length === 0) {
      return true;
    }
    if (!this.authService.isAuthenticated()) {
      this.router.navigate(['/login']);
      return false;
    }
    const hasRequiredRole = requiredRoles.some(role =&amp;gt; 
      this.authService.hasRole(role)
    );
    if (!hasRequiredRole) {
      this.router.navigate(['/unauthorized']);
      return false;
    }
    return true;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Step 3: Configure Routes
&lt;/h4&gt;

&lt;p&gt;Create src/app/app.routes.ts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Routes } from '@angular/router';
import { MsalGuard } from '@azure/msal-angular';

import { Home } from './components/home/home';
import { Login } from './components/login/login';
import { Profile } from './components/profile/profile';
import { AuthGuard } from './guards/auth.guard';
import { RoleGuard } from './guards/role.guard';
export const routes: Routes = [
  {
    path: '',
    redirectTo: '/home',
    pathMatch: 'full'
  },
  {
    path: 'home',
    component: Home
  },
  {
    path: 'login',
    component: Login
  },
  {
    path: 'profile',
    component: Profile,
    canActivate: [MsalGuard]
  },
  {
    path: '**',
    redirectTo: '/home'
  }
];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  User Interface Integration
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Step 1: Create Home Component
&lt;/h4&gt;

&lt;p&gt;Update src/app/components/home/home.ts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { Subject, takeUntil, filter } from 'rxjs';

import { AuthService, UserProfile } from '../../services/auth.service';
import { MsalBroadcastService } from '@azure/msal-angular';
import { InteractionStatus, EventType, EventMessage } from '@azure/msal-browser';
@Component({
  selector: 'app-home',
  standalone: true,
  imports: [CommonModule, RouterModule],
  template: `
    &amp;lt;div class="home-container"&amp;gt;
      &amp;lt;div class="hero-section"&amp;gt;
        &amp;lt;h1&amp;gt;Welcome to My SSO App&amp;lt;/h1&amp;gt;
        &amp;lt;p class="lead"&amp;gt;Secure authentication with Azure Entra ID&amp;lt;/p&amp;gt;

        &amp;lt;div *ngIf="!isAuthenticated" class="auth-prompt"&amp;gt;
          &amp;lt;p&amp;gt;Please sign in to access your personalized dashboard&amp;lt;/p&amp;gt;
          &amp;lt;button
            (click)="login()"
            [disabled]="isLoggingIn"
            class="btn btn-primary btn-lg"&amp;gt;
            &amp;lt;span *ngIf="!isLoggingIn"&amp;gt;Sign In with Microsoft&amp;lt;/span&amp;gt;
            &amp;lt;span *ngIf="isLoggingIn"&amp;gt;Signing In...&amp;lt;/span&amp;gt;
          &amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;div *ngIf="isAuthenticated" class="welcome-user"&amp;gt;
          &amp;lt;h2&amp;gt;Hello, {{userProfile?.name}}!&amp;lt;/h2&amp;gt;
          &amp;lt;p&amp;gt;You are successfully authenticated&amp;lt;/p&amp;gt;
          &amp;lt;div class="user-actions"&amp;gt;
            &amp;lt;a routerLink="/profile" class="btn btn-outline-primary"&amp;gt;
              View Profile
            &amp;lt;/a&amp;gt;
            &amp;lt;button (click)="logout()" class="btn btn-outline-secondary"&amp;gt;
              Sign Out
            &amp;lt;/button&amp;gt;
          &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;div *ngIf="isAuthenticated" class="dashboard-section"&amp;gt;
        &amp;lt;h3&amp;gt;Quick Actions&amp;lt;/h3&amp;gt;
        &amp;lt;div class="action-cards"&amp;gt;
          &amp;lt;div class="card"&amp;gt;
            &amp;lt;h4&amp;gt;Profile&amp;lt;/h4&amp;gt;
            &amp;lt;p&amp;gt;View and manage your profile information&amp;lt;/p&amp;gt;
            &amp;lt;a routerLink="/profile" class="btn btn-primary"&amp;gt;Go to Profile&amp;lt;/a&amp;gt;
          &amp;lt;/div&amp;gt;

          &amp;lt;div class="card"&amp;gt;
            &amp;lt;h4&amp;gt;Settings&amp;lt;/h4&amp;gt;
            &amp;lt;p&amp;gt;Configure your application preferences&amp;lt;/p&amp;gt;
            &amp;lt;a routerLink="/settings" class="btn btn-primary"&amp;gt;Settings&amp;lt;/a&amp;gt;
          &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  `,
  styleUrls: ['./home.css']
})
export class Home implements OnInit, OnDestroy {
  isAuthenticated = false;
  isLoggingIn = false;
  userProfile: UserProfile | null = null;
  private readonly _destroying$ = new Subject&amp;lt;void&amp;gt;();

  constructor(
    private authService: AuthService,
    private msalBroadcastService: MsalBroadcastService
  ) {}
  ngOnInit(): void {
    this.checkAuthentication();
    this.setupEventListeners();
  }

  ngOnDestroy(): void {
    this._destroying$.next(undefined);
    this._destroying$.complete();
  }

  private checkAuthentication(): void {
    this.isAuthenticated = this.authService.isAuthenticated();

    if (this.isAuthenticated) {
      this.authService.userProfile$.subscribe(profile =&amp;gt; {
        this.userProfile = profile;
      });

      // Fetch fresh profile data
      this.authService.fetchUserProfile().subscribe();
    }
  }

  private setupEventListeners(): void {
    // Listen for login success events
    this.msalBroadcastService.msalSubject$
      .pipe(
        filter((msg: EventMessage) =&amp;gt; msg.eventType === EventType.LOGIN_SUCCESS),
        takeUntil(this._destroying$)
      )
      .subscribe((result: EventMessage) =&amp;gt; {
        console.log('Login successful');
        this.isLoggingIn = false;
        this.checkAuthentication();
      });

    // Listen for login failure events
    this.msalBroadcastService.msalSubject$
      .pipe(
        filter((msg: EventMessage) =&amp;gt; msg.eventType === EventType.LOGIN_FAILURE),
        takeUntil(this._destroying$)
      )
      .subscribe((result: EventMessage) =&amp;gt; {
        console.log('Login failed');
        this.isLoggingIn = false;
      });

    // Listen for interaction status changes
    this.msalBroadcastService.inProgress$
      .pipe(
        filter((status: InteractionStatus) =&amp;gt; status === InteractionStatus.None),
        takeUntil(this._destroying$)
      )
      .subscribe(() =&amp;gt; {
        this.isLoggingIn = false;
        this.checkAuthentication();
      });
  }
  login(): void {
    if (this.isLoggingIn) {
      return; // Prevent multiple login attempts
    }

    this.isLoggingIn = true;
    try {
      this.authService.loginRedirect();
    } catch (error) {
      console.error('Login error:', error);
      this.isLoggingIn = false;
    }
  }
  logout(): void {
    this.authService.logout();
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Step 2: Create Profile Component
&lt;/h4&gt;

&lt;p&gt;Create src/app/components/profile/profile.ts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';

import { AuthService, UserProfile } from '../../services/auth.service';
@Component({
  selector: 'app-profile',
  standalone: true,
  imports: [CommonModule],
  template: `
    &amp;lt;div class="profile-container"&amp;gt;
      &amp;lt;div class="profile-header"&amp;gt;
        &amp;lt;h1&amp;gt;User Profile&amp;lt;/h1&amp;gt;
        &amp;lt;p&amp;gt;Your account information from Azure Entra ID&amp;lt;/p&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;div *ngIf="loading" class="loading"&amp;gt;
        &amp;lt;div class="spinner"&amp;gt;&amp;lt;/div&amp;gt;
        &amp;lt;p&amp;gt;Loading profile...&amp;lt;/p&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;div *ngIf="userProfile &amp;amp;&amp;amp; !loading" class="profile-content"&amp;gt;
        &amp;lt;div class="profile-card"&amp;gt;
          &amp;lt;div class="profile-avatar"&amp;gt;
            &amp;lt;div class="avatar-placeholder"&amp;gt;
              {{getInitials(userProfile.name)}}
            &amp;lt;/div&amp;gt;
          &amp;lt;/div&amp;gt;

          &amp;lt;div class="profile-info"&amp;gt;
            &amp;lt;h2&amp;gt;{{userProfile.name}}&amp;lt;/h2&amp;gt;
            &amp;lt;p class="email"&amp;gt;{{userProfile.email}}&amp;lt;/p&amp;gt;

            &amp;lt;div class="profile-details"&amp;gt;
              &amp;lt;div class="detail-row" *ngIf="userProfile.jobTitle"&amp;gt;
                &amp;lt;strong&amp;gt;Job Title:&amp;lt;/strong&amp;gt;
                &amp;lt;span&amp;gt;{{userProfile.jobTitle}}&amp;lt;/span&amp;gt;
              &amp;lt;/div&amp;gt;

              &amp;lt;div class="detail-row" *ngIf="userProfile.department"&amp;gt;
                &amp;lt;strong&amp;gt;Department:&amp;lt;/strong&amp;gt;
                &amp;lt;span&amp;gt;{{userProfile.department}}&amp;lt;/span&amp;gt;
              &amp;lt;/div&amp;gt;

              &amp;lt;div class="detail-row"&amp;gt;
                &amp;lt;strong&amp;gt;User ID:&amp;lt;/strong&amp;gt;
                &amp;lt;span&amp;gt;{{userProfile.id}}&amp;lt;/span&amp;gt;
              &amp;lt;/div&amp;gt;
            &amp;lt;/div&amp;gt;
          &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;div class="profile-actions"&amp;gt;
          &amp;lt;button (click)="refreshProfile()" class="btn btn-primary"&amp;gt;
            Refresh Profile
          &amp;lt;/button&amp;gt;
          &amp;lt;button (click)="logout()" class="btn btn-outline-danger"&amp;gt;
            Sign Out
          &amp;lt;/button&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
      &amp;lt;div *ngIf="!userProfile &amp;amp;&amp;amp; !loading" class="error-state"&amp;gt;
        &amp;lt;h3&amp;gt;Unable to load profile&amp;lt;/h3&amp;gt;
        &amp;lt;p&amp;gt;There was an error loading your profile information.&amp;lt;/p&amp;gt;
        &amp;lt;button (click)="refreshProfile()" class="btn btn-primary"&amp;gt;
          Try Again
        &amp;lt;/button&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  `,
  styleUrls: ['./profile.css']
})
export class Profile implements OnInit {
  userProfile: UserProfile | null = null;
  loading = true;
  constructor(private authService: AuthService) {}
  ngOnInit(): void {
    this.loadProfile();
  }
  loadProfile(): void {
    this.loading = true;

    this.authService.userProfile$.subscribe(profile =&amp;gt; {
      this.userProfile = profile;
      this.loading = false;
    });
    this.authService.fetchUserProfile().subscribe({
      error: (error) =&amp;gt; {
        console.error('Failed to load profile:', error);
        this.loading = false;
      }
    });
  }
  refreshProfile(): void {
    this.loadProfile();
  }
  logout(): void {
    this.authService.logout();
  }
  getInitials(name: string): string {
    return name
      .split(' ')
      .map(n =&amp;gt; n[0])
      .join('')
      .toUpperCase()
      .substring(0, 2);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Step 3: Create Login Component
&lt;/h4&gt;

&lt;p&gt;Create src/app/components/login/login.ts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router } from '@angular/router';

import { AuthService } from '../../services/auth.service';
@Component({
  selector: 'app-login',
  standalone: true,
  imports: [CommonModule],
  template: `
    &amp;lt;div class="login-container"&amp;gt;
      &amp;lt;div class="login-card"&amp;gt;
        &amp;lt;div class="login-header"&amp;gt;
          &amp;lt;h1&amp;gt;Sign In&amp;lt;/h1&amp;gt;
          &amp;lt;p&amp;gt;Access your account with Microsoft SSO&amp;lt;/p&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;div *ngIf="!isAuthenticated" class="login-content"&amp;gt;
          &amp;lt;div class="login-illustration"&amp;gt;
            &amp;lt;div class="microsoft-logo"&amp;gt;
              &amp;lt;svg width="48" height="48" viewBox="0 0 48 48"&amp;gt;
                &amp;lt;path fill="#f25022" d="M0 0h23v23H0z"/&amp;gt;
                &amp;lt;path fill="#00a4ef" d="M25 0h23v23H25z"/&amp;gt;
                &amp;lt;path fill="#7fba00" d="M0 25h23v23H0z"/&amp;gt;
                &amp;lt;path fill="#ffb900" d="M25 25h23v23H25z"/&amp;gt;
              &amp;lt;/svg&amp;gt;
            &amp;lt;/div&amp;gt;
          &amp;lt;/div&amp;gt;
          &amp;lt;div class="login-form"&amp;gt;
            &amp;lt;button
              (click)="login()"
              class="btn btn-microsoft"
              [disabled]="isLoading"&amp;gt;
              &amp;lt;span *ngIf="!isLoading"&amp;gt;Sign in with Microsoft&amp;lt;/span&amp;gt;
              &amp;lt;span *ngIf="isLoading"&amp;gt;Signing in...&amp;lt;/span&amp;gt;
            &amp;lt;/button&amp;gt;

            &amp;lt;div class="login-benefits"&amp;gt;
              &amp;lt;h3&amp;gt;Benefits of signing in:&amp;lt;/h3&amp;gt;
              &amp;lt;ul&amp;gt;
                &amp;lt;li&amp;gt;✓ Secure authentication&amp;lt;/li&amp;gt;
                &amp;lt;li&amp;gt;✓ Single sign-on across apps&amp;lt;/li&amp;gt;
                &amp;lt;li&amp;gt;✓ Access to personalized features&amp;lt;/li&amp;gt;
                &amp;lt;li&amp;gt;✓ Automatic session management&amp;lt;/li&amp;gt;
              &amp;lt;/ul&amp;gt;
            &amp;lt;/div&amp;gt;
          &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
        &amp;lt;div *ngIf="isAuthenticated" class="already-signed-in"&amp;gt;
          &amp;lt;div class="success-icon"&amp;gt;✓&amp;lt;/div&amp;gt;
          &amp;lt;h2&amp;gt;You're already signed in!&amp;lt;/h2&amp;gt;
          &amp;lt;p&amp;gt;Redirecting to your dashboard...&amp;lt;/p&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  `,
  styleUrls: ['./login.css']
})
export class Login implements OnInit {
  isAuthenticated = false;
  isLoading = false;
  constructor(
    private authService: AuthService,
    private router: Router
  ) {}
  ngOnInit(): void {
    this.isAuthenticated = this.authService.isAuthenticated();

    if (this.isAuthenticated) {
      // Redirect authenticated users to home
      setTimeout(() =&amp;gt; {
        this.router.navigate(['/home']);
      }, 2000);
    }
  }
  login(): void {
    this.isLoading = true;
    this.authService.loginRedirect();
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Testing and Troubleshooting
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Step 1: Basic Testing
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Start development server
ng serve

# Open browser to http://localhost:4200
# Test authentication flow
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Step 2: Common Issues and Solutions
&lt;/h4&gt;

&lt;h4&gt;
  
  
  Issue 1: Redirect URI Mismatch
&lt;/h4&gt;

&lt;p&gt;&lt;strong&gt;Error:&lt;/strong&gt; AADSTS50011: The reply URL specified in the request does not match the reply URLs configured for the application&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Verify redirect URI in Azure portal matches exactly&lt;/li&gt;
&lt;li&gt;Check for trailing slashes or case sensitivity&lt;/li&gt;
&lt;li&gt;Ensure SPA platform is selected (not Web)&lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;
  
  
  Issue 3: CORS Issues
&lt;/h4&gt;

&lt;p&gt;&lt;strong&gt;Error:&lt;/strong&gt; Access to fetch at '&lt;a href="https://login.microsoftonline.com/.." rel="noopener noreferrer"&gt;https://login.microsoftonline.com/..&lt;/a&gt;.' from origin '&lt;a href="http://localhost:4200" rel="noopener noreferrer"&gt;http://localhost:4200&lt;/a&gt;' has been blocked by CORS policy&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Ensure you’re using SPA (Single Page Application) configuration&lt;/li&gt;
&lt;li&gt;Verify MSAL configuration is correct&lt;/li&gt;
&lt;li&gt;Check browser developer tools for specific error details&lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;
  
  
  Issue 3: Token Issues
&lt;/h4&gt;

&lt;p&gt;&lt;strong&gt;Error:&lt;/strong&gt; InteractionRequiredAuthError or Token acquisition failed&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Add error handling in your service
getAccessToken(): Observable&amp;lt;string&amp;gt; {
  const account = this.msalService.instance.getActiveAccount();
  if (!account) {
    return of('');
  }

  const request: SilentRequest = {
    scopes: ['User.Read'],
    account: account
  };
  return this.msalService.acquireTokenSilent(request).pipe(
    map(result =&amp;gt; result.accessToken),
    catchError(error =&amp;gt; {
      console.error('Silent token acquisition failed:', error);
      // Try interactive token acquisition
      return this.msalService.acquireTokenPopup(request).pipe(
        map(result =&amp;gt; result.accessToken),
        catchError(popupError =&amp;gt; {
          console.error('Popup token acquisition failed:', popupError);
          return of('');
        })
      );
    })
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 3: Debugging Tools
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Enable MSAL Logging
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// In msal.config.ts
export const msalConfig: Configuration = {
  // ... other config
  system: {
    loggerOptions: {
      loggerCallback: (level, message, containsPii) =&amp;gt; {
        if (containsPii) return;
        console.log(`MSAL [${level}]: ${message}`);
      },
      piiLoggingEnabled: false,
      logLevel: LogLevel.Verbose // Enable verbose logging
    }
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Browser Developer Tools
&lt;/h4&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Network Tab:&lt;/strong&gt; Check for failed requests to Microsoft endpoints&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Console Tab:&lt;/strong&gt; Look for MSAL error messages&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Application Tab:&lt;/strong&gt; Inspect stored tokens in Session/Local Storage&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Step 4: Testing Checklist
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;[] Login redirect works correctly&lt;/li&gt;
&lt;li&gt;[] User can access protected routes after authentication&lt;/li&gt;
&lt;li&gt;[] Logout clears session and redirects properly&lt;/li&gt;
&lt;li&gt;[] Token refresh works automatically&lt;/li&gt;
&lt;li&gt;[] Profile information displays correctly&lt;/li&gt;
&lt;li&gt;[] Error handling works for network issues&lt;/li&gt;
&lt;li&gt;[] Authentication guards protect routes properly&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Best Practices
&lt;/h3&gt;

&lt;h3&gt;
  
  
  Security Best Practices
&lt;/h3&gt;

&lt;h4&gt;
  
  
  1. Token Storage
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Use sessionStorage for better security
export const msalConfig: Configuration = {
  cache: {
    cacheLocation: BrowserCacheLocation.SessionStorage, // More secure than localStorage
    storeAuthStateInCookie: false // Set to true only if needed for IE11
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  2. Scope Management
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Request minimal scopes needed
export const loginRequest = {
  scopes: ['openid', 'profile', 'User.Read'] // Only what you need
};

// Request additional scopes when needed
private requestAdditionalScopes(scopes: string[]): Observable&amp;lt;string&amp;gt; {
  const account = this.msalService.instance.getActiveAccount();
  const request = {
    scopes: scopes,
    account: account
  };

  return this.msalService.acquireTokenSilent(request).pipe(
    map(result =&amp;gt; result.accessToken)
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  3. Error Handling
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Comprehensive error handling
private handleAuthError(error: any): void {
  if (error.errorCode === 'user_cancelled') {
    console.log('User cancelled authentication');
    return;
  }

  if (error.errorCode === 'consent_required') {
    // Handle consent required
    this.msalService.acquireTokenPopup(this.loginRequest);
    return;
  }

  console.error('Authentication error:', error);
  // Show user-friendly error message
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Performance Best Practices
&lt;/h3&gt;

&lt;h4&gt;
  
  
  1. Lazy Loading
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Use lazy loading for non-critical routes
const routes: Routes = [
  {
    path: 'admin',
    loadComponent: () =&amp;gt; import('./admin/admin.component').then(m =&amp;gt; m.AdminComponent),
    canActivate: [MsalGuard]
  }
];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  2. Caching Strategy
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Cache user profile to avoid repeated API calls
private userProfileCache: UserProfile | null = null;
private profileCacheExpiry: number = 0;

fetchUserProfile(): Observable&amp;lt;UserProfile | null&amp;gt; {
  const now = Date.now();

  // Return cached profile if still valid (5 minutes)
  if (this.userProfileCache &amp;amp;&amp;amp; now &amp;lt; this.profileCacheExpiry) {
    return of(this.userProfileCache);
  }

  return this.http.get(graphConfig.graphMeEndpoint).pipe(
    map((profile: any) =&amp;gt; {
      this.userProfileCache = this.mapProfile(profile);
      this.profileCacheExpiry = now + (5 * 60 * 1000); // 5 minutes
      return this.userProfileCache;
    })
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Accessibility Best Practices
&lt;/h3&gt;

&lt;h4&gt;
  
  
  1. ARIA Labels
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!-- Add proper ARIA labels for authentication states --&amp;gt;
&amp;lt;button 
  (click)="login()" 
  [attr.aria-label]="isLoading ? 'Signing in, please wait' : 'Sign in with Microsoft'"
  [disabled]="isLoading"&amp;gt;
  Sign In
&amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  2. Loading States
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!-- Provide clear loading feedback --&amp;gt;
&amp;lt;div *ngIf="isLoading" 
     role="status" 
     aria-live="polite"
     class="loading-spinner"&amp;gt;
  &amp;lt;span class="sr-only"&amp;gt;Loading authentication...&amp;lt;/span&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Monitoring and Analytics
&lt;/h3&gt;

&lt;h4&gt;
  
  
  1. Authentication Events
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Track authentication events
private trackAuthEvent(event: string, data?: any): void {
  // Send to your analytics service
  console.log('Auth Event:', event, data);

  // Example with Application Insights
  // this.applicationInsights.trackEvent(event, data);
}
// Use in authentication flows
login(): void {
  this.trackAuthEvent('login_attempt');
  this.msalService.loginRedirect();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  2. Error Tracking
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Track authentication errors
private trackAuthError(error: any): void {
  const errorData = {
    errorCode: error.errorCode,
    errorMessage: error.message,
    timestamp: new Date().toISOString()
  };

  // Send to error tracking service
  console.error('Auth Error:', errorData);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;You’ve successfully implemented Azure Entra ID SSO in your Angular standalone application! This comprehensive implementation provides:&lt;/p&gt;

&lt;h3&gt;
  
  
  What You’ve Accomplished
&lt;/h3&gt;

&lt;p&gt;✅ &lt;strong&gt;Secure Authentication:&lt;/strong&gt; Users can sign in with their Microsoft credentials&lt;/p&gt;

&lt;p&gt;✅ &lt;strong&gt;Route Protection:&lt;/strong&gt; Sensitive areas are protected by authentication guards ✅ &lt;strong&gt;Token Management:&lt;/strong&gt; Automatic token refresh and secure storage&lt;/p&gt;

&lt;p&gt;✅ &lt;strong&gt;User Profile Integration:&lt;/strong&gt; Access to user information from Microsoft Graph&lt;/p&gt;

&lt;p&gt;✅ &lt;strong&gt;Error Handling:&lt;/strong&gt; Comprehensive error handling and user feedback&lt;/p&gt;

&lt;p&gt;✅ &lt;strong&gt;Best Practices:&lt;/strong&gt; Security, performance, and accessibility considerations&lt;/p&gt;

&lt;h3&gt;
  
  
  Next Steps
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;1. Production Deployment:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Update redirect URIs for production environment&lt;/li&gt;
&lt;li&gt;Configure proper HTTPS certificates&lt;/li&gt;
&lt;li&gt;Set up monitoring and logging&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. Enhanced Features:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Implement role-based access control&lt;/li&gt;
&lt;li&gt;Add multi-tenant support if needed&lt;/li&gt;
&lt;li&gt;Integrate with Microsoft Graph APIs&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;3. Testing:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Add unit tests for authentication service&lt;/li&gt;
&lt;li&gt;Implement e2e tests for authentication flows&lt;/li&gt;
&lt;li&gt;Test with different user scenarios&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Additional Resources
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-overview" rel="noopener noreferrer"&gt;Microsoft Authentication Library (MSAL) Documentation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.microsoft.com/en-us/azure/active-directory/" rel="noopener noreferrer"&gt;Azure Entra ID Documentation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.microsoft.com/en-us/graph/" rel="noopener noreferrer"&gt;Microsoft Graph API Documentation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://angular.io/guide/security" rel="noopener noreferrer"&gt;Angular Security Best Practices&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Support and Community
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://stackoverflow.com/questions/tagged/azure-ad-msal" rel="noopener noreferrer"&gt;Stack Overflow — azure-ad-msal&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://techcommunity.microsoft.com/t5/microsoft-identity-platform/ct-p/MicrosoftIdentityPlatform" rel="noopener noreferrer"&gt;Microsoft Identity Platform Community&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/AzureAD/microsoft-authentication-library-for-js" rel="noopener noreferrer"&gt;MSAL.js GitHub Repository&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Happy coding! 🚀&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;This guide provides a solid foundation for implementing Azure Entra ID SSO in Angular applications. Remember to keep your dependencies updated and follow Microsoft’s latest security recommendations.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>vikashgyan</category>
      <category>azureentraidsso</category>
      <category>ssosinglesignonporta</category>
      <category>msalangular</category>
    </item>
  </channel>
</rss>
