20) Browser APIs
fetch API
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 Requestfetch("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 Requestfetch("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
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 exampleasync 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 appsAxios
localStorage and sessionStorage
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 APIslocalStorage→ persistentsessionStorage→ temporary (per tab)
Store only strings
Be careful with security
i) localStorage
Stores data permanently (until manually cleared)localStorage.setItem("name", "Rahul"); const name = localStorage.getItem("name"); console.log(name); // RahulNo 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 closedsessionStorage.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// 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 infoCookies vs localStorage vs sessionStorage
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, sessionsii) localStorage -
Stores data permanently in the browser.
No expiration
Not sent to server
Shared across tabsiii) sessionStorage -
Stores data temporarily (per tab session)
Cleared when tab closes
Not shared across tabsKey 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)5MB+)
Storage APIs → much larger (
iv) Security
Cookies → safer with HttpOnly, Secure
localStorage/sessionStorage → vulnerable to XSSsetTimeout and setInterval
setTimeout→ runs once after delaysetInterval→ runs repeatedly
Both are asynchronous
Controlled via:clearTimeoutandclearInterval
Work with event loop
i) setTimeout
Executes a function once after a specified delaysetTimeout(() => { console.log("Hello after 2 seconds"); }, 2000);Runs only once after 2000 ms (2 seconds)
With Arguments -function greet(name) { console.log("Hello " + name); } setTimeout(greet, 1000, "Rahul");Cancel setTimeout -
const id = setTimeout(() => { console.log("Will not run"); }, 2000); clearTimeout(id);ii) setInterval
Executes a function repeatedly at fixed intervalssetInterval(() => { console.log("Runs every 2 seconds"); }, 2000);Keeps running until stopped
Stop setInterval -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