What is CSP (Content Security Policy)
A CSP can be used to control the resources that a document is allowed to load. This is primarily used for protection against cross-site scripting (XSS) attacks.
My blog posts about web development, programming, and other topics.
A CSP can be used to control the resources that a document is allowed to load. This is primarily used for protection against cross-site scripting (XSS) attacks.
Cross-site scripting (XSS) is a web vulnerability where attackers inject malicious client-side scripts (usually JavaScript) into trusted websites. XSS can be prevented by escaping user input and avoiding direct HTML injection. Prevention: React JSX auto-escape content. Avoid dangerouslySetInnerHTML input sanitize/validate Use CSP
Dependency vulnerabilities come from third-party libraries, so we regularly audit and update packages to keep the application secure. Comes from npm packages / external libraries Even if your code is safe → dependency can be unsafe Common in outdated packa How to detect npm audit yarn audit
Polling involves a client repeatedly sending requests to a server at regular to check for new updates or new data. It operates on the standard HTTP request-response model. Types of polling? Short Polling Long Polling What is Short Polling? Short polling: In Short polling it means the client sends request to the server at fixed intervals, regarding whether data has changed. How Short polling works? Client send http request Server immediately responds with current data. Client waits for a fixewd time (e.g 5 seconds). Cycle repeat endlessly. Use Cases of Short Polling? Simple dashboard. Periodic status checks. Low-priority data refresh. Legacy system. Backup/fallback mechanism. Drawbacks of Short Polling Requests even when nothing changes. High server and network load and request. Delayed updates. Battery drain on mobile. Poor scalability with many clients. What is Long Polling? The server holds the client's request open until new data is available or timeout is reached. Once data is sent, the connection closes, and the client immediately send a new request. How Long polling works? Client sends an HTTP req. Server does not respond immediately. Server waits for new data or timeout. When data changes ---> server reponds. Then Client send new request. Use Cases of Long Polling? Notification systems (older) Chat apps (older) Real-time feed(legacy) Environment where web socket is blocked. Drawbacks of Long Polling? Holds server connection open. More complex server logic. Still not true real time. Difficult to scale. Can overload.
Flow - Understand → Reproduce → Identify → Fix → Test → Deploy → Prevent If an issue occurs in production, first I try to understand the problem by checking logs, monitoring tools like Sentry, and browser console errors. Then I check recent deployments or commits because production issues are often caused by recent changes. After that I try to reproduce the issue locally or in staging. Once reproduced, I debug using tools like Chrome DevTools, checking network requests, API responses, and component states. After identifying the root cause, I implement the fix and test it locally and in staging. If it’s a critical issue, we deploy a hotfix. Finally, I ensure proper tests, logging, and error handling are added to prevent similar issues in the future.
Aggregation is used to process and transform data and return computed results (like sum, count, average, grouping). Why We Use Aggregation: We use aggregation when we need: Grouping data Calculations (sum, avg, count) Filtering large datasets Data transformation Analytics / reports Example use cases: Total sales per customer Average salary per department Count users by city //orders { "customer": "Zahid", "amount": 100 } { "customer": "Ali", "amount": 200 } { "customer": "Zahid", "amount": 300 } db.orders.aggregate([ { $group: { _id: "$customer", totalAmount: { $sum: "$amount" } } } ]); //output [ { "_id": "Zahid", "totalAmount": 400 }, { "_id": "Ali", "totalAmount": 200 } ]
MongoDB is a NoSQL document database that stores data in JSON-like BSON documents instead of tables. SQL: Tables-> Rows -> Fixed Schema -> JOIN MongoDB: Collections -> Collections -> Documents -> Flexible Schema -> $lookup A document is a JSON-like object stored inside a collection. A collection is a group of documents (similar to a table in SQL). Every MongoDB document has a unique _id field automatically generated. BSON is Binary JSON , the format MongoDB uses internally to store data. MongoDB Queries : db.users.find() -> Find all users db.users.find({ age: 25 }) -> Find user by age db.users.insertOne({ name: "Zahid",age: 28}) -> Insert document db.users.updateOne({ name: "Zahid" }, { $set: { age: 29 } }) -> Update user db.users.deleteOne({ name: "Zahid" }) -> Delete User
LCP(large content paint) measures how fast the main content of the page becomes visible to the user. we can compress images Preload critical images/assets and Reduce JS bundle size using SSR / SSG / edge caching. Good score: ≤ 2.5 seconds FID / INP (First Input Delay / Interaction to Next Paint) : It measure how fast the page responds when a user interacts (click, tap, input). Reduce main-thread work by splitting JS bundles and deferring non-critical scripts. Good score: ≤ 100 ms CLS( cumulative layout shift): It meassure how much the layout shifts unexpectedly. CLS Always define image dimensions Reserve space for dynamic content Use skeleton loaders Avoid inserting content above existing content good score: ≤ 0.1
CLS measures unexpected layout shifts while the page is loading. We prevent it by defining : Image dimensions Reserving layout space Avoiding dynamic content shifts. Good: <0.1
Reconciliation is the process where React compares the old and new Virtual DOM to determine what needs to change in the real DOM. React Fiber is the new architecture introduced in React 16 that implements reconciliation in a more efficient way. Fiber enables incremental rendering, priority scheduling, and interruptible updates. So reconciliation is the concept, and Fiber is the engine that powers it.
PM2 is a production process manager that can run applications in cluster mode while also providing features like automatic restarts, monitoring, logging, and zero-downtime deployment.
Node js is single thread it allow us to create multiple worker processes to utilize CPU cores. It helps to improve the performance and handle more concurrent requests by running multiple instance of the application on same machine.
It is measure delay between user first interaction and browser responds. It mainly happened due to js main thread block by heavy js. We improve it by reducing JS execution time and using code splitting. Good: < 100ms
A CDN is a geographically distributed network of servers that delivers static content from the nearest location to the user. We use it to reduce latency, improve performance, handle traffic spikes, and enhance security with features like DDoS protection and caching.
LCP measures how fast main content becomes visible to user. We can improve LCP optimize hero image reduce bundle js size and pre load critical assets. In next js we can use SSG/ISR technique to fast load.
A brute force attack is when an attacker repeatedly tries multiple password combinations to gain unauthorized access. To prevent this, I implement rate limiting on login endpoints, account lock mechanisms, and CAPTCHA verification. I also enforce strong password policies and use two-factor authentication for extra security.
REST APIs follow a stateless request-response model and are ideal for CRUD operations. Each request is independent and connection closes after response. WebSockets create a persistent bidirectional connection between client and server. They are suitable for real-time features like chat and live notifications. REST is better for structured data fetching, while WebSockets are used when instant updates are required.
Reconciliation is the process where React compares the new Virtual DOM with the previous Virtual DOM to determine the minimal changes needed in the real DOM. React uses a diffing algorithm that: Compares elements of the same type Uses keys to track list items Updates only the parts of the DOM that changed
React rendering lifecycle has two major phases: Render Phase and Commit Phase. Render Phase: React calls the component function to compute the JSX. It builds a new Virtual DOM and compares it with the previous one. Commit Phase: React applies the minimal changes to the real DOM.
Stable Server Components (RSC): Allows components to run on the server by default. New use() API: Allows directly awaiting promises inside components. React 19 introduces Server Actions: Forms can call server functions without creating separate API routes. useFormStatus() – track pending form submissions useFormState() – manage form state easily Better Hydration & Streaming: Smarter hydration error handling, Better streaming performance, More efficient rendering of async content
Before React-19 version we can use ssr in react with the help of manual setup of node+reactDOM server. import ReactDOMServer from 'react-dom/server' const html = ReactDOMServer.renderToString( ) following: Render React components to HTML on the server Send the HTML to the browser Hydrate it using ReactDOM.hydrate() From React 18, we could also use: renderToPipeableStream() (streaming SSR) renderToReadableStream() (for edge runtimes)
It pre-render the page and sends HTML for SEO and fast first paint. Hydration enables the event handling, client side routing and state update. Without hydration, Next.js pages would be static like plain HTML.
Hydration mismatch error happens while server generated html content does not match with client render output. This usually occurs due to non-deterministic values like Math.random(), timestamps, locale differences, or conditional rendering based on window or browser-only APIs.
SAFE: It’s safe when the value you pass to dangerouslySetInnerHTML is fully static. UNSAFE: It’s not safe when that value includes unsanitized user input or other untrusted data, because someone could inject HTML/script (e.g. ...) and run code in the page.
The Event Loop is a mechanism that allows Node.js to perform non-blocking I/O operations. It continuously checks the call stack and callback queue, executing callbacks once the stack is empty.
The sitemap is used so search engines can discover and index your site; product pages are added so those important, public URLs are explicitly included and get better crawling and SEO.
Caching is a technique to store the previously computed or fetched data so we do not need to re-computed or refetch it again. In JavaScript, we cache data using objects, Maps, closures, or browser storage. In React, caching is commonly done using memoization hooks like useMemo, useCallback, API cache libraries like React Query, or browser storage.”
LCP measures how fast the main content of the page becomes visible to the user. “To improve LCP, I optimize hero images, preload critical assets, and reduce render-blocking scripts.” Common causes of poor LCP Large unoptimized images Slow server response Render-blocking CSS/JS Client-side heavy rendering How to improve LCP Optimize & compress images Preload critical images/assets Reduce JS bundle size Use SSR / SSG / edge caching FID / INP (First Input Delay / Interaction to Next Paint) What it is Measures how fast the page responds when a user interacts (click, tap, input). “To improve FID/INP, I reduce main-thread work by splitting JS bundles and deferring non-critical scripts.” Common causes of poor FID / INP Heavy JavaScript execution Long main-thread tasks Large synchronous scripts CLS: Measures visual stability — how much the layout shifts unexpectedly. “To prevent CLS, I reserve layout space and ensure all images have fixed dimensions.” Common causes of poor CLS Images without width/height Dynamically injected content Ads, banners, fonts loading late How to improve CLS Always define image dimensions Reserve space for dynamic content Use skeleton loaders Avoid inserting content above existing content
TypeScript is a superset of JavaScript that adds static typing. \n It helps catch errors at compile time, improves code readability, and makes large-scale applications easier to maintain. \n It improves code quality, reduces runtime bugs, and enhances developer productivity. \n TypeScript also provides better IntelliSense, refactoring, and documentation.
SSR renders the page on every request. SSG + ISR serves pre-built static pages and updates them periodically or on demand. 1️⃣ SSR – Server-Side Rendering How it works User requests a page Server runs code (DB/API calls) HTML is generated at request time HTML is sent to the browser Key characteristics Page is rendered on every request Database/API is called every time HTML is always fresh Pros Always up-to-date data Good for personalized or auth-based pages Cons Slower than SSG Higher server and DB load Limited CDN caching Best use cases Dashboards Admin panels User-specific pages Real-time data 2️⃣ SSG + ISR – Static Site Generation with Incremental Static Regeneration How it works Pages are generated at build time HTML is stored and served from CDN After a defined time (revalidate), the page is regenerated in the background New users get updated HTML without rebuilding the whole app Key characteristics Pages are static Extremely fast (CDN-served) Database is not called on every request Pros Very fast performance Excellent SEO Low server cost Scales easily Cons Data is not real-time Slight delay before updates appear Best use cases Blogs Marketing pages Documentation Portfolio websites
It is google performance metrics. which is measure user real experience specially page load speed, interactivity and layout stability.
Interface : when modeling real objects or entities that may be extended. eg: interface User { id: string; name: string; isActive: boolean; } // extendable interface Admin extends User { permissions: string[]; } Records : when creating a strict key-value mapping where keys come from a union type and all keys must be present. eg: type Status = "loading" | "success" | "error"; const statusText: Record = { loading: "Loading", success: "Done", error: "Failed", };
Server-Side Rendering (SSR) generates full HTML on the server for every request, offering superior SEO and fast initial loads, making it ideal for content-heavy sites. Client-Side Rendering (CSR) sends a blank page to the browser, which renders content using JavaScript, providing higher interactivity for dynamic web apps but slower initial performance. Rendering Location: SSR renders on the server; CSR renders in the browser (client). SEO Performance: SSR is superior for SEO because search engines receive fully rendered HTML, whereas CSR requires additional effort to ensure proper indexing. Initial Page Load: SSR provides faster initial load times, beneficial for users on slower connections, while CSR often has a slower initial load due to JavaScript execution. Interactivity: CSR is superior for rich, interactive user experiences (e.g., social media feeds, SPAs) as updates occur without reloading the page. Server/Client Load: SSR increases the load on the server, while CSR shifts the rendering load to the client's browser.
Amazon S3 (Simple Storage Service) is a highly scalable, durable, and secure object storage service used to store and retrieve any amount of data, making it ideal for backups, media storage, and cloud-native applications.
JavaScript is often described as a single-threaded language, yet it can handle asynchronous operations like API calls, timers, and user interactions without blocking the UI. The secret behind this behavior is the JavaScript Event Loop. What Does “Single-Threaded” Mean? Being single-threaded means JavaScript can execute only one task at a time in the call stack. If a long-running task blocked the stack, the entire application would freeze. To avoid this, JavaScript uses asynchronous mechanisms powered by the event loop. Key Components of the Event Loop To understand the event loop, you need to know these core parts: 1. Call Stack Executes synchronous JavaScript code Follows Last In, First Out (LIFO) Functions are pushed when called and popped when finished 2. Web APIs Provided by the browser (or Node.js) Handle async tasks like: setTimeout DOM events fetch These APIs run outside the call stack 3. Callback Queue (Macrotask Queue) Stores callbacks from: setTimeout setInterval UI events 4. Microtask Queue Higher-priority queue Includes: Promises (.then, .catch, .finally) queueMicrotask MutationObserver 5. Event Loop Continuously checks: Is the call stack empty? Are there microtasks to execute? Are there macrotasks waiting?
Node.js allows JavaScript to run outside the browser using an event-driven, non-blocking I/O model, making it highly efficient for building fast and scalable backend services.
Next.js enhances React by providing server-side rendering, file-based routing, API routes, and performance optimizations, making it ideal for SEO-friendly and production-ready applications.
React simplifies UI development with its component-based architecture, virtual DOM, and powerful ecosystem, making it the go-to library for building scalable and maintainable user interfaces.