A small concept that confuses many developers: CORS. Almost every developer has seen this error at some point: “Blocked by CORS policy.” When I first encountered it, it looked like something was broken in my code. But in reality, it’s the browser protecting users. The key idea behind CORS is Origin. Origin is made of three parts: • Protocol (HTTP / HTTPS) • Domain • Port If any of these change, the browser treats the request as coming from a different origin. Example: Frontend https://facebook.com:3000 Backend API https://lnkd.in/g2FwCsEk Even though they look related, the browser sees them as different origins. So when the frontend sends a request, the browser automatically includes a header like: Origin: https://facebook.com Now the server has to explicitly allow it by sending: Access-Control-Allow-Origin If the server allows it, the browser delivers the response. If not, the browser blocks it and throws the famous CORS policy error. I created a simple diagram to visualize how this interaction actually works between the browser and the server. Understanding this makes debugging frontend-backend communication much easier. Curious to know: When did you first encounter a CORS error in your projects? Sheryians Coding School Anshu Pandey Ritik Rajput Daneshwar Verma Ankur Prajapati #webdevelopment #javascript #nodejs #backend #frontend #cors
CORS Policy Error: Understanding Origin and Access-Control-Allow-Origin
More Relevant Posts
-
🔥 Today I finally understood how frontend talks to backend — and why CORS was blocking me all along. 1. 😩 The Problem I built a React frontend. I built an Express backend. I hit "fetch" and BAM — "Access to fetch at 'http://localhost:5000/api' from origin 'http://localhost:3000' has been blocked by CORS policy" ❌ I stared at the screen. Refreshed. Googled. Panicked. 😅 2. 🎓 Then Ankur Prajapati bhaiya explained it like this — Imagine your browser is a security guard. Your frontend lives at localhost:3000. Your backend lives at localhost:5000. That guard sees DIFFERENT origins — and blocks by default. This is CORS. Cross-Origin Resource Sharing. The browser says: "You can only fetch from the SAME origin unless the server explicitly allows it." 3. 🛠️ The Fix — One line on your backend: const cors = require('cors'); app.use(cors({ origin: 'http://localhost:3000' })); That's it. That one line tells the browser: "Hey, I trust this frontend. Let it in." ✅ 4. 💡 What I actually learned today: ✅ Frontend and backend on different ports = different origins = CORS kicks in ✅ CORS is a browser protection — not a server error ✅ Always whitelist specific origins in production — never use origin: "*" in prod ✅ How fetch() works and how to connect React to Express APIs 4. Shoutout to Ankur Prajapati bhaiya for making this SO clear with real examples. The "security guard" analogy — it just clicked. 🙌 #WebDevelopment #CORS #FullStack #NodeJS #React #LearningInPublic #JavaScript
To view or add a comment, sign in
-
-
🚀 Understanding CORS (Cross-Origin Resource Sharing) Simplified for Developers If you’ve ever seen this error in your browser 👇 “No 'Access-Control-Allow-Origin' header is present…” Congrats — you’ve met CORS 😅 Let’s break it down in the simplest way 👇 🔹 What is CORS? CORS is a browser security feature that controls how your frontend and backend communicate when they are on different origins. 👉 Example: Frontend: http://localhost:3000 Backend: http://localhost:5000 Different ports = different origin → 🚫 blocked by default 🔹 Why does it exist? To protect users from malicious websites making unauthorized requests using their browser. 🔹 How does it work? When your frontend makes a request: Browser sends the request with origin info Server responds with permission headers Browser decides: allow ✅ or block ❌ 🔹 Common Fix (Node.js / Express) import cors from "cors"; app.use(cors({ origin: "http://localhost:3000" })); 🔹 Key Points to Remember ✔️ CORS is enforced by the browser ✔️ Backend must allow the origin ✔️ Postman/cURL don’t care about CORS ✔️ Never blindly use * in production 🔹 Pro Tip 💡 If you're working with React / Next.js + API, always configure CORS early — it saves hours of debugging. 💬 Have you faced CORS issues before? What was the hardest bug you solved? #WebDevelopment #JavaScript #ReactJS #NextJS #Backend #FullStack #CORS #Programming
To view or add a comment, sign in
-
-
⚛️ React Keys & Reconciliation — A small detail that makes a BIG difference Most developers treat key as just a warning fixer. But under the hood, it’s one of the most important concepts in React performance. Here’s why 👇 React uses a diffing algorithm (reconciliation) to update the DOM efficiently. Instead of re-rendering everything, React tries to figure out: 👉 What changed? 👉 What stayed the same? 👉 What should be updated? This is where keys come in. ❌ When you don’t provide keys (or use wrong ones): • React can’t track elements properly • Unnecessary re-renders happen • Component state gets mixed up (especially in lists) • Performance drops Example mistake: Using index as a key in dynamic lists 😬 ✅ When you use correct keys: • React identifies changes precisely • Only required updates happen • Component state stays intact • Rendering becomes efficient 🧠 Think of keys like identity cards for components Without identity → confusion With identity → precise updates 🔥 Pro Tip: Always use keys that are: ✔ Stable ✔ Unique ✔ Predictable Examples: Good → user.id, product.id Bad → index, Math.random() ⚡ Final thought: React is fast because of reconciliation. But it only works well if you don’t break the algorithm. Keys might look small… …but they directly impact performance + correctness. What’s the worst bug you’ve faced because of wrong keys? 😄 #ReactJS #FrontendDevelopment #WebDevelopment #JavaScript #SoftwareEngineering #TechTips
To view or add a comment, sign in
-
💡React Tip💡 Never pass the setState function directly as a prop to any of the child components like this: const Parent = () => { const [state, setState] = useState({ name: '', age: '' }) . . . return ( <Child setState={setState} /> ) } ✅ The state of a component should only be changed by that component itself. ✅ This ensures your code is predictable. If you pass setState directly to multiple components, it will be difficult to identify from where the state is getting changed. ✅ This lack of predictability can lead to unexpected behavior and make debugging code difficult. ✅ Over time, as your application grows, you may need to refactor or change how the state is managed in the parent component. ✅ If child components rely on direct access to setState, these changes can ripple through the codebase and require updates in multiple places, increasing the risk of introducing bugs. ✅ If sensitive data is part of the state, directly passing setState could potentially expose that data to child components, increasing security risks. ✅ React's component reconciliation algorithm works more efficiently when state and props updates are clearly defined within components. ✅ When child components directly call setState, React may not be able to optimize the rendering process as effectively. Instead of passing setState directly, you can do the following: 1️⃣ Pass data as prop: Pass the data that the child component needs as props, not the setState function itself. This way, you provide a clear interface for the child component to receive data without exposing the implementation details of state. 2️⃣ Pass function as prop: If the child component needs to interact with the parent component's state, you can pass the function as a prop. Declare a function in the parent component and update the state in that function, you can pass this function as a prop to the child component and call it from the child component when needed. 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲. #javascript #reactjs #nextjs #webdevelopment
To view or add a comment, sign in
-
🚀 The Event Loop: Browser vs. Node.js 🌐 Ever wondered how JavaScript stays "fast" despite being single-threaded? The secret sauce is the Event Loop. But depending on where your code runs, the Event Loop wears different hats. 🎩 Here is a quick breakdown of how it works on the Client-side vs. the Server-side: 🖥️ 1. JavaScript in the Browser (Client-Side) In the browser, the Event Loop is all about User Experience. The Goal: Keep the UI responsive. How it works: When a user clicks, scrolls, or fetches data, these actions are added to a task queue. The Flow: The Event Loop constantly checks if the Call Stack is empty. If it is, it pushes the next task from the queue to the stack. This ensures that heavy tasks don't "freeze" the screen while rendering. ⚙️ 2. Node.js (Server-Side) In Node.js, the Event Loop is the backbone of High-Concurrency servers. The Goal: Handle thousands of simultaneous requests without blocking. The Heavy Lifters: For "blocking" tasks like File System (FS) or Database operations, the Event Loop offloads the work to Worker Threads (via the Libuv library). The Callback Cycle: 1. The Event Loop registers a callback for an operation. 2. It hands the task to a worker thread. 3. Once the worker is done, it sends the result back to the queue. 4. The Event Loop picks it up and executes the final callback to send the response. 💡 The Bottom Line Whether you are building a snappy UI or a scalable backend, understanding the Event Loop is the difference between a laggy app and a high-performance system. #JavaScript #NodeJS #WebDevelopment #Programming #SoftwareEngineering #TechTips #react #express #next
To view or add a comment, sign in
-
React Hooks changed the game by allowing us to use state and other features without writing classes. If you are building modern web apps, mastering these hooks is non-negotiable! 💻✨ Here is a quick guide to the most essential React Hooks and when to use them: 🔹 useState – The State Manager Purpose: Manages local component data. Use Cases: Form inputs, counters, toggles, or any dynamic UI updates. 🔹 useEffect – The Lifecycle Handler ⚡ Purpose: Handles side effects (actions outside React's control). Use Cases: API data fetching, setting up timers, or direct DOM manipulation. 🔹 useContext – The Prop-Drilling Killer 🛡️ Purpose: Shares data globally across the component tree. Use Cases: User authentication, Theme switching (Dark/Light mode), or Language settings. 🔹 useRef – The Persistent Reference Purpose: Grabs DOM elements or stores values without triggering a re-render. Use Cases: Focusing an input field, managing scroll positions, or storing previous state values. 🔹 useMemo – The Value Optimizer 🧠 Purpose: Remembers expensive calculation results. Use Cases: Filtering massive datasets or heavy mathematical computations. 🔹 useCallback – The Function Memorizer Purpose: Prevents functions from being recreated on every render. Use Cases: Passing stable functions to optimized child components to prevent lag. 🔹 useReducer – The Complex State Boss Purpose: Manages complex state logic (Redux-style). Use Cases: Multi-step forms or states where one update depends on another. ✨ Why Hooks Matter? Hooks don't just "make things work"—they make your code readable, reusable, and scalable. They separate concerns and keep your components clean. Which Hook do you find most challenging to master? Let's discuss in the comments! 👇 #ReactJS #WebDevelopment #Frontend #JavaScript #CodingTips #ReactHooks #SoftwareEngineering #Programming
To view or add a comment, sign in
-
-
React performance isn't about adding useMemo everywhere. 🚫 It's about measuring first — then fixing the right thing. Most engineers optimize by intuition. They add useMemo, split bundles, wrap everything in memo — and the app is now more complex but no faster. Because they fixed the wrong thing. There are exactly three categories of React performance problems: 1. Too much JavaScript Bundle too large → slow initial load → high Time to Interactive Fix: code splitting, React.lazy, dynamic imports 2. Too much rendering Components re-rendering unnecessarily → laggy interactions Fix: React.memo, useMemo, useCallback — but only where justified 3. Too much browser work Layout thrashing, no virtualisation → dropped frames, janky scroll Fix: separate DOM reads from writes, react-window for long lists The fix for one category can actively make another worse if applied blindly. Wrapping everything in useMemo adds comparison overhead on every render. Splitting every bundle into tiny chunks creates more network requests. Optimizing the wrong category = more complexity, zero gain. The process that actually works: Reproduce → Measure → Identify the category → Fix that specific thing → Measure again. Chrome DevTools Performance tab tells you where the browser is struggling. React DevTools Profiler tells you which components are the problem. Two different tools. Two different questions. Know which one to reach for. One thing that surprised me — layout thrashing is almost invisible until you know what to look for. Reading offsetHeight and writing style, height in the same loop forces the browser to recalculate layout on every single iteration. Separating all reads from all writes drops it to one calculation. Same code. Completely different performance. Small things. Large consequences at scale. Sharing one deep dive at a time. #React #WebPerformance #FrontendEngineering #JavaScript #PlatformEngineering
To view or add a comment, sign in
-
-
Why do we specifically pass 'props' into 'super(props)' in a React component constructor? It is one of those things many developers do out of habit without realizing the actual mechanism behind it. While calling 'super()' is a JavaScript requirement to initialize the 'this' keyword, passing 'props' is a very specific React requirement for the constructor phase. The reason is simple: visibility. When you call 'super(props)', you are telling the parent 'React.Component' class to initialize 'this.props' for you immediately. If you only call 'super()' without the argument, 'this.props' will be undefined inside the constructor. React eventually assigns props to the instance anyway, but that happens after the constructor has finished running. If your logic requires you to access a property or compute a state based on a prop right inside the constructor, forgetting the 'props' argument will crash your logic. You would be trying to read from a variable that hasn't been wired up to the instance yet. Even though modern React code bases have shifted to Functional Components where this ceremony is gone, the underlying logic of when data becomes available to an instance is a core part of the library’s history. It is a small detail that perfectly illustrates how React works under the hood. #ReactJS #Javascript #SoftwareEngineering #FrontendDevelopment #WebDev #CodingTips
To view or add a comment, sign in
-
🔥 Why useEffect Runs Twice in React Strict Mode If you’ve seen this while developing with React: JSX code : useEffect(() => { console.log("Effect ran"); }, []); You expect this to run once. But in development, the console shows: Effect ran Effect ran So… is React broken? Not really. 🧠 What’s Actually Happening When React Strict Mode is enabled, React intentionally runs some lifecycle logic twice in development. This includes useEffect. Why? Because React is checking if your effects are safe and predictable. 🔍 What React Is Testing React wants to detect bugs like: Side effects that are not cleaned up Code that relies on running only once Hidden memory leaks To do that, React: 1️⃣ Mounts the component 2️⃣ Runs the effect 3️⃣ Immediately unmounts it 4️⃣ Mounts it again If your cleanup logic is correct, everything still works. ✅ Example with Cleanup JSX code useEffect(() => { const id = setInterval(() => { console.log("running"); }, 1000); return () => clearInterval(id); }, []); This ensures no leftover side effects. 🎯 Important Note This only happens in development. Production builds run effects normally. #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #WebDevelopment #LearningInPublic
To view or add a comment, sign in
-
⚛️ React Tip: When Should You Use useCallback? While working on React applications, one common performance issue developers face is unnecessary component re-renders. One hook that often comes up in this discussion is useCallback. But many developers (including me earlier) either overuse it or use it incorrectly. So here’s a simple way to understand it. 🔹 What does useCallback do? `useCallback` memoizes a function. This means React will reuse the same function instance unless its dependencies change. Example 👇 const handleClick = useCallback(() => { console.log("Button clicked"); }, []); Without `useCallback`, a new function is created every time the component re-renders. Most of the time this isn’t a problem. But it becomes important when passing functions to memoized child components. 🔹 Example scenario Imagine a parent component passing a function as a prop to a child component wrapped with `React.memo`. If the function reference changes on every render, the child component will also re-render unnecessarily. Using `useCallback` helps keep the function reference stable, preventing those extra renders. 🔹 When should you actually use it? ✅ When passing callbacks to memoized components ✅ When the function is a dependency in another hook ✅ When optimizing large component trees ⚠️ When NOT to use it: • For every function in your component • When there is no performance issue • Just because someone said it improves performance 💡 One important lesson I’ve learned: Optimization should be intentional, not automatic. React already does a lot of work under the hood. Use hooks like `useCallback` only when they actually solve a problem. Curious to hear from other developers 👇 Do you use `useCallback` often, or do you prefer optimizing only after profiling? #reactjs #frontenddevelopment #javascript #webdevelopment #reacthooks #softwareengineering #coding
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
well explained 😀