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
LocalStorage vs SessionStorage: Choosing the Right Client-Side Storage
More Relevant Posts
-
Most bugs don’t come from complex logic — they come from misunderstood behavior. One classic example in JavaScript: **shallow copy vs deep copy**. If you’ve worked with objects long enough, you’ve probably seen unexpected mutations. That usually comes down to how copying actually works under the hood. 🔹 SHALLOW COPY — copies structure, not depth Common methods: spread operator `{...obj}`, `Object.assign()`, array `slice()` / `concat()` ✔️ Creates a new top-level object ❌ Nested objects/arrays still share references ```js const user = { name: "Aman", prefs: { theme: "dark" } }; const copy = { ...user }; copy.prefs.theme = "light"; console.log(user.prefs.theme); // "light" ``` Even though `copy` looks independent, the nested object is still pointing to the same memory. 🔸 DEEP COPY — full separation Modern approach: `structuredClone()` ✔️ Completely independent copy ✔️ Handles nested objects, arrays, Map, Set, Date, etc. ```js const user = { name: "Aman", prefs: { theme: "dark" } }; const clone = structuredClone(user); clone.prefs.theme = "light"; console.log(user.prefs.theme); // "dark" ``` Quick comparison • `{...spread}` → shallow • `Object.assign()` → shallow • `structuredClone()` → deep ✅ • `JSON.parse(JSON.stringify())` → deep ⚠️ (drops Date, undefined, functions) • `_.cloneDeep()` → deep ✅ (useful for legacy support) When should you use what? → Flat data (no nesting)? Shallow copy is enough → Nested structures? Go for deep copy → Working with Date, Map, Set? Prefer `structuredClone()` → Need wide browser support? Use `_.cloneDeep()` Simple rule: If your data has depth, your copy should too. #JavaScript #WebDevelopment #Frontend #CodingTips #JS #SoftwareEngineering #Programming
To view or add a comment, sign in
-
𝐔𝐧𝐝𝐞𝐫𝐬𝐭𝐚𝐧𝐝𝐢𝐧𝐠 𝐑𝐞𝐚𝐜𝐭 + 𝐀𝐏𝐈 + 𝐃𝐚𝐭𝐚 𝐅𝐥𝐨𝐰 𝐢𝐧 𝟑 𝐒𝐢𝐦𝐩𝐥𝐞 𝐒𝐭𝐞𝐩𝐬 As a Full Stack Developer, one of the most fundamental concepts I work with daily is how React communicates with a backend API. Let me break it down: ━━━━━━━━━━━━━━━━━━━━ 𝐒𝐓𝐄𝐏 𝟏 — 𝐑𝐞𝐚𝐜𝐭 𝐋𝐚𝐲𝐞𝐫 ━━━━━━━━━━━━━━━━━━━━ When a component mounts, useEffect() fires and triggers the API call. useState() stores the incoming data and manages loading states. The JSX re-renders automatically when state changes. 𝐊𝐞𝐲 𝐢𝐧𝐬𝐢𝐠𝐡𝐭: React doesn't fetch data — it just reacts to it. ━━━━━━━━━━━━━━━━━━━━ 𝐒𝐓𝐄𝐏 𝟐 — 𝐀𝐏𝐈 𝐂𝐚𝐥𝐥 ━━━━━━━━━━━━━━━━━━━━ fetch() or axios sends an HTTP request to the backend. Express.js receives the request, processes business logic, queries PostgreSQL. The server returns a clean JSON response. 𝐊𝐞𝐲 𝐢𝐧𝐬𝐢𝐠𝐡𝐭: Your API is the bridge between UI and database. ━━━━━━━━━━━━━━━━━━━━ 𝐒𝐓𝐄𝐏 𝟑 — 𝐃𝐚𝐭𝐚 𝐅𝐥𝐨𝐰 ━━━━━━━━━━━━━━━━━━━━ setData() updates the state with the response. React detects the state change and triggers a re-render. The UI reflects the new data instantly — no page reload needed. 𝐊𝐞𝐲 𝐢𝐧𝐬𝐢𝐠𝐡𝐭: State is the single source of truth in React. ━━━━━━━━━━━━━━━━━━━━ 𝐓𝐡𝐞 𝐟𝐮𝐥𝐥 𝐟𝐥𝐨𝐰 𝐢𝐧 𝐨𝐧𝐞 𝐥𝐢𝐧𝐞: User opens page → useEffect fires → fetch API → Express queries DB → JSON returns → setData() → UI updates This is the foundation of every modern web application. Master this, and you can build anything. ───────────────────── #ReactJS #NodeJS #FullStackDevelopment #WebDevelopment #JavaScript #ExpressJS #PostgreSQL #Frontend #Backend #Programming #100DaysOfCode #TechTips
To view or add a comment, sign in
-
-
Do your Angular callbacks feel like a game of "I hope this data matches"? 🤔 Here is #Day18 of #TypescriptBeforeAngular with SANDEEP KUMAR (#IAM5K): Function Types (Defining Callbacks and Event Handlers) We define a callback function in a service, type the argument as any, and later accidentally pass the wrong data from our component. JavaScript won't stop you, so you only find out when your application crashes at runtime for the user. Today, we meet the contract of safe communication: #FunctionTypes. 1️⃣ What are Function Types? In #TypeScript, you don’t always need a formal blueprint (like an Interface or a Class) to define an object’s structure. Instead of building everything from scratch, you can use Function Types to define the specific "shape" of a function—exactly what parameters it requires (inputs) and what type it returns (output). // The recipe: Input must be string, output must be string. type GreetFunction = (name: string) => string; // Initialization: TypeScript guarantees this function matches: const greet: GreetFunction = (name) => `Hello, ${name}!`; 2️⃣ Significance in #Angular: When I first started, my app communication was a mess. Every service callback used any, leading to confusing template errors because the component was receiving data it didn't expect. In modern Angular (especially for defining @Output() properties or asynchronous Service callbacks), Function Types are essential. Whether you are: Defining an EventEmitter<(data: string) => void>. Creating a callback contract for a dynamic service method. Being explicit about your function types ensures that your component and service are perfectly aligned. The compiler guarantees that you always pass the right data, in the right format, to the right handler. It turns "I think this works" into "I know this works." It is about building a project that isn't just "typed," but truly truly safe. 💡 Beginner Tip: Think of Function Types as standardized handshake agreements. If you use them to document the expected signature of your callbacks and event handlers, your code becomes vastly easier to read and maintain, especially as your application grows and your communication logic becomes more complex. 👉 What is the most complex callback structure ((A, B, C) => void) you use in your Angular app?👇 Connect/Follow me SANDEEP KUMAR so you dont miss the next concept. #WebDev #CodingTips #NewDeveloper #CleanCode #FunctionTypes #Callbacks #Programming #TypeSafety #Javascipt #BTech
To view or add a comment, sign in
-
-
💡 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
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
-
🛡️ Introducing ngx-attack-detector: Real-Time Script Attack Detection for Angular Apps I'm excited to share my latest open-source Angular library, ngx-attack-detector, now available on GitHub Packages. This package acts as a security watchdog for your front end, instantly alerting you when your app experiences an unusual flood of requests. The Problem Malicious scripts or aggressive bots can overwhelm your Angular app with HTTP requests. These attacks can degrade performance, rack up API costs, and compromise the user experience. Most monitoring happens server-side, missing client-side script injections. The Solution This library monitors all outgoing HTTP requests (via fetch and XHR) directly in the browser. When more than a configurable number of requests are made within a 5-second window, it immediately fires a highly visible toast warning. How It Works Global Request Patching: The package's GlobalRequestMonitor seamlessly hooks into the browser's Fetch and XMLHttpRequest APIs to record every outgoing request. Configurable Detection: The AttackDetectorService checks incoming requests against a sliding window. You can easily set the time window (windowMs) and max allowed requests (maxRequests). Instant Developer Feedback: For a quick local test, a standalone injection token directly patches your fetch for instant verification. Once a threshold is breached, a toast notification appears, warning that your application is potentially under a script attack. Technology Stack Angular >=12.0.0: Built with standalone components and @Injectable services for easy integration. RxJS: Uses BehaviorSubject and Observable to emit detection events. TypeScript: Fully typed with interfaces for AttackConfig. Quick Start To test it yourself, simply install and inject the service: bash npm install @md-mehbub-ul-islam/ngx-attack-detector@0.0.1 GitHub Repository & Package Code: https://lnkd.in/gBEC7vDy Package: https://lnkd.in/gUQfsBbm What's Next I plan to add support for HTTP Interceptor integration for requests made with Angular's HttpClient and configurable toast positions and styling. Have you ever needed a quick client-side way to monitor unusual request spikes? I'd love to hear your use cases! #Angular #OpenSource #WebSecurity #Frontend #TypeScript #CyberSecurity #GitHubPackages #AngularLibrary
To view or add a comment, sign in
-
I've reviewed 40+ Node.js codebases. JWT is misused in almost every single one. Not because developers don't understand JWT. Because they misunderstand what JWT is actually for. JWT is not a session. It's a signed claim. That distinction matters more than most tutorials explain. Here are the 4 mistakes I find repeatedly: MISTAKE 1: STORING JWT IN LOCALSTORAGE localStorage is readable by any JavaScript on the page. One XSS vulnerability and every token on that domain is gone. // ❌ This is in 60% of codebases I audit localStorage.setItem('token', jwt) // ✅ Use httpOnly cookies instead res.cookie('token', jwt, { httpOnly: true, // JS cannot read this secure: true, // HTTPS only sameSite: 'strict' }) MISTAKE 2: SIGNING WITH HS256 IN MULTI-SERVICE SYSTEMS HS256 uses a shared secret. Every service that verifies tokens must also know the secret — meaning every service can also create tokens. // ❌ For microservices jwt.sign(payload, process.env.JWT_SECRET) // HS256 // ✅ For microservices: RS256 (asymmetric) // Auth service signs with private key jwt.sign(payload, privateKey, { algorithm: 'RS256' }) // All other services verify with public key only jwt.verify(token, publicKey) Other services can verify but never forge. That's the difference. MISTAKE 3: 24-HOUR ACCESS TOKENS WITH NO REFRESH LOGIC Long access tokens are a security liability. If a token leaks, the attacker has 24 hours. The pattern: → Access token: 15 minutes → Refresh token: 7 days, stored in httpOnly cookie → Refresh endpoint rotates the refresh token on each use MISTAKE 4: PUTTING SENSITIVE DATA IN THE PAYLOAD JWT payloads are base64 encoded, not encrypted. Anyone who has the token can decode and read the payload. // ❌ Never do this jwt.sign({ userId, email, password, creditCard }, secret) // ✅ Minimum viable payload jwt.sign({ sub: userId, role: 'user' }, secret) Look up data from the database using the userId. Don't put it in the token. Which of these have you caught in a codebase review? #NodeJS #TypeScript #WebSecurity #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
-
🚨 Feel like your Angular app is built on shaky ground because of undefined data? 🚨 Here is #Day9 of #TypescriptBeforeAngular with SANDEEP KUMAR (#IAM5K): #Null & #Undefined (Handling "Strict Nothingness") The most common errors in web development are "cannot read property 'name' of undefined" or "cannot read property 'id' of null". They happen when we assume data is present, but it isn’t. Today, we meet the solution that makes modern Angular robust: Strict Null Checks. 1️⃣ What are Null and Undefined? In #TypeScript, null and undefined are two distinct types that represent "nothingness." undefined: A variable has been declared, but nothing has been put inside it yet. null: An explicit value representing the absence of any object value. (You often use this to initialize a variable that will later hold an object). // Ssssh! They are different "empty" buckets. let name: string | undefined; // starts as `undefined` let profile: UserProfile | null = null; // explicitly initialized as `null` 2️⃣ Significance in #Angular: As a beginner, I used to treat null and undefined as if they were identical. This led to a lot of frustrating, unexpected crashes in my HTML templates. In modern Angular, Strict Null Checks are turned on by default. This is a complete game-changer for stability. It forces you to explicitly account for the possibility that a value might be missing. If you have a #Signal like: user = signal<User | null>(null); The compiler is now your safety net. It will not let you access user().name until you first prove that user() is not null. This "fail early" approach prevents a whole class of runtime errors, making your Angular apps significantly more reliable and your templates much cleaner. 💡 Beginner Tip: Think of undefined as uninitialized data (like optional parameters) and null for values that are explicitly missing (like an API response that didn't find a user). Being intentional makes your logic much easier to reason about. 👉 Did you knew about the difference in null and undefined? What’s the most frustrating "cannot read property of..." error you’ve ever had to debug in an Angular template? Tell me in the comments👇 #WebDev #CodingTips #NewDeveloper #CleanCode #NullAndUndefined #StrictNullChecks #IAM5K #SandeepKumar #TypeSafety #Programming #javascript
To view or add a comment, sign in
-
-
𝗛𝘁𝘁𝗽𝗖𝗹𝗶𝗲𝗻𝘁 𝘃𝘀 𝗵𝘁𝘁𝗽𝗥𝗲𝘀𝗼𝘂𝗿𝗰𝗲 𝗶𝗻 𝗔𝗻𝗴𝘂𝗹𝗮𝗿 (𝗢𝗹𝗱 𝘃𝘀 𝗠𝗼𝗱𝗲𝗿𝗻 𝗪𝗮𝘆) In Angular, fetching data from APIs is a daily task. But the way we handle it is evolving. Many developers still use HttpClient, but Angular now also provides a more modern approach: httpResource. What is HttpClient? HttpClient is the traditional way to make API calls. ✔ You manually call APIs ✔ You handle loading, error, and state ✔ You subscribe to observables What is httpResource? httpResource is a newer, reactive way to fetch data. ✔ Automatically manages loading state ✔ Handles errors more cleanly ✔ Works smoothly with signals Think of it as: Less manual work, more reactive behavior. Why Do We Need httpResource? In real projects: • We write the same loading logic again and again • We handle errors manually everywhere • We manage state in multiple places This increases complexity. httpResource simplifies this by handling common patterns automatically. Real-Life Example Imagine ordering food: With HttpClient → You call the restaurant → Track order manually → Ask for updates again and again With httpResource → You place the order → You automatically get updates (preparing, out for delivery, delivered) Less effort. Better experience. Simple Example Using HttpClient this.http.get('/api/users').subscribe({ next: (data) => this.users = data, error: (err) => console.error(err) }); Using httpResource usersResource = httpResource(() => ({ url: '/api/users' })); Now in template: @if(usersResource.isLoading()) { <p>Loading...</p> } @else if(usersResource.error()) { <p>Error occurred</p> } @else { <p>{{ usersResource.value() }}</p> } When to Use What? • HttpClient → Full control, complex scenarios • httpResource → Cleaner, reactive, less boilerplate One Simple Conclusion : Good developers don’t just write API calls they choose the right abstraction to reduce complexity. #Angular #FrontendDevelopment #WebDevelopment #RxJS #AngularSignals #SoftwareEngineering #TechCommunity #AngularDeveloper
To view or add a comment, sign in
-
✅ JavaScript Advanced Concepts You Should Know 🔍💻 These concepts separate beginner JS from production-level code. Understanding them helps with async patterns, memory, and modular apps. 1️⃣ Closures A function that "closes over" variables from its outer scope, maintaining access even after the outer function returns. Useful for data privacy and state management. function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 2️⃣ Promises & Async/Await Promises handle async operations; async/await makes them read like sync code. Essential for APIs, timers, and non-blocking I/O. // Promise chain fetch(url).then(res => res.json()).then(data => console.log(data)).catch(err => console.error(err)); // Async/Await (cleaner) async function getData() { try { const res = await fetch(url); const data = await res.json(); console.log(data); } catch (err) { console.error(err); } } 3️⃣ Hoisting Declarations (var, function) are moved to the top of their scope during compilation, but initializations stay put. let/const are block-hoisted but in a "temporal dead zone." console.log(x); // undefined (hoisted, but not initialized) var x = 5; console.log(y); // ReferenceError (temporal dead zone) let y = 10; 4️⃣ The Event Loop JS is single-threaded; the event loop processes the call stack, then microtasks (Promises), then macrotasks (setTimeout). Explains why async code doesn't block. 5️⃣ this Keyword Dynamic binding: refers to the object calling the method. Changes with call site, new, or explicit binding. const obj = { name: "Sam", greet() { console.log(`Hi, I'm ${this.name}`); }, }; obj.greet(); // "Hi, I'm Sam" // In arrow function, this is lexical const arrowGreet = () => console.log(this.name); // undefined in global 6️⃣ Spread & Rest Operators Spread (...) expands iterables; rest collects arguments into arrays. const nums = [1, 2, 3]; const more = [...nums, 4]; // [1, 2, 3, 4] function sum(...args) { return args.reduce((a, b) => a + b, 0); } sum(1, 2, 3); // 6 7️⃣ Destructuring Extract values from arrays/objects into variables. const person = { name: "John", age: 30 }; const { name, age } = person; // name = "John", age = 30 const arr = [1, 2, 3]; const [first, second] = arr; // first = 1, second = 2 8️⃣ Call, Apply, Bind Explicitly set 'this' context. Call/apply invoke immediately; bind returns a new function. function greet() { console.log(`Hi, I'm ${this.name}`); } greet.call({ name: "Tom" }); // "Hi, I'm Tom" const boundGreet = greet.bind({ name: "Alice" }); boundGreet(); // "Hi, I'm Alice" 9️⃣ 💡 Practice these in a Node.js REPL or browser console to see how they interact. 💬 Tap ❤️ if you're learning something new!
To view or add a comment, sign in
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