💡 Understanding Browser Storage in JavaScript: localStorage vs sessionStorage vs Cookies If you're working in front-end development, managing data in the browser is something you do almost every day. But many developers still get confused between these three: 🔹 localStorage 🔹 sessionStorage 🔹 Cookies Let’s break it down with simple examples 👇 📌 1. localStorage (Persistent Storage) ✔ Data stays even after closing the browser ✔ No expiration time Example: #javascript // Store data localStorage.setItem("username", "Alex"); // Get data console.log(localStorage.getItem("username")); // Remove data localStorage.removeItem("username"); 👉 Use case: Save user preferences like theme (dark/light mode) 📌 2. sessionStorage (Temporary Storage) ✔ Data is cleared when the tab is closed ✔ Works per tab (not shared across tabs) Example: #javascript // Store data sessionStorage.setItem("sessionUser", "Alex"); // Get data console.log(sessionStorage.getItem("sessionUser")); 👉 Use case: Temporary form data or session-based info 📌 3. Cookies (Server Interaction + Expiry Control) ✔ Stored as small text data ✔ Can have expiration date ✔ Sent to server with every request Example: #javascript // Set cookie document.cookie = "user=Alex; expires=Fri, 31 Dec 2026 12:00:00 UTC; path=/"; // Read cookie console.log(document.cookie); 👉 Use case: Authentication, tracking, remembering login sessions ⚡ Quick Comparison: localStorage → Long-term storage sessionStorage → Temporary per tab Cookies → Server communication + expiry control 🚀 Pro Tip: Avoid storing sensitive data (like passwords/tokens) in localStorage or cookies without proper security measures. #javascript #frontenddevelopment #webdevelopment #coding #interviewprep #techlearning #immediatejoiner #hiring #requiter #jobseekers #ui #ux #react #javascript #frontend #growth
localStorage vs sessionStorage vs Cookies in JavaScript
More Relevant Posts
-
LocalStorage vs. SessionStorage: Where is your data actually going? 💾 As JavaScript developers, we often need to store data on the client side. But choosing the right storage can make or break your application's performance and user experience! 🧱 The Trio of Methods Whether you use localStorage or sessionStorage, the API is the same: .setItem(key, value): Store the data. .getItem(key): Retrieve the data. .removeItem(key): Delete a specific item. .clear(): Wipe everything! 🧪 Storing Objects (The JSON Trick) You cannot store a raw JavaScript Object directly. If you do, it turns into "[object Object]". You must stringify it first! javascript const userObject = { firstName: "Santha Kumar", age: 33 }; // ✅ Correct way to store localStorage.setItem("user_data", JSON.stringify(userObject)); // ✅ Correct way to retrieve const data = JSON.parse(localStorage.getItem("user_data")); console.log(data.firstName); Use code with caution. ⚠️ Note: Functions inside objects (like isSigns) are lost during stringification! ⚔️ The Big Comparison FeatureLocalStorageSessionStoragePersistencePermanent (Until manually cleared)Temporary (Cleared when tab is closed)Storage Size~5MB to 10MB~5MBScopeShared across all tabs of the same originLimited to the specific tab/windowUse CaseTheme settings, User PreferencesForm data, temporary session states 💼 Real-World Scenario: Naukri.com: Might use LocalStorage to remember your "Last Searched Job" even if you close the browser. Flipkart: Might use SessionStorage to keep track of filters applied during a single shopping session so they don't persist forever. Important Security Tip: Never store JWT tokens or passwords in these storages. They are vulnerable to XSS attacks because any script on your page can access them! Which one do you use more in your projects? LocalStorage or SessionStorage? Let's discuss! 👇 #JavaScript #WebDevelopment #Frontend #CodingTips #LocalStorage #WebStorage #SoftwareEngineering #TechEducation
To view or add a comment, sign in
-
-
🚀 Fetch vs Axios in JavaScript When building modern web applications, interacting with APIs is a daily task. Two of the most commonly used tools for this are Fetch and Axios. 🔹 What is fetch()? Definition: fetch() is a built-in Web API in JavaScript used to make HTTP requests to servers and retrieve resources. 👉 It is promise-based and available in all modern browsers. 📌 How Fetch Works >> Sends a request to a server (GET, POST, etc.) >> Returns a Promise >> Resolves to a Response object >> You must extract data manually (e.g., .json()) 💻 Example async function fetchData() { try { const response = await fetch("https://lnkd.in/dQeGAVaB"); // Checking response status manually if (!response.ok) { throw new Error("HTTP error! Status: " + response.status); } // Convert response into JSON const data = await response.json(); console.log(data); } catch (error) { console.error("Fetch Error:", error); } } ⚠️ Important Characteristics of Fetch ✔️ Built into browser (no installation) ✔️ Returns Promise ✔️ Requires manual JSON parsing ✔️ Does NOT throw errors for HTTP failures (you must handle it) ✔️ Slightly more verbose 🔹 What is axios? Definition: axios is a third-party JavaScript library used to make HTTP requests from the browser or Node.js. 👉 It is also promise-based but provides many additional features out of the box. 📌 How Axios Works >> Sends HTTP requests (GET, POST, PUT, DELETE, etc.) >> Automatically transforms response into JSON >> Automatically throws errors for bad status codes >> Provides advanced configuration options 💻 Example import axios from "axios"; async function fetchData() { try { const response = await axios.get("https://lnkd.in/dQeGAVaB"); // Axios directly gives data console.log(response.data); } catch (error) { console.error("Axios Error:", error); } } ⚠️ Important Characteristics of Axios ✔️ Requires installation (npm install axios) ✔️ Automatic JSON transformation ✔️ Better error handling ✔️ Supports interceptors (modify request/response globally) ✔️ Supports timeout, cancellation, headers easily ✔️ Cleaner and shorter syntax 💡 When to Use Fetch vs Axios? 👉 Use Fetch when: >> You want a lightweight solution >> No external dependencies required >> Working on small/simple projects 👉 Use Axios when: >> You are building real-world applications >> Need better error handling >> Want features like: >>Interceptors, Global configuration, Request cancellation #JavaScript #WebDevelopment #Axios #FetchAPI #Frontend #Programming #Developers #Coding
To view or add a comment, sign in
-
If you think monolithic architectures can’t deliver lightning-fast, highly modern web applications, think again. ⚡️ I just rolled out a major update to my open-source Manga Reader project—an enterprise-grade content management and rendering platform engineered from the ground up for high traffic and seamless UX. Under the Hood 🛠️: 🔹 Backend (API-First): Powered by Laravel 11 & PHP 8.2. Service-layer architecture separating business logic from presentation. 🔹 Frontend (Reactive): Tailwind CSS, JS and Blade, packaged with Vite for blisteringly fast asset delivery. 🔹 Data Pipeline: Custom chunked uploading logic for massive files & automated MangaDex API sync. 🔹 Performance: Fast Paginate for instant catalog querying, robust Intervention Image processing, and isolated theme layers. 🔹 Security & Ops: Granular RBAC (Spatie), automated backups, and Cloudflare-ready edge compatibility. I built this not just as a reader, but as a robust architecture playground. Whether it's managing complex hierarchical data (Volumes -> Chapters -> Pages) or syncing reactive state across an advanced system-aware Dark Mode, it handles the load. As a developer, there’s nothing quite like turning complex technical constraints into buttery-smooth user experiences. It’s completely open-source. Dive into the code, check out the architecture, or open a PR if you feel like hacking on something fun this weekend. ⬇️ 🔗 GitHub Repo: https://lnkd.in/dt8HtXuq #Laravel #PHP #WebDevelopment #SoftwareEngineering #OpenSource #TailwindCSS #TechStack #Developers
To view or add a comment, sign in
-
-
📑 Knowledge Base Platform - XXVI Edit Profile & Privacy Settings In this stage I implemented the profile editing flow with personal data visibility settings. The goal was to allow users to manage their own profile information while controlling access to sensitive fields such as phone number and birthday. On the backend, I introduced a Visibility enum and added private visibility for phone number and birthday in the user model. The update DTO was extended with visibility settings, and I implemented dedicated updateMe controller logic, service methods, and route handling. On the fronted, I added API methods, store actions, and a reusable profile form component. To improve the UI, used day.js formatting to display in a cleaner day + month format instead of full raw dates. I also created two mappers for transforming profile data between API and from models, connected the edit page, and added visibility rendering tules on the profile page. An Edit Profile button was integrated into the user profile interface. Result User self-service profile management with privacy controls: ➜ Edit personal profile data; ➜ Hide or show selected sensitive fields; ➜ Cleaner birthday presentation; ➜ Reusable form and structured data mapping; ➜ Better ownership of personal account settings. 📎 Repo: https://lnkd.in/dnuCveCa Here are the previous parts: Admin User Edit Flow https://lnkd.in/daxaS7Pu Reusable user Profile Page https://lnkd.in/dFApMmMi #frontend #backend #vue #nodejs #javascript #webdevelopment #privacy #profile #developer #opentowork
To view or add a comment, sign in
-
🔥 Stop Making Repeated API Calls in React! (Use Smart Caching) As a Frontend Developer, one of the most common performance issues I’ve seen is: 👉 Same API getting called again and again This not only slows down the app ⏳ but also increases server load 📉 💡 The solution? Client-Side Caching using TanStack Query (React Query) --- ✅ What is TanStack Query? It’s a powerful data-fetching library that automatically: ✔️ Caches API responses ✔️ Prevents duplicate API calls ✔️ Refetches data in background ✔️ Manages loading & error states --- 💻 Example: Avoid Redundant API Calls import { useQuery } from "@tanstack/react-query"; const fetchUsers = async () => { const res = await fetch("/api/users"); return res.json(); }; export default function Users() { const { data, isLoading } = useQuery({ queryKey: ["users"], // unique cache key queryFn: fetchUsers, staleTime: 5 * 60 * 1000, // cache valid for 5 mins }); if (isLoading) return <p>Loading...</p>; return <div>{data.length} users</div>; } --- 🧠 How it works? - First API call → data stored in cache - Next time → data served from cache (no API call) 🚀 - After "staleTime" → background refetch happens --- ⚡ Why I prefer this in production? 👉 No need to manually manage cache 👉 Built-in request deduplication 👉 Improves performance drastically 👉 Cleaner & scalable code --- 🎯 Pro Tip (Senior Level) Use proper "queryKey" + cache invalidation strategy for dynamic apps --- 💬 Have you used React Query or still managing API calls manually? Let’s discuss 👇 #ReactJS #Frontend #Performance #WebDevelopment #JavaScript #ReactQuery #TanStackQuery #SoftwareEngineering
To view or add a comment, sign in
-
What is a Proxy in Javascript? A Proxy is a wrapper you place around an object that lets you intercept and control what happens when someone interacts with it. Say a dev wants to read a property? You can intercept that. Set a value? You can intercept that too. Deleting a key? Same thing. Think of it as a security checkpoint sitting around your object. It decides what gets through, what is not allowed to get through, and what gets modified along the way. How it works: A Proxy takes two things: The target - this is original object you want to secure. The handler: an object containing traps - functions that intercept specific operations. Example: const user = { name: "Markus", age: 25 }; const proxy = newProxy(user, { get (target, key) { console.log(`Someone read: ${key}`); return target[key]; }, set (target, key, value) { console.log(`Someone set: ${key} = ${value}`); target[key] = value; return true; } }); proxy.name; -> "Someone read: name" proxy.age = 30; -> "Someone set: age = 30" Every interaction with the proxy goes through your handler first - giving you complete visibility and control. The three most common traps: -> get - intercepts property reading -> set - intercepts property writing -> deleteProperty - intercepts property deletion Real world use cases - where Proxy truly shines. -> Validation - proxy rejects invalid values before they reach your object. const handler = { set(target, key, value) { if (key === "age" && typeof value !== "number") { throw new TypeError("Age must be a number"); } target[key] = value; return true; } }; -> Logging - proxy tracks every read and write automatically without cluttering your business logic. -> Default values - return a fallback when a property doesn't exist instead of undefined. const handler = { get(target, key) { return key in target ? target[key] : "Property not found"; } }; the function above simply says if the key is available in the target element return the key. Else return the string "property not found" Proxy makes your code more intentional - putting you in control of exactly how your data is accessed, changed, and protected.
To view or add a comment, sign in
-
🚀 Frontend Learning — Cookies vs LocalStorage vs SessionStorage (Clear Difference) If you’re working with authentication or storing data in the browser… => You must understand this clearly 🍪 Cookies 👉 Stored in browser & sent with every HTTP request -> Small size (~4KB) -> Can have expiry -> Used for authentication (tokens, sessions) -> Sent on every request → can affect performance 📦 Local Storage 👉 Stored in browser (client-side only) -> Large capacity (~5–10MB) -> No expiry (until manually cleared) -> Not sent to server -> Less secure (accessible via JS) ⏳ Session Storage 👉 Same as localStorage but with a twist 👇 -> Data cleared when tab is closed -> Scoped per tab -> Not shared across tabs 🧠 Key Differences -> Cookies → Server + Client (auto sent) -> LocalStorage → Client only (persistent) -> SessionStorage → Client only (temporary) 🔥 When to Use What? -> Cookies → Authentication / session handling -> LocalStorage → Persist user preferences (theme, settings) -> SessionStorage → Temporary data (form state, tab-specific data) 💡 Pro Insight -> Never store sensitive data (like passwords) in localStorage -> Prefer HttpOnly cookies for secure authentication 🎯 Key Takeaway => Not all storage is the same… -> Choosing the right one = better performance + better security At a senior level, it’s not just about storing data… -> It’s about storing it correctly 🔥 #FrontendDevelopment #JavaScript #WebDevelopment #Cookies #LocalStorage #SessionStorage #CodingTips #Developers #LearnInPublic
To view or add a comment, sign in
-
-
Day 19/30 — JavaScript Journey JavaScript – Local Storage 💾 Save data like a real app (client-side persistence) Local Storage is part of the browser’s Web Storage API—it allows you to store key–value data directly in the user’s browser, with no backend required. This is how real apps remember user preferences, auth states (carefully), UI settings, and more. 🔥 Why Local Storage matters Persistence → Data survives page reloads & browser restarts Fast access → No network calls, instant reads Simple API → 4–5 methods, zero setup Offline capability → Works even without internet 🧠 Core API (you must know) // Store data localStorage.setItem("theme", "dark"); // Read data const theme = localStorage.getItem("theme"); // Remove one item localStorage.removeItem("theme"); // Clear everything localStorage.clear(); ⚠️ Important: Data is ALWAYS stored as string If you store objects → convert using JSON const user = { name: "Rakesh", role: "Developer" }; // Save localStorage.setItem("user", JSON.stringify(user)); // Retrieve const storedUser = JSON.parse(localStorage.getItem("user")); 💡 Real-world use cases 🔐 Save login state (but NOT sensitive tokens) 🎨 Dark / Light mode preference 🛒 Cart items in e-commerce apps 📝 Draft forms / unsaved inputs ⚙️ App settings (language, layout, filters) 🚫 Limitations (don’t ignore this) ❌ Storage limit ~5MB (varies by browser) ❌ Not secure → accessible via JS (XSS risk) ❌ Synchronous → large data can block UI ❌ No expiry → stays until manually cleared 🧪 Pro Pattern (Used in real apps) Create a wrapper for cleaner usage: const storage = { set: (key, value) => { localStorage.setItem(key, JSON.stringify(value)); }, get: (key) => { const value = localStorage.getItem(key); return value ? JSON.parse(value) : null; }, remove: (key) => localStorage.removeItem(key) }; 🚀 Pro Tips (Senior-level thinking) Use Local Storage for UI state, not business-critical data Combine with session management (cookies / backend) Handle errors with try...catch (JSON parsing can fail) Use namespacing → "app_user", "app_theme" Sync across tabs using "storage" event ⚡ Bottom line Local Storage is your quick persistence layer for frontend apps. Used correctly → it makes your app feel fast, smart, and stateful. Used blindly → it becomes a security and performance risk.
To view or add a comment, sign in
-
-
There is a critical frontend pattern that is frequently omitted from standard training but causes significant production issues. It is the challenge of handling rapid, sequential API requests. Consider a common scenario: you have a data dashboard with a year filter. A user clicks "2023", experiences a slight network delay, and immediately clicks "2024". The Flawed Approach (The Boolean Lock) : Many developers initially solve this by introducing an isFetching state variable. If a request is pending, the function simply returns and ignores any subsequent clicks. While this prevents multiple network calls, it creates a deeply flawed user experience. The application ignores the user's final intent. When the data for 2023 eventually loads, the user is left staring at the wrong dataset, assuming the interface is broken. The Silent Bug (Race Conditions) : If you remove the boolean lock and allow all clicks to trigger fetch requests, you encounter a worse problem. The network is unpredictable. The server might process the "2024" request faster than the "2023" request. Your application updates with the 2024 data, but moments later, the delayed 2023 payload resolves and overwrites your state. The user selected 2024 but is silently viewing 2023 data. This leads to inaccurate data reporting and confused users. The Professional Standard: AbortController The robust architectural solution is to cancel outdated requests rather than block new ones. By creating an instance of AbortController and passing its signal to your fetch request, you gain the ability to call the abort method the moment a new user action is triggered. Why this is the industry standard: 1. State Integrity: It completely eliminates the race condition. Your component will never attempt to update its state with a stale payload that arrived out of order. 2. Resource Optimization: It terminates the pending connection at the browser level. This prevents unnecessary processing and conserves bandwidth. 3. Accurate User Intent: The interface remains perfectly synchronized with the user's most recent interaction. Key Takeaway, Stop punishing fast users with boolean locks and stop leaving your application vulnerable to race conditions. Utilize the native AbortController API to manage network traffic, cancel obsolete requests, and guarantee data integrity in your user interface. How many of you have spent hours debugging a state mismatch in production only to trace it back to a delayed API response overwriting fresh data? Share your experiences with network race conditions below. #FrontendDevelopment #JavaScript #ReactJS #WebDevelopment #CodingTips #TechCommunity #UXDesign
To view or add a comment, sign in
-
-
#js #26 **map, filter and reduce method in Javascript** 🔹 1. map() 👉 Purpose: Transform each element → return a new array const arr = [1, 2, 3]; const result = arr.map(num => num \* 2); console.log(result); // [2, 4, 6] ✔️ Key points: Same length as original array Does NOT modify original array 🔹 2. filter() 👉 Purpose: Return elements that match a condition const arr = [1, 2, 3, 4]; const result = arr.filter(num => num > 2); console.log(result); // [3, 4] ✔️ Key points: Returns subset (can be smaller) Condition must return true or false 🔹 3. reduce() 👉 Purpose: Reduce array → single value const arr = [1, 2, 3, 4]; const sum = arr.reduce((acc, curr) => acc + curr, 0); console.log(sum); // 10 ✔️ Syntax: arr.reduce((accumulator, currentValue) => {}, initialValue); 🔥 Real-world Examples ✅ 1. Double numbers arr.map(n => n \* 2); ✅ 2. Get even numbers arr.filter(n => n % 2 === 0); ✅ 3. Sum of array arr.reduce((sum, n) => sum + n, 0); ✅ 4. Count frequency const arr = [1, 2, 2, 3]; const freq = arr.reduce((acc, num) => { acc[num] = (acc[num] || 0) + 1; return acc; }, {}); console.log(freq); // {1:1, 2:2, 3:1} 🔹Difference | Method | Output | Use case | | ------ | ------------ | -------------- | | map | New array | Transform data | | filter | New array | Select data | | reduce | Single value | Aggregate data | 🔥 Chain Example (Very Important) const arr = [1, 2, 3, 4, 5]; const result = arr .filter(n => n > 2) .map(n => n \* 2) .reduce((sum, n) => sum + n, 0); console.log(result); // 24 🧠 Easy Way to Remember map → modify each item filter → pick some items reduce → combine all into one #Javascript #Frontend #Backend #ObjectOrientedProgramming #SoftwareEngineering
To view or add a comment, sign in
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development