Blackhole textureSpace texture

Blog — Sakib U. SiddiQuie

Read the latest blog posts by Sakib U. SiddiQuie on fullstack development, AI, and tech insights.

My Blog

Welcome to this page, read my blogs if you find something interesting, Get in touch and subscribe to the newsletter.

#Blogs

Mastering SQL for Superset

🚀 Mastering SQL for Superset: Create Datasets, Reports, Charts & Dashboards Like a Pro If you’ve ever stared at a blank chart in Superset wondering “Where do I even start?”, you’re not alone. Apache Superset is an incredibly powerful open-source BI tool, but to truly unlock its power, you need strong SQL skills — especially when building custom datasets, advanced charts, or KPI-rich dashboards. In this blog, I’ll walk you through the SQL techniques and patterns you need to master to create datasets that drive insightful reports and dashboards in Superset — from the ground up. 📌 Why SQL Matters in Superset Superset gives you two main ways to visualize data: Direct from a table or view Using custom SQL queries saved as "Virtual Datasets" To build flexible, reusable, and performance-optimized charts and dashboards, you'll want to master SQL patterns that do the heavy lifting before data even hits your visuals. 🧱 1. Building SQL Datasets for Superset Your dataset should be: Clean: Use AS to alias messy column names Pre-aggregated (when needed) Rich in dimensions and metrics 🛠️ Example: Sales Dataset SELECT o.order_id, o.order_date, c.customer_name, p.product_name, p.category, o.quantity, o.unit_price, (o.quantity * o.unit_price) AS total_amount, c.country FROM orders o JOIN customers c ON o.customer_id = c.customer_id JOIN products p ON o.product_id = p.product_id WHERE o.order_date >= CURRENT_DATE - INTERVAL '1 year' 📊 2. Pre-Aggregated Summary Datasets These are perfect for bar charts, pie charts, KPIs. SELECT category, SUM(quantity) AS total_units_sold, SUM(quantity * unit_price) AS total_revenue FROM orders o JOIN products p ON o.product_id = p.product_id GROUP BY category ORDER BY total_revenue DESC; 💡 Save this as a dataset in Superset: SQL Lab → Write Query → Save Dataset → Use in charts 🧠 3. Use CASE Statements for Conditional Metrics Add categories like revenue tiers or performance groups: SELECT country, CASE WHEN total_amount >= 10000 THEN 'High' WHEN total_amount >= 5000 THEN 'Medium' ELSE 'Low' END AS revenue_tier FROM ( SELECT country, SUM(quantity * unit_price) AS total_amount FROM orders o JOIN customers c ON o.customer_id = c.customer_id GROUP BY country ) t Now you can filter your dashboards by tier! 📈 4. Time Series Datasets for Line Charts Time-based visualizations love clean datetime groupings. SELECT DATE_TRUNC('month', order_date) AS order_month, SUM(quantity * unit_price) AS monthly_sales FROM orders GROUP BY order_month ORDER BY order_month; ✅ Use in Superset Line Chart, Area Chart, Time Pivot 🪜 5. Funnel and Stage Reports Perfect for marketing or sales dashboards. SELECT lead_stage, COUNT(*) AS leads_count FROM leads GROUP BY lead_stage ORDER BY FIELD(lead_stage, 'Contacted', 'Qualified', 'Proposal', 'Won'); Funnel chart (if available) or horizontal bar charts work great here. 🔥 6. Pivot-Ready Heatmap Data Let’s prepare a pivot table of revenue per product, per month. SELECT product_name, DATE_TRUNC('month', order_date) AS month, SUM(quantity * unit_price) AS revenue FROM orders o JOIN products p ON o.product_id = p.product_id GROUP BY product_name, month ✅ In Superset: Use Pivot Table → Rows = Product, Columns = Month 🗺️ 7. Geo-Ready Datasets for Map Visualizations Include latitude/longitude or geo fields. SELECT customer_name, city, country, latitude, longitude, SUM(quantity * unit_price) AS revenue FROM customers c JOIN orders o ON c.customer_id = o.customer_id GROUP BY customer_name, city, country, latitude, longitude ✅ Use Superset Map, Country Map, or Geo Heatmaps. 📏 8. Window Functions for Advanced Metrics Window functions are your secret weapon for cumulative metrics, rankings, etc. SELECT customer_name, order_date, quantity * unit_price AS order_amount, SUM(quantity * unit_price) OVER (PARTITION BY customer_name ORDER BY order_date) AS cumulative_spend FROM orders o JOIN customers c ON o.customer_id = c.customer_id Use this for customer lifetime value or behavior tracking. 🧰 9. Creating Virtual Datasets in Superset Go to SQL Lab → SQL Editor Run your custom query Click Save as Dataset Give it a name, schema, and description Use it in Charts and Dashboards This allows reusability and version control of complex SQL logic. 💡 10. Dashboard Design Tips Use filters: Time range, category, country Mix chart types: KPIs, tables, pie, line, bar Arrange grid layout with key metrics on top Optimize SQL for speed – avoid huge unfiltered queries Use drilldowns if enabled for interactive exploration ✅ Sample KPIs You Can Build with SQL Sure! Here's your KPI info formatted neatly as a table that should fit well into your content: KPI Name SQL Expression Total Revenue SUM(quantity unit_price) Orders Count COUNT(DISTINCT order_id) Avg Order Size AVG(quantity unit_price) Repeat Rate Complex logic using COUNT + GROUP BY Top Product SELECT product_name ORDER BY SUM(sales) If you want it in any other style or with more detail, just let me know! ⚙️ Performance Tips for Superset SQL Always filter large date ranges (e.g., WHERE order_date >= '2023-01-01') Use materialized views for heavy joins Index filter columns (e.g., order_date, product_id) Avoid SELECT * – use explicit column names Test your query with EXPLAIN or Superset SQL Lab 📚 Tools to Practice Superset Live Demo Mockaroo – generate sample datasets SQL Fiddle – test your queries online Mode SQL Tutorial 🧠 Final Thoughts By mastering the right SQL techniques, you’ll move from static dashboards to dynamic, deeply analytical Superset experiences — ones that stakeholders love and rely on. Superset is only as powerful as the data you feed it, and now you’re equipped to craft that data like a pro. If you found this useful, stay tuned for more BI and SQL deep-dives — or drop a comment below and share what dashboards you’re building! Happy Querying 👨‍💻👩‍💻!

#Blogs

🧠 All the APIs You Should Know (Part 3: Recommendations, Cheatsheets & Real-World Tips)

Awesome — now that we’ve completed all the core API types with working code examples, let’s wrap up this series with: 🧠 All the APIs You Should Know (Part 3: Recommendations, Cheatsheets & Real-World Tips) Whether you're designing a scalable backend, integrating real-time features, or connecting to third-party services — knowing which API to use and when can save you hours (or days) of refactoring. Here’s the final breakdown: 🧩 When to Use Which API Use Case-------------------------------Recommended API Type----------------------------Why It’s Best CRUD apps / backend APIs---------- REST or GraphQL-------- REST is universal, GraphQL is flexible Frontend-heavy apps----------------- GraphQL Precise data fetching, fewer round-trips Real-time |-Use Case------------------------|-Recommended API Type------|-Why It’s Best | | ------------------------------- | ------------------------- | ---------------------------------------- | | CRUD apps / backend APIs--------| REST or GraphQL-----------| REST is universal, GraphQL is flexible---| | Frontend-heavy apps-------------| GraphQL-------------------| Precise data fetching, fewer round-trips-| | Real-time chat / games----------| WebSocket-----------------| Bi-directional, low-latency comms--------| | Notifications / push updates----| SSE or WebSocket----------| SSE is simpler for one-way data----------| | P2P video / file transfer-------| WebRTC--------------------| Direct browser-to-browser communication--| | Payment events / 3rd party push-| Webhooks------------------| Lightweight + easy to integrate----------| | Background jobs & retries-------| Message Queues (RabbitMQ)-| Decouples systems and handles load-------| | Internal microservices----------| gRPC or REST--------------| gRPC for speed and structure-------------| | Streaming logs / analytics------| Kafka or SSE--------------| Supports massive real-time ingestion-----| | Enterprise integrations---------| SOAP----------------------| Still used in banks, insurance, legacy---| | Authenticated APIs--------------| OAuth2 + JWT--------------| Secure, token-based authentication-------| 🛠 Suggested Tools & Libraries | API Type | Node.js Library | Frontend Tooling | | ------------- | --------------------------- | ----------------------------- | | REST | `express`, `fastify` | `axios`, `fetch` | | GraphQL | `apollo-server`, `graphql` | `@apollo/client`, URQL | | WebSocket | `ws`, `socket.io` | `socket.io-client`, native WS | | Webhook | `express`, `body-parser` | Postman, webhook.site | | SSE | Native Express | `EventSource` | | WebRTC | Native APIs + `simple-peer` | `simple-peer`, raw WebRTC | | gRPC | `@grpc/grpc-js` | Proxy needed for browsers | | Message Queue | `amqplib`, `bullmq` | Background jobs only | | Kafka | `kafkajs`, `node-rdkafka` | Usually backend-only | | SOAP | `soap` | Insomnia, SoapUI for testing | | Auth (JWT) | `jsonwebtoken`, `bcryptjs` | Store in cookies/localStorage | 📋 Cheatsheet Summary 🔧 REST ✅ Simple, widely supported ❌ Verbose for nested data GET /users POST /users PUT /users/:id DELETE /users/:id 🔮 GraphQL ✅ One endpoint, one query ❌ Caching is harder query { users { id, name } } mutation { addUser(name: "John") { id } } ⚡ WebSocket ✅ Full-duplex, low latency ❌ Harder to scale and test const socket = new WebSocket('ws://localhost'); socket.send('hi'); socket.onmessage = e => console.log(e.data); 📬 Webhooks ✅ Good for 3rd party triggers ❌ Requires retry handling & validation app.post('/webhook', (req, res) => { console.log(req.body); }); 🛰 Server-Sent Events ✅ Simpler than WebSockets (for one-way) ❌ Only server → client res.setHeader('Content-Type', 'text/event-stream'); res.write('data: Hello\n\n'); 🎥 WebRTC ✅ Real-time video / audio ❌ Requires signaling & STUN/TURN infra const peer = new RTCPeerConnection(); peer.createOffer().then(...); 🧵 gRPC ✅ Fast, typed, structured ❌ Needs proto files, not browser-native service UserService { rpc GetUser (UserRequest) returns (UserResponse); } 📨 Message Queues ✅ Scalable, async processing ❌ Adds infra complexity channel.sendToQueue('jobs', Buffer.from('email-task')); 💧 SOAP ✅ Contract-based, secure ❌ Verbose XML, not frontend-friendly <soap:Envelope> <soap:Body> <SayHello> <name>Dev</name> </SayHello> </soap:Body> </soap:Envelope> 🔐 JWT Auth / OAuth2 ✅ Secure and modern ❌ Needs proper storage and validation const token = jwt.sign({ user }, 'secret'); 🧠 Final Thoughts REST and GraphQL cover 90% of use cases WebSockets or SSE bring in real-time magic Webhooks, gRPC, and queues add scalability & reliability Don’t ignore old tech like SOAP — it’s still around in enterprise systems ✨ What to Do Next Pick any of api and use this post as reference and build a project. Try mixing APIs in a single app (e.g., REST + WebSockets + Queue) Build a small SaaS or dashboard using these APIs as building blocks

#web-development, #react.js, #fullstack, #api

💻 All the APIs You Should Know (Part 2: Real Code Examples in Node.js + React)

Awesome — let's roll into Part 2: Code Examples 💻 💻 All the APIs You Should Know (Part 2: Real Code Examples in Node.js + React) In this section, we’re not just talking theory — we're going hands-on. You’ll see how to: Build each API type in Node.js (Express/Apollo/ws) Connect to it from React (or Angular if noted) Understand where each API shines through code If you missed Part 1 (theory + concepts), go back here — but if you're ready to get your hands dirty, let’s start! 🧱 REST API – Node + React 🛠 Backend (Node.js + Express) // server.js const express = require('express'); const app = express(); app.use(express.json()); const users = [{ id: 1, name: 'Alice' }]; app.get('/users', (req, res) => { res.json(users); }); app.post('/users', (req, res) => { const newUser = { id: Date.now(), ...req.body }; users.push(newUser); res.status(201).json(newUser); }); app.listen(3001, () => console.log('REST API running on http://localhost:3001')); 🖥 Frontend (React) // App.jsx import { useState, useEffect } from 'react'; function App() { const [users, setUsers] = useState([]); const [name, setName] = useState(''); useEffect(() => { fetch('http://localhost:3001/users') .then(res => res.json()) .then(setUsers); }, []); const handleAdd = async () => { const res = await fetch('http://localhost:3001/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name }), }); const newUser = await res.json(); setUsers([...users, newUser]); setName(''); }; return ( <> <h1>Users</h1> <input value={name} onChange={e => setName(e.target.value)} /> <button onClick={handleAdd}>Add User</button> <ul>{users.map(u => <li key={u.id}>{u.name}</li>)}</ul> </> ); } 🔮 GraphQL – Node + React 🛠 Backend (Apollo Server) // graphql-server.js const { ApolloServer, gql } = require('apollo-server'); const typeDefs = gql` type User { id: ID name: String } type Query { users: [User] } type Mutation { addUser(name: String!): User } `; let users = [{ id: 1, name: 'Alice' }]; const resolvers = { Query: { users: () => users, }, Mutation: { addUser: (_, { name }) => { const user = { id: Date.now(), name }; users.push(user); return user; }, }, }; const server = new ApolloServer({ typeDefs, resolvers }); server.listen(4000).then(({ url }) => console.log(`GraphQL ready at ${url}`)); 🖥 Frontend (React + Apollo Client) npm install @apollo/client graphql // App.jsx import { gql, useQuery, useMutation, ApolloProvider, ApolloClient, InMemoryCache } from '@apollo/client'; const client = new ApolloClient({ uri: 'http://localhost:4000', cache: new InMemoryCache() }); const GET_USERS = gql`query { users { id name } }`; const ADD_USER = gql`mutation($name: String!) { addUser(name: $name) { id name } }`; function Users() { const { data } = useQuery(GET_USERS); const [addUser] = useMutation(ADD_USER); const [name, setName] = useState(''); return ( <> <input value={name} onChange={e => setName(e.target.value)} /> <button onClick={() => addUser({ variables: { name } })}>Add</button> <ul>{data?.users.map(u => <li key={u.id}>{u.name}</li>)}</ul> </> ); } export default function App() { return ( <ApolloProvider client={client}> <Users /> </ApolloProvider> ); } 🔌 WebSockets – Node + React 🛠 Backend (WebSocket Server) // ws-server.js const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', ws => { ws.send('👋 Hello from server!'); ws.on('message', message => { console.log('Received:', message); }); }); 🖥 Frontend (React) // App.jsx import { useEffect } from 'react'; function App() { useEffect(() => { const socket = new WebSocket('ws://localhost:8080'); socket.onmessage = e => console.log('Server:', e.data); socket.onopen = () => socket.send('Hello from client!'); }, []); return <h1>WebSocket Test</h1>; } 📬 Webhooks – Node.js 🛠 Webhook Listener (Server) // webhook-listener.js const express = require('express'); const app = express(); app.use(express.json()); app.post('/webhook', (req, res) => { console.log('📦 Webhook received:', req.body); res.sendStatus(200); }); app.listen(9000, () => console.log('Listening for webhooks on port 9000')); 🧪 To Test It: You can POST to it manually or use Webhook.site or tools like curl or Postman: curl -X POST http://localhost:9000/webhook -H "Content-Type: application/json" -d '{"event": "order_placed"}' 📡 Server-Sent Events (SSE) 🛠 Node.js SSE Server // sse-server.js const express = require('express'); const app = express(); app.get('/events', (req, res) => { res.setHeader('Content-Type', 'text/event-stream'); setInterval(() => { res.write(`data: ${Date.now()}\n\n`); }, 1000); }); app.listen(7070, () => console.log('SSE running on port 7070')); 🖥 React SSE Client // App.jsx import { useEffect } from 'react'; function App() { useEffect(() => { const source = new EventSource('http://localhost:7070/events'); source.onmessage = e => console.log('Update:', e.data); }, []); return <h1>Server-Sent Events</h1>; } 💧 SOAP – Node.js (With soap Package) SOAP is XML-based and contract-driven. We'll use a mock SOAP service with Node.js using the soap package. 🧪 This is rare in new projects but shows up in legacy & enterprise integrations. 🛠 SOAP Server (Node.js) npm install soap express // soap-server.js const soap = require('soap'); const express = require('express'); const app = express(); const PORT = 8001; const service = { HelloService: { HelloServicePort: { sayHello(args) { return { message: `Hello, ${args.name}` }; }, }, }, }; const wsdl = ` <definitions name="HelloService" targetNamespace="http://www.examples.com/wsdl/HelloService.wsdl" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <message name="SayHelloRequest"> <part name="name" type="xsd:string"/> </message> <message name="SayHelloResponse"> <part name="message" type="xsd:string"/> </message> <portType name="Hello_PortType"> <operation name="sayHello"> <input message="tns:SayHelloRequest"/> <output message="tns:SayHelloResponse"/> </operation> </portType> <binding name="Hello_Binding" type="tns:Hello_PortType"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="sayHello"> <soap:operation soapAction="sayHello"/> <input><soap:body use="literal"/></input> <output><soap:body use="literal"/></output> </operation> </binding> <service name="HelloService"> <port name="HelloServicePort" binding="tns:Hello_Binding"> <soap:address location="http://localhost:${PORT}/wsdl"/> </port> </service> </definitions> `; app.listen(PORT, function () { soap.listen(app, '/wsdl', service, wsdl); console.log(`SOAP service listening at http://localhost:${PORT}/wsdl`); }); 🎥 WebRTC – Browser Only (P2P) WebRTC works peer-to-peer in the browser but needs signaling (like WebSocket) to exchange info first. Here’s a simple demo setup: 🖥 Frontend (React or Vanilla JS) <!-- index.html --> <video id="localVideo" autoplay muted></video> <video id="remoteVideo" autoplay></video> <script> const localVideo = document.getElementById('localVideo'); const remoteVideo = document.getElementById('remoteVideo'); navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(stream => { localVideo.srcObject = stream; const peer1 = new RTCPeerConnection(); const peer2 = new RTCPeerConnection(); stream.getTracks().forEach(track => peer1.addTrack(track, stream)); peer1.onicecandidate = e => e.candidate && peer2.addIceCandidate(e.candidate); peer2.onicecandidate = e => e.candidate && peer1.addIceCandidate(e.candidate); peer2.ontrack = e => { remoteVideo.srcObject = e.streams[0]; }; peer1.createOffer() .then(offer => peer1.setLocalDescription(offer)) .then(() => peer2.setRemoteDescription(peer1.localDescription)) .then(() => peer2.createAnswer()) .then(answer => peer2.setLocalDescription(answer)) .then(() => peer1.setRemoteDescription(peer2.localDescription)); }); </script> ⚙️ gRPC – Node.js (Protocol Buffers) We'll use @grpc/grpc-js and @grpc/proto-loader. 📄 hello.proto syntax = "proto3"; service HelloService { rpc SayHello (HelloRequest) returns (HelloReply); } message HelloRequest { string name = 1; } message HelloReply { string message = 1; } 🛠 Server npm install @grpc/grpc-js @grpc/proto-loader // grpc-server.js const grpc = require('@grpc/grpc-js'); const protoLoader = require('@grpc/proto-loader'); const packageDef = protoLoader.loadSync('hello.proto'); const grpcObject = grpc.loadPackageDefinition(packageDef); const helloPackage = grpcObject.HelloService; const server = new grpc.Server(); server.addService(helloPackage.service, { SayHello: (call, callback) => { callback(null, { message: `Hello ${call.request.name}` }); }, }); server.bindAsync('0.0.0.0:50051', grpc.ServerCredentials.createInsecure(), () => { server.start(); }); 🖥 Client // grpc-client.js const grpc = require('@grpc/grpc-js'); const protoLoader = require('@grpc/proto-loader'); const packageDef = protoLoader.loadSync('hello.proto'); const grpcObject = grpc.loadPackageDefinition(packageDef); const client = new grpcObject.HelloService('localhost:50051', grpc.credentials.createInsecure()); client.SayHello({ name: 'Dev' }, (err, res) => { console.log(res.message); }); 📨 Message Queue – RabbitMQ with Node.js 🛠 Producer (Sender) npm install amqplib // producer.js const amqp = require('amqplib'); async function send() { const conn = await amqp.connect('amqp://localhost'); const channel = await conn.createChannel(); const queue = 'jobs'; await channel.assertQueue(queue); channel.sendToQueue(queue, Buffer.from('Send Welcome Email')); console.log('Message sent!'); setTimeout(() => conn.close(), 500); } send(); 🛠 Consumer (Worker) // consumer.js const amqp = require('amqplib'); async function consume() { const conn = await amqp.connect('amqp://localhost'); const channel = await conn.createChannel(); const queue = 'jobs'; await channel.assertQueue(queue); channel.consume(queue, msg => { console.log('Received:', msg.content.toString()); channel.ack(msg); }); } consume(); 🔁 Streaming API – Kafka-Style (Simulated) Kafka is too heavy to set up here, so we’ll simulate a stream using a basic EventEmitter to represent continuous data streaming. // streaming-server.js const express = require('express'); const EventEmitter = require('events'); const app = express(); const stream = new EventEmitter(); app.get('/stream', (req, res) => { res.setHeader('Content-Type', 'text/event-stream'); const send = data => res.write(`data: ${JSON.stringify(data)}\n\n`); stream.on('data', send); req.on('close', () => stream.off('data', send)); }); setInterval(() => { stream.emit('data', { price: Math.random() * 100 }); }, 1000); app.listen(8003, () => console.log('Streaming API on http://localhost:8003/stream')); 🔐 OAuth2 + JWT Authentication 🛠 Backend: JWT Auth with Express npm install express jsonwebtoken bcryptjs // auth-server.js const express = require('express'); const jwt = require('jsonwebtoken'); const bcrypt = require('bcryptjs'); const app = express(); app.use(express.json()); const users = [{ username: 'admin', password: bcrypt.hashSync('1234', 8) }]; app.post('/login', (req, res) => { const user = users.find(u => u.username === req.body.username); if (!user || !bcrypt.compareSync(req.body.password, user.password)) { return res.sendStatus(401); } const token = jwt.sign({ username: user.username }, 'secret-key', { expiresIn: '1h' }); res.json({ token }); }); app.get('/protected', (req, res) => { const token = req.headers.authorization?.split(' ')[1]; try { const decoded = jwt.verify(token, 'secret-key'); res.json({ message: `Hello ${decoded.username}` }); } catch { res.sendStatus(401); } }); app.listen(8004, () => console.log('Auth server on http://localhost:8004')); ✅ we now have working examples code : ⚡ Coming Up: Part 3 — Final Recommendations, Architecture Tips & Cheatsheets Next up, I’ll wrap this series with: 🔧 When to use each API (real-world context) ⚔️ REST vs GraphQL vs gRPC vs Webhooks — when to choose what 📋 Full cheatsheets and decision trees 📦 Extra tools and packages to use per API type

#web-development, #frontend, #ui, #css

CSS Layout, Display & Positioning — Developer Notes with Examples

🧱 CSS Layout, Display & Positioning — Developer Notes with Examples If you're working on any frontend project — whether it's a portfolio, dashboard, or SPA — mastering CSS layout, display, and position is non-negotiable. These core concepts determine how your UI elements appear and behave in relation to one another. In this post, we’ll cover: The different types of display properties CSS positioning with real-world parent-child relationships Combining display and position for advanced layouts A cheat sheet you can bookmark or screenshot 🔖 📌 1. Understanding display: The Foundation of Layout The display property defines how an element behaves in the document flow. Every element is a box, and display tells the browser how to treat that box. 🔹 Common display values: Value Description block Fills the full width. Starts on a new line. inline Fits the content. No line break. inline-block Like inline, but allows width and height. flex Turns container into a flex layout. grid Turns container into a grid layout. none Hides the element completely. 🔧 Code Example: Block vs Inline vs Inline-block <div class="block">Block</div> <span class="inline">Inline</span> <div class="inline-block">Inline-block</div> .block { display: block; background-color: coral; } .inline { display: inline; background-color: lightblue; } .inline-block { display: inline-block; background-color: lightgreen; width: 100px; height: 40px; } 🧩 2. Flexbox Layouts (Parent-Child Example) Flexbox is the most used layout model for responsive design and component alignment. 👨‍👩‍👧‍👦 Parent: display: flex When a parent is a flex container, all direct children become flex items. <div class="parent"> <div class="child">Child 1</div> <div class="child">Child 2</div> </div> .parent { display: flex; gap: 10px; } .child { flex: 1; background: #ddd; padding: 10px; } ✅ flex: 1 makes both children grow equally inside the parent. 🧭 3. position: Controlling Element Placement The position property defines how an element is positioned within the layout, and whether it's relative to the parent, the viewport, or itself. 🔹 Types of Positioning: Value Description static Default layout flow (no positioning) relative Positioned relative to itself absolute Positioned relative to nearest positioned ancestor fixed Stuck to viewport sticky Acts relative until scrolled to threshold 🔧 Code Example: Relative + Absolute (Parent-Child) <div class="relative-parent"> <div class="absolute-child">I'm absolute</div> </div> .relative-parent { position: relative; width: 300px; height: 200px; background: #eee; } .absolute-child { position: absolute; top: 10px; right: 10px; background: tomato; padding: 5px; } ✅ .absolute-child is positioned relative to .relative-parent because it’s the nearest ancestor with a position value other than static. 🧷 4. Sticky vs Fixed 🔧 Code Snippet .fixed-header { position: fixed; top: 0; width: 100%; background: yellow; } .sticky-nav { position: sticky; top: 0; background: pink; } fixed stays stuck to viewport even when scrolled. sticky scrolls with the page until a threshold, then stays fixed. 🧰 5. Real-World Layout Example 🖥️ Two-Column Layout (Sidebar + Content) <div class="layout"> <aside class="sidebar">Sidebar</aside> <main class="main-content">Content</main> </div> .layout { display: flex; height: 100vh; } .sidebar { width: 250px; background: #f4f4f4; } .main-content { flex: 1; background: white; padding: 20px; } ✅ This is a flexible desktop layout — sidebar takes fixed width, content takes remaining space. 🔁 6. Combining display + position (Practical UI Component) <div class="card"> <img src="..." alt="..." /> <span class="badge">New</span> </div> .card { position: relative; display: inline-block; } .badge { position: absolute; top: 10px; right: 10px; background: red; color: white; padding: 4px 8px; border-radius: 6px; } 🎯 Common in UI components — use inline-block to control sizing, relative to anchor badge. 🧾 Cheatsheet — Quick Reference 🧱 Layout Display display Value Use Case block Sections, divs inline Spans, inline text inline-block Small components with box model flex One-dimensional layout grid Two-dimensional layout none Hide element 🧭 Positioning position Type Use For static Default behavior relative Local positioning absolute Overlay inside a parent fixed Sticky headers, buttons sticky Navigation, scroll indicators 👨‍👧 Parent-Child Effects Parent Style Child Behavior display: flex Children become flex items display: grid Children become grid cells position: relative Children with absolute use it as anchor ✅ Conclusion Mastering display and position is essential for laying out responsive, modern UIs. Whether you're building simple blogs or complex dashboards, these core tools let you place elements exactly where you need them.

#Blogs

🔥 All The APIs You Should Know as a Developer (Part 1: Theory, Use Cases & Why They Exist)

Hey there 👋 Whether you're a backend engineer, full-stack dev, or someone diving into API architecture, you've probably realized… REST and GraphQL are just the tip of the iceberg. There’s a whole world of APIs — each designed to solve a very specific problem — and knowing when and why to use them can seriously level up your backend game. This post kicks off a 3-part guide where I’ll break down: 🧠 What each type of API does 🎯 Why it exists and what problem it solves ⚔️ Where it's useful (and where it’s not) 🧩 Alternatives, pros, and cons Let’s dive in. ☕️ 🧱 1. REST API – The OG 🧠 What is it? REST (Representational State Transfer) is the “standard” HTTP API. You hit URLs like /users/123 using verbs like GET, POST, PUT, DELETE. 🎯 Why it came in: SOAP was too complex. REST simplified data exchange by using simple HTTP verbs and stateless interactions. 🛠️ Common Use Cases: CRUD APIs (users, products, orders) Mobile app backends Public developer APIs (e.g., GitHub, Stripe) ✅ Pros: Easy to use Cacheable Works anywhere ❌ Gotchas: Over-fetching or under-fetching data Multiple requests for nested data 🔮 2. GraphQL – Query What You Want 🧠 What is it? A query language for APIs. Instead of multiple endpoints, you hit a single /graphql endpoint and ask for exactly what you need. 🎯 Why it came in: Frontend devs were tired of REST giving them either too much or too little data. GraphQL fixed that. 🛠️ Use Cases: Modern SPAs (React/Angular) Mobile apps with weak connections APIs with complex data structures ✅ Pros: One request, custom data Strong typing Awesome dev tooling ❌ Gotchas: Caching is tricky Can be overkill for simple apps 🔌 3. WebSockets – For Real-Time Vibes 🧠 What is it? A persistent, bi-directional connection between client and server. Think chat, live games, or real-time dashboards. 🎯 Why it came in: Polling the server every 2 seconds is just sad 😢. WebSockets let both sides talk freely. 🛠️ Use Cases: Live chat Multiplayer games Real-time notifications ✅ Pros: Low latency Push and pull data anytime ❌ Gotchas: Harder to scale Can break over flaky networks 📬 4. Webhooks – "Ping Me When Stuff Happens" 🧠 What is it? A simple way to get notified when an event occurs — like Stripe telling you a payment succeeded. 🎯 Why it came in: Nobody wants to poll an API constantly just to know if something happened. Let the server notify you. 🛠️ Use Cases: Stripe payment events GitHub repo pushes Slack bot commands ✅ Pros: Easy to implement Decouples systems ❌ Gotchas: You need retry logic Signature verification is important 🚀 5. gRPC – Blazing Fast for Backend-to-Backend 🧠 What is it? A high-performance RPC (Remote Procedure Call) framework using Protocol Buffers and HTTP/2. 🎯 Why it came in: REST was too chatty and slow for microservices in big systems. gRPC is faster, typed, and more efficient. 🛠️ Use Cases: Internal microservice communication Backend-to-backend APIs Real-time systems ✅ Pros: Super fast Strong typing Codegen in many languages ❌ Gotchas: Browser support is meh (needs proxy) Debugging binary payloads is rough 🎥 6. WebRTC – For Video & P2P Goodness 🧠 What is it? Peer-to-peer communication directly between browsers. WebRTC lets you build video chat, file sharing, and low-latency streaming apps. 🎯 Why it came in: To skip servers for real-time audio, video, and data — and reduce latency big time. 🛠️ Use Cases: Video calling P2P file transfers Interactive media apps ✅ Pros: Peer-to-peer = low latency Secure by default No middleman servers ❌ Gotchas: Signaling is required (e.g., via WebSocket) STUN/TURN servers can get complex 📡 7. SSE (Server-Sent Events) – Push-Only Simplicity 🧠 What is it? A simple way for servers to push real-time updates to the browser over HTTP. 🎯 Why it came in: WebSockets were overkill for simple "push-only" updates. 🛠️ Use Cases: Live notifications Dashboards Monitoring systems ✅ Pros: Super easy Auto-reconnect Works over HTTP/1.1 ❌ Gotchas: Only one-way (server → client) Browser support isn’t 100% 📨 8. Message Queues – Async Everything 🧠 What is it? MQs like RabbitMQ, Kafka, or SQS handle async comms between services. 🎯 Why it came in: Tight coupling between services = bad. MQs let them talk without waiting. 🛠️ Use Cases: Background jobs (emails, payments) Event-driven systems Decoupled microservices ✅ Pros: Decouples systems Supports retries, durability ❌ Gotchas: More infra to manage Debugging async failures can be tricky 💧 BONUS: SOAP – The XML Dinosaur 🧠 What is it? SOAP (Simple Object Access Protocol) is an old-school protocol that uses XML for messaging and runs over HTTP, SMTP, or other protocols. 🎯 Why it came in: Back in the early 2000s, enterprises needed a standardized, secure, and strict way to communicate between systems — especially in banking, healthcare, and other regulated industries. SOAP provided: Strongly-typed interfaces (WSDL) Built-in support for security (WS-Security) Message validation Complex data types 🛠️ Use Cases: Enterprise systems (ERP, banking, healthcare) B2B APIs that need strict contracts Legacy systems still running SOAP services ✅ Pros: Very strict (good for contracts) Security baked in Extensible headers and envelopes ❌ Gotchas: Heavy XML payloads Verbose and slow Harder to work with in modern apps 👀 Real Talk: Most modern APIs don't use SOAP unless they're dealing with legacy enterprise systems. You’ll mostly encounter SOAP when: Integrating with old banking software Using legacy .NET or Java enterprise services Building government or healthcare systems REST vs SOAP at a Glance Feature REST SOAP Format JSON, XML XML only Transport HTTP HTTP, SMTP, more Flexibility Loose Very strict Speed Fast Slower (XML bloat) Used Today? Widely Rare (only legacy/enterprise) Spec Defined? Informal WSDL + XSD formal spec 🧩 Quick Recap API Type Real-Time Two-Way Best For REST ❌ ❌ Classic CRUD APIs GraphQL ❌ ❌ Frontend-flexible queries WebSockets ✅ ✅ Real-time chat/games Webhooks ✅ ❌ Event push (payments, etc.) gRPC ❌ ❌ Internal microservices WebRTC ✅ ✅ Video, audio, P2P data SSE ✅ ❌ Notifications & dashboards MQ / PubSub ❌ ❌ Async event processing 👀 Coming Up Next: Code Everything That’s it for the theory 🍿 In Part 2, we’ll jump into real working examples: Node.js for building APIs React or Angular clients WebSockets, GraphQL, Webhooks, and more

#laravel, #node.js, #angular, #react.js, #fullstack

Complete Guide to CORS & Axios: From Theory to Practical Implementation in Node.js, Laravel, React, and Angular

Complete Guide to CORS & Axios: From Theory to Practical Implementation in Node.js, Laravel, React, and Angular Table of Contents Introduction Understanding CORS: What, Why, and How Same-Origin Policy (SOP) Cross-Origin Resource Sharing (CORS) How Browsers Enforce CORS Types of CORS Requests Simple Requests Preflighted Requests Important CORS Headers Explained Handling Credentials in CORS How to Enable and Configure CORS on Backend Node.js with Express PHP Laravel Axios: A Powerful HTTP Client Axios vs Fetch Installing Axios Using Axios in Frontend Frameworks React Example Angular Example Advanced Axios Usage Global Configuration Interceptors Error Handling Integrating Axios with CORS Common CORS and Axios Issues & How to Debug Best Practices & Tips CORS & Axios Cheatsheet Summary Introduction In modern web development, building applications with a separation between frontend and backend is commonplace. Frontend apps often need to interact with backend APIs hosted on different domains, ports, or protocols — triggering browser Cross-Origin Resource Sharing (CORS) policies. Additionally, making HTTP requests in frontend apps is crucial — and Axios is one of the most popular libraries that simplifies these requests. This guide aims to cover everything you need to understand and implement CORS handling and use Axios effectively in your projects, with practical examples in Node.js, Laravel, React, and Angular. Understanding CORS: What, Why, and How Same-Origin Policy (SOP) Browsers enforce Same-Origin Policy to restrict how scripts loaded from one origin can interact with resources from another origin. An "origin" is defined as the combination of protocol + domain + port. Example: http://example.com:3000 ≠ http://example.com:4000 (different port → different origin) http://example.com ≠ https://example.com (different protocol → different origin) Cross-Origin Resource Sharing (CORS) CORS is a mechanism that allows servers to specify which origins are permitted to access their resources. It relaxes the SOP by explicitly whitelisting origins and HTTP methods via HTTP headers. How Browsers Enforce CORS Browser sends an HTTP request with an Origin header indicating the source of the request. Server responds with specific CORS headers to allow or deny the request. Browser examines these headers: If headers permit, the browser allows the frontend script to read the response. Otherwise, the response is blocked by the browser. Types of CORS Requests Simple Requests Use safe HTTP methods: GET, POST, HEAD Only allow a limited set of headers (e.g., Accept, Content-Type with certain media types) Sent directly without preflight. Preflighted Requests Include requests with: Methods other than GET, POST, HEAD (e.g., PUT, DELETE) Custom headers (like Authorization) Content-Type other than simple types (like application/json) Browser sends an OPTIONS request before the actual request to verify permission. Server responds with allowed methods and headers. If allowed, browser proceeds with actual request. Important CORS Headers Explained Header Description Access-Control-Allow-Origin Specifies the allowed origin(s). Can be a specific origin or * for all origins. Access-Control-Allow-Methods Lists allowed HTTP methods (used in preflight response). Access-Control-Allow-Headers Lists allowed headers client can send (preflight). Access-Control-Allow-Credentials Whether cookies or auth data can be sent (true or omitted). Access-Control-Expose-Headers Headers accessible to frontend JS (by default, only simple headers accessible). Access-Control-Max-Age Caches preflight results duration in seconds. Handling Credentials in CORS Cookies, HTTP Auth, client-side SSL certificates are not sent by default on cross-origin requests. To enable: Client: Set withCredentials: true (Axios/fetch) Server: Set header Access-Control-Allow-Credentials: true Important: Cannot use * wildcard for Access-Control-Allow-Origin when Allow-Credentials is true. Must specify explicit origin. How to Enable and Configure CORS on Backend Node.js with Express import express from 'express'; import cors from 'cors'; const app = express(); app.use(cors({ origin: 'http://localhost:3000', methods: ['GET', 'POST', 'PUT', 'DELETE'], allowedHeaders: ['Content-Type', 'Authorization'], credentials: true })); app.get('/api/data', (req, res) => { res.json({ message: 'CORS enabled!' }); }); app.listen(5000, () => console.log('Server running on port 5000')); Handling Preflight: app.options('*', cors()); // Enables CORS preflight for all routes PHP Laravel Laravel 8+ ships with CORS middleware pre-installed (HandleCors). Configure config/cors.php: return [ 'paths' => ['api/*', 'sanctum/csrf-cookie'], 'allowed_methods' => ['*'], 'allowed_origins' => ['http://localhost:3000'], 'allowed_headers' => ['Content-Type', 'X-Requested-With', 'Authorization'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => true, ]; Ensure middleware is enabled in app/Http/Kernel.php under $middlewareGroups. Axios: A Powerful HTTP Client Axios vs Fetch Feature Axios Fetch Syntax Simple and concise More verbose JSON parsing Automatic Manual with .json() Request & response interceptors Supported Not supported natively Request cancellation Supported Supported via AbortController Error handling Throws for HTTP errors Doesn't throw for HTTP errors Progress tracking Supported Not directly supported Works in Node.js Yes No Installing Axios npm install axios Using Axios in Frontend Frameworks React Example import axios from 'axios'; import { useEffect, useState } from 'react'; function App() { const [data, setData] = useState(null); useEffect(() => { axios.get('http://localhost:5000/api/data', { withCredentials: true }) .then(res => setData(res.data)) .catch(err => console.error('API error:', err)); }, []); return ( <div> <h1>API Response:</h1> <pre>{JSON.stringify(data, null, 2)}</pre> </div> ); } Angular Example // data.service.ts import { Injectable } from '@angular/core'; import axios from 'axios'; @Injectable({ providedIn: 'root', }) export class DataService { baseUrl = 'http://localhost:5000/api'; async getData() { try { const response = await axios.get(`${this.baseUrl}/data`, { withCredentials: true }); return response.data; } catch (error) { console.error('API error:', error); throw error; } } } // home.component.ts import { Component, OnInit } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-home', template: `<pre>{{ data | json }}</pre>`, }) export class HomeComponent implements OnInit { data: any; constructor(private dataService: DataService) {} async ngOnInit() { this.data = await this.dataService.getData(); } } Advanced Axios Usage Global Configuration Set common defaults for all Axios requests: axios.defaults.baseURL = 'http://localhost:5000/api'; axios.defaults.withCredentials = true; axios.defaults.headers.common['Authorization'] = 'Bearer your_token'; Interceptors Intercept requests or responses to modify or handle globally: // Add token before requests axios.interceptors.request.use(config => { const token = localStorage.getItem('token'); if (token) config.headers['Authorization'] = `Bearer ${token}`; return config; }); // Handle errors globally axios.interceptors.response.use( response => response, error => { if (error.response.status === 401) { // Handle unauthorized errors } return Promise.reject(error); } ); Error Handling Axios throws on HTTP errors (status outside 2xx). Use .catch() or try/catch with async/await. Integrating Axios with CORS To send cookies or HTTP auth credentials on cross-origin requests: axios.get('http://localhost:5000/api/secure-data', { withCredentials: true }); Backend must have: Access-Control-Allow-Origin with explicit origin (not *) Access-Control-Allow-Credentials: true Common CORS and Axios Issues & How to Debug Issue Cause Fix CORS error in browser console Missing or incorrect CORS headers on backend Add correct CORS headers and handle preflight OPTIONS Access-Control-Allow-Origin is * but credentials fail Credentials not allowed with wildcard origin Specify exact origin, enable credentials on backend Preflight request fails Backend doesn’t handle OPTIONS request Add handler for OPTIONS preflight (Express app.options) Cookies not sent in request Missing withCredentials: true on client Add withCredentials: true in Axios/fetch Authorization headers missing Backend not allowing Authorization header Add Authorization to Access-Control-Allow-Headers Best Practices & Tips Use specific origins, avoid * when cookies or auth are involved Centralize Axios config for maintainability Use interceptors for auth tokens or error handling Always test with browser DevTools (Network tab) for CORS headers and errors Use Postman or curl to test backend APIs — they bypass CORS restrictions Cache preflight responses via Access-Control-Max-Age for performance CORS & Axios Cheatsheet Task Backend (Node.js) Backend (Laravel) Frontend (Axios) Enable CORS app.use(cors({ origin: 'http://localhost:3000', credentials: true })) Set allowed_origins and supports_credentials in config/cors.php Use { withCredentials: true } in Axios requests Handle Preflight OPTIONS app.options('*', cors()) Middleware auto-handles OPTIONS No special config needed Allow credentials credentials: true and specific origin supports_credentials => true and specific origin withCredentials: true Set allowed headers allowedHeaders: ['Content-Type', 'Authorization'] allowed_headers config Set custom headers in Axios with headers option Global Axios config N/A N/A axios.defaults.baseURL and axios.defaults.withCredentials Add Auth token automatically N/A N/A Use axios.interceptors.request Summary CORS is crucial for cross-origin security and enabling frontend-backend communication. Backend must send appropriate CORS headers, especially when handling credentials. Axios simplifies HTTP requests with powerful features like interceptors and automatic JSON handling. Always match frontend and backend origins exactly for CORS to work properly. Use withCredentials: true when cookies or authentication are involved. Debug CORS issues with browser DevTools and backend logs. Organize your code with global Axios configurations and interceptors for cleaner and scalable apps.

#node.js, #API Design, #Backend Engineering, #Web Development, #react.js

🚀 All the API Types You Should Know (With Code Examples)

A beginner friendly guide to REST, GraphQL, WebSocket, Webhooks, gRPC, SOAP, SSE, WebRTC, and more — with real Node.js + React code. ✨ Why This Guide? If you're a developer building modern applications — especially full-stack — knowing which API pattern to use (and when) can make your architecture scalable, maintainable, and future-proof. This guide breaks it down in 3 parts: 🔍 Theoretical overview – What each API is, why it exists, pros/cons, use cases 💻 Real-world code examples – With Node.js + React/Angular ✅ Recommendations & cheatsheets – So you can choose confidently in your projects 🔍 Part 1: API Types Explained In this section, we cover all the major APIs you’ll encounter. ✅ REST (Representational State Transfer) What it solves: CRUD operations over HTTP Use when: You want a simple, standard API Pros: Easy to test, widely supported Cons: Over-fetching, multiple round-trips ✅ Alternative: GraphQL 🔮 GraphQL What it solves: Over/under-fetching data from REST Use when: You want flexibility and fewer network calls Pros: Precise queries, single endpoint Cons: Complex caching, learning curve ✅ Alternative: REST (simpler), tRPC ⚡ WebSocket What it solves: Real-time bidirectional communication Use when: You need live updates (chat, games) Pros: Fast, persistent connection Cons: Stateful, tricky at scale ✅ Alternative: SSE for one-way streams 📬 Webhooks What it solves: Event-driven push from external services Use when: Listening to 3rd-party triggers (like Stripe) Pros: Lightweight, asynchronous Cons: Delivery isn't guaranteed ✅ Alternative: Polling (less efficient) 🛰️ SSE (Server-Sent Events) What it solves: One-way streaming from server to client Use when: Live dashboards, notifications Pros: Built into browser, simple Cons: One-way only, no mobile support ✅ Alternative: WebSocket (bi-directional) 💧 SOAP (Simple Object Access Protocol) What it solves: Contract-first APIs in XML Use when: Enterprise or legacy systems Pros: Strict schema, secure, standards-based Cons: Verbose XML, hard to integrate ✅ Alternative: REST or gRPC 🎥 WebRTC What it solves: Peer-to-peer video/audio/file sharing Use when: You need direct communication (video chat) Pros: Fast, low-latency Cons: Requires signaling, infra-heavy ✅ Alternative: WebSocket + media servers 🧵 gRPC (Google RPC) What it solves: Efficient internal service communication Use when: Microservices or backend-to-backend Pros: Type-safe, fast, binary Cons: Browser-unfriendly, needs .proto files ✅ Alternative: REST for simplicity 📨 Message Queues (RabbitMQ, Kafka) What it solves: Async communication & background jobs Use when: Decoupling, retries, task processing Pros: Scalable, reliable Cons: Adds infra complexity ✅ Alternative: In-memory queues (for simple apps) 💻 Part 2: Code Examples (Node.js + React) Each API above is demonstrated in this section using Node.js + React. ▶️ Jump to Part 2 – Code Examples You'll see: REST (Express) GraphQL (Apollo) WebSocket (ws) Webhooks (Express) SSE WebRTC (Vanilla) gRPC (with proto) RabbitMQ (with amqplib) SOAP (with WSDL) JWT Auth API (OAuth2-style) All examples are copy-paste ready. 🧠 Part 3: Final Recommendations & Cheatsheet ▶️ Jump to Part 3 – API Decision Cheatsheets Includes: ✅ Use case-based API suggestions 🛠️ Suggested libraries for Node.js and frontend 📋 REST vs GraphQL vs gRPC comparison 💬 Real-world architecture tips 💬 Final Thoughts Most projects will benefit from combining multiple API styles: Example: Use REST for core CRUD, WebSockets for notifications, and a queue for background tasks. Don’t be afraid to mix and match — each API solves different problems. 📦 Want the Full Codebase? All code examples are available in a GitHub repo (or drop me a message, and I’ll send it over). Or you can copy the examples directly from this blog. ❤️ Like This Guide? If this helped you: ⭐ Star the GitHub repo (if linked) 📰 Subscribe to the blog 💬 Comment with your favorite API combo

English

Sakib SiddiQuie is a Tech enthusiast.
Featured Analysis
cat

Title

Welcome to this page, read my blogs if you find something interesting, Get in touch and subscribe to the newsletter.

2024-03-12T04:00:00+0000Author

Video Title

Main Category

Article Description

Sakib SiddiQuie is a Tech enthusiast.

Head

Title and yes title

Title and yes title

this is the description...

Title and yes title

Title and yes title

this is the description...

Title and yes title

Title and yes title

this is the description...

Title and yes title

Title and yes title

this is the description...

Title and yes title

Title and yes title

this is the description...

Head Text and Welcome to this page, read my blogs if you find something interesting, Get in touch and subscribe to the newsletter.

Title and yes title

this is the description...

Title and yes title

this is the description...

Title and yes title

this is the description...

Title and yes title

this is the description...

Title and yes title

this is the description...

No image
Featured Analysis
learning

Head Text and

Sub Head and Welcome to this page, read my blogs if you find something interesting, Get in touch and subscribe to the newsletter. Welcome to this page, read my blogs if you find something interesting, Get in touch and subscribe to the newsletter. Welcome to this page, read my blogs if you find something interesting, Get in touch and subscribe to the newsletter. Welcome to this page, read my blogs if you find something interesting, Get in touch and subscribe to the newsletter. Welcome to this page, read my blogs if you find something interesting, Get in touch and subscribe to the newsletter. Welcome to this page, read my blogs if you find something interesting, Get in touch and subscribe to the newsletter.

2023-06-02T04:25:00+0000Sakib Uddin SiddiQuie