# 20) Browser APIs

1.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">fetch API</mark>**  
    The Fetch API is the modern way to make HTTP requests in JavaScript. It’s a browser-provided API that lets you communicate with servers (APIs, backends) in a clean, promise-based way.  
    What is Fetch API?  
    The Fetch API allows you to: Get data from a server (GET) Send data (POST, PUT, DELETE) Work with APIs asynchronously.  
    **i) GET Request**
    
    ```javascript
    fetch("https://api.example.com/users")
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(err => console.error(err));
    ```
    
    fetch() sends request  
    Returns a Promise response.json()  
    parses JSON  
    You get actual data  
    **ii) POST Request**
    
    ```javascript
    fetch("https://api.example.com/users", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        name: "Rahul",
        age: 25
      })
    })
    .then(res => res.json())
    .then(data => console.log(data));
    ```
    
    **iii) Handling Authentication**
    
    ```javascript
    fetch(url, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
    ```
    
    **iv) CORS Issues**  
    Happens when frontend & backend are on different domains  
    Must be handled by backend  
    **v) Real world example**
    
    ```javascript
    async function fetchUser() {
      try {
        const res = await fetch("https://api.example.com/user/1");
    
        if (!res.ok) {
          throw new Error("Failed request");
        }
    
        const user = await res.json();
        console.log(user);
    
        localStorage.setItem("user", JSON.stringify(user));
      } catch (err) {
        console.error("Error:", err);
      }
    }
    ```
    
    Fetch API is used for HTTP requests  
    Returns a Promise  
    Works great with async/await  
    Does not auto-handle HTTP errors  
    Essential for React / frontend apps
    
2.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">Axios</mark>**
    
3.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">localStorage and sessionStorage</mark>**  
    localStorage and sessionStorage are part of the Web Storage API, a browser feature that lets you store data directly on the client (user’s browser).  
    Both are **client-side storage APIs**  
    `localStorage` → persistent  
    `sessionStorage` → temporary (per tab)  
    Store only **strings**  
    Be careful with **security**  
    **i) localStorage**  
    Stores data **permanently** (until manually cleared)
    
    ```javascript
    localStorage.setItem("name", "Rahul");
    
    const name = localStorage.getItem("name");
    console.log(name); // Rahul
    ```
    
    No expiration  
    Persists even after browser restart  
    Shared across tabs (same origin)  
    **ii) sessionStorage**  
    Stores data only for a session  
    A session = until the tab is closed
    
    ```javascript
    sessionStorage.setItem("token", "12345");
    
    const token = sessionStorage.getItem("token");
    ```
    
    Data is cleared when tab is closed  
    Not shared between tabs  
    Exists only during session  
    **iii) Common Methods**
    
    ```javascript
    // set Data
    storage.setItem("key", "value");
    
    // get Data
    storage.getItem("key");
    
    // remove Item
    storage.removeItem("key");
    
    // clear All
    storage.clear();
    ```
    
    **iv) Important Notes**  
    Only stores strings  
    Synchronous API  
    Same-Origin Policy  
    **v) Real-World Use Cases**  
    localStorage - Theme (dark/light mode), Language preference, Remember user settings  
    sessionStorage - Form data (temporary), Multi-step form state, Session-specific info
    
4.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">Cookies vs localStorage vs sessionStorage</mark>**  
    i) Cookies -  
    Small pieces of data stored in the browser and **automatically sent with every HTTP request**.  
    Can be accessed by **server & client**  
    Supports **expiration date**  
    Used for **authentication, sessions**
    
    ii) localStorage -  
    Stores data **permanently in the browser.**  
    No expiration  
    Not sent to server  
    Shared across tabs
    
    iii) sessionStorage -  
    Stores data **temporarily (per tab session)**  
    Cleared when tab closes  
    Not shared across tabs
    
    **Key Differences**  
    i) Persistance  
    Cookies → configurable expiry  
    localStorage → permanent  
    sessionStorage → per tab session  
    ii) Server Communication  
    Cookies → automatically sent in HTTP requests  
    Others → client-side only  
    iii) Capacity  
    Cookies → very small (~4KB)  
    Storage APIs → much larger (~5MB+)  
    iv) Security  
    Cookies → safer with HttpOnly, Secure  
    localStorage/sessionStorage → vulnerable to XSS
    
5.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">setTimeout and setInterval</mark>**  
    `setTimeout` → runs **once after delay**  
    `setInterval` → runs **repeatedly**  
    Both are **asynchronous**  
    Controlled via: `clearTimeout` and `clearInterval`  
    Work with **event loop**  
    **i) setTimeout**  
    Executes a function **once after a specified delay**
    
    ```javascript
    setTimeout(() => {
      console.log("Hello after 2 seconds");
    }, 2000);
    ```
    
    Runs **only once** after 2000 ms (2 seconds)  
    With Arguments -
    
    ```javascript
    function greet(name) {
      console.log("Hello " + name);
    }
    
    setTimeout(greet, 1000, "Rahul");
    ```
    
    Cancel setTimeout -
    
    ```javascript
    const id = setTimeout(() => {
      console.log("Will not run");
    }, 2000);
    
    clearTimeout(id);
    ```
    
    **ii) setInterval**  
    Executes a function **repeatedly at fixed intervals**
    
    ```javascript
    setInterval(() => {
      console.log("Runs every 2 seconds");
    }, 2000);
    ```
    
    Keeps running until stopped  
    Stop setInterval -
    
    ```javascript
    const intervalId = setInterval(() => {
      console.log("Running...");
    }, 1000);
    
    clearInterval(intervalId);
    ```
    
    Timers are handled by browser APIs (e.g., in Google Chrome), then pushed to the **callback queue**, and executed via the **event loop**.  
    **Real-World Use Cases -**  
    setTimeout :  
    Delayed UI actions  
    Debouncing  
    Notifications  
    setInterval :  
    Polling APIs  
    Live clocks  
    Auto-refresh data
