<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Shanto's Notes]]></title><description><![CDATA[Shanto's Notes]]></description><link>https://notes.shanto.dev</link><generator>RSS for Node</generator><lastBuildDate>Sun, 18 Oct 2026 02:36:53 GMT</lastBuildDate><atom:link href="https://notes.shanto.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Ecobazar 



Building My First Full-Stack E-Commerce Store (Next.js 16, MongoDB, NextAuth v5)]]></title><description><![CDATA[A step-by-step teardown of a real Bangladeshi organic-grocery store I built from scratch.#Live Demo#Repo Link
This is my first full-stack project and I wanted to write down every single thing I built ]]></description><link>https://notes.shanto.dev/ecobazar</link><guid isPermaLink="true">https://notes.shanto.dev/ecobazar</guid><category><![CDATA[eco bazar]]></category><category><![CDATA[e-commerce website development]]></category><category><![CDATA[ecommerce]]></category><category><![CDATA[e-commerce]]></category><category><![CDATA[full stack]]></category><dc:creator><![CDATA[Jahid Hasan Shanto]]></dc:creator><pubDate>Fri, 21 Aug 2026 06:28:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/65b807b730a5fd59cad56cfc/d802deb9-92ec-4650-9d47-0d8d35a9d3ef.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>A step-by-step teardown of a real Bangladeshi organic-grocery store I built from scratch.<br />#<a href="https://eco.shanto.dev">Live Demo</a><br />#<a href="https://github.com/Shanto-prime/eco-bazar-e-commerce">Repo Link</a></p>
<p>This is my <strong>first full-stack project</strong> and I wanted to write down every single thing I built and learned the tech stack, every feature, every design decision, and the parts that broke and how I fixed them. If you're a beginner learning full-stack, I hope this saves you a few weeks. If you're a hiring manager reading this, everything below is real, deployed, and answering HTTP 200 as I type this.</p>
</blockquote>
<hr />
<h2>What is Ecobazar?</h2>
<p>Ecobazar is a <strong>full-stack e-commerce store for Bangladeshi organic groceries</strong>. It has two faces running on the <strong>same domain</strong>:</p>
<ul>
<li><p><strong>Storefront</strong> the public shop. Browse categories, search, filter by price + star rating, view product details with an image gallery, add to cart, checkout as a guest or signed-in user, track your order, request a return within 15 days of delivery, write a review after your order arrives.</p>
</li>
<li><p><strong>Dashboard</strong> (<code>/dashboard</code>) a <strong>role-based admin area</strong>. Depending on whether you're a <strong>CUSTOMER</strong>, <strong>MODERATOR</strong>, or <strong>ADMIN</strong>, you see a different dashboard with different powers. Admins can create/edit/delete products, manage users, promote or demote roles, upload promo banners, set up time-limited Hot Deals offers, approve profile-change requests, and read the audit log.</p>
</li>
</ul>
<p>The store is Bangladesh-oriented prices in Taka (৳), districts and thanas in the checkout form (no US zip codes), Bangla product names alongside English (Deshi Aloo, Kacha Morich, Ilish Mach, Sundarban Honey…).</p>
<p><strong>Everything is real code, running now.</strong> No mock APIs, no lorem-ipsum products. 59 products in the catalogue, 12 categories, image gallery on the biggest product, full order lifecycle from cart → checkout → PAID → SHIPPED → DELIVERED → optional 15-day return with restock.</p>
<hr />
<h2>The numbers, at a glance</h2>
<p>Real counts, straight from <code>grep</code>:</p>
<table>
<thead>
<tr>
<th>What</th>
<th>Count</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Source files</strong> (<code>.js</code> + <code>.jsx</code>) under <code>app/</code>, <code>components/</code>, <code>lib/</code></td>
<td><strong>137</strong></td>
</tr>
<tr>
<td><strong>Total lines of code</strong> (source only)</td>
<td><strong>16,055</strong></td>
</tr>
<tr>
<td><strong>Route pages</strong> (<code>page.js</code> / <code>page.jsx</code>)</td>
<td><strong>26</strong></td>
</tr>
<tr>
<td><strong>Prisma models</strong> (in <code>schema.prisma</code>)</td>
<td><strong>19</strong></td>
</tr>
<tr>
<td><strong>Server actions files</strong> (<code>"use server"</code>)</td>
<td><strong>12</strong></td>
</tr>
<tr>
<td><strong>Zod schemas</strong> (files importing zod)</td>
<td><strong>14</strong></td>
</tr>
<tr>
<td><strong>Products in the seeded catalogue</strong></td>
<td><strong>59</strong></td>
</tr>
<tr>
<td><strong>E2E test spec files</strong> (Playwright)</td>
<td><strong>18</strong></td>
</tr>
<tr>
<td><code>useState</code> <strong>calls</strong></td>
<td><strong>149</strong></td>
</tr>
<tr>
<td><code>useEffect</code> <strong>calls</strong></td>
<td><strong>30</strong></td>
</tr>
<tr>
<td><code>useTransition</code> <strong>calls</strong></td>
<td><strong>36</strong></td>
</tr>
<tr>
<td><code>useRouter</code> <strong>calls</strong></td>
<td><strong>31</strong></td>
</tr>
<tr>
<td><code>useRef</code> <strong>calls</strong></td>
<td><strong>23</strong></td>
</tr>
<tr>
<td><code>useCallback</code> <strong>calls</strong></td>
<td><strong>15</strong></td>
</tr>
<tr>
<td><code>useContext</code> <strong>calls</strong></td>
<td><strong>8</strong></td>
</tr>
<tr>
<td><code>useMemo</code> <strong>calls</strong></td>
<td><strong>7</strong></td>
</tr>
<tr>
<td><code>useSearchParams</code> <strong>calls</strong></td>
<td><strong>6</strong></td>
</tr>
<tr>
<td><code>usePathname</code> <strong>calls</strong></td>
<td><strong>4</strong></td>
</tr>
<tr>
<td><code>useReducer</code> <strong>calls</strong></td>
<td><strong>2</strong></td>
</tr>
</tbody></table>
<p>Plus <strong>two custom hooks</strong>: <code>useT()</code> for i18n (85 uses across the app) and <code>useCart()</code> for the cart context (22 uses). More on these below.</p>
<hr />
<h2>Full tech stack</h2>
<p>Every piece of this stack was a deliberate choice with a reason. Nothing is here "because tutorials use it".</p>
<h3>Frontend</h3>
<ul>
<li><p><strong>Next.js 16 (App Router)</strong> file-based routing, server components by default. Server-first rendering means most of the app doesn't ship JavaScript for its rendered HTML, only for the interactive bits. Turbopack is the bundler (default in 16).</p>
</li>
<li><p><strong>React 19</strong> server components + client components + server actions.</p>
</li>
<li><p><strong>Tailwind CSS v4</strong> utility-first CSS. v4 keeps its config <em>in CSS</em> (<code>app/globals.css</code>), not in a <code>tailwind.config.js</code>.</p>
</li>
<li><p><strong>JavaScript</strong> this project is <strong>plain JS, not TypeScript</strong>. First full-stack project meant one less thing to fight with. I might migrate to TS later.</p>
</li>
</ul>
<h3>Backend</h3>
<ul>
<li><p><strong>Prisma 5.22</strong> ORM for the database. Type-safe queries, migrations (well, <code>db push</code> for Mongo since it has no migrations), model definitions in <code>prisma/schema.prisma</code>.</p>
</li>
<li><p><strong>MongoDB 8.0</strong> as a <strong>single-node replica set</strong> MongoDB itself, but running in replica-set mode. Why? Prisma's MongoDB connector needs a replica set to run <code>$transaction</code>, and my checkout logic <em>needs</em> transactions to prevent overselling. More on that later.</p>
</li>
<li><p><strong>NextAuth v5 (Auth.js)</strong> authentication. Credentials (username/email + password), plus optional Google/Facebook OAuth that auto-mounts only when the env vars are set.</p>
</li>
<li><p><strong>Zod 3.23</strong> runtime input validation. Every server action and API route parses inputs through a Zod schema before hitting the database.</p>
</li>
<li><p><strong>bcryptjs</strong> password hashing (pure-JS bcrypt so it works everywhere).</p>
</li>
</ul>
<h3>Deployment / DevOps</h3>
<ul>
<li><p><strong>Ubuntu 24.04 VPS</strong> (OpenVZ container, 1 GB RAM, 1 CPU, 9.8 GB disk) at <code>eco.shanto.dev</code>.</p>
</li>
<li><p><strong>nginx 1.24</strong> as reverse proxy on ports 80 + 443, with a friendly maintenance page for when the app is down.</p>
</li>
<li><p><strong>PM2 7.0</strong> as the Node process manager, with <code>--max-memory-restart 500M</code> so a runaway worker triggers a controlled restart before it OOM-kills the whole box.</p>
</li>
<li><p><strong>Let's Encrypt</strong> via certbot, auto-renewed by a systemd timer.</p>
</li>
<li><p><strong>ufw</strong> firewall 22, 80, 443 in, everything else deny.</p>
</li>
<li><p><strong>GitHub Actions</strong> for CI/CD every <code>git push</code> to <code>main</code> triggers a build on GitHub's runners (7 GB RAM, no OOM risk), which then rsyncs the artifacts to the VPS.</p>
</li>
</ul>
<h3>Testing</h3>
<ul>
<li><strong>Playwright</strong> for end-to-end tests. 18 spec files, 70+ test cases.</li>
</ul>
<h3>Tools during dev</h3>
<ul>
<li><p><strong>ESLint</strong> (flat config, <code>eslint-config-next</code>) for linting.</p>
</li>
<li><p><strong>sharp</strong> (bundled with Next.js) for image processing I wrote a script that resized all 61 product photos from 156 MB down to 3.4 MB in place.</p>
</li>
</ul>
<hr />
<h2>Feature list everything I built</h2>
<h3>Storefront (customer-facing)</h3>
<ol>
<li><p><strong>Home page</strong> hero grid with a main promo image + a live TOP-placement admin banner (falls back to a static image if no banner is set) + a Hot Deals link card, service bar (free shipping / support / secure payment / money-back), category tiles, "Popular Products" best-sellers row, Hot Deals area with a big featured card + smaller card grid, a BELOW_LIST admin banner slot, "Featured Products" row, and a "Customer Reviews" carousel with 6 seeded reviews (4× 5-star, 2× 4-star I purposely didn't make them all 5 stars because all-5 looks fake).</p>
</li>
<li><p><strong>Nav bar</strong> Home · Shop · Pages · Track Order · About · Contact. "Track Order" wires to <code>/orders/lookup</code>, my guest tracker.</p>
</li>
<li><p><strong>Shop page</strong> server-side paginated grid (9 products per page). Live search by name. Category filter in the sidebar. <strong>Price range slider</strong> whose min/max are pulled from the actual cheapest and most-expensive product in the DB (not a hardcoded 0-100). Star rating filter (radios at 5★/4★/3★/2★/1★). Sort by latest / price / name. All filters are URL-shareable via query strings.</p>
</li>
<li><p><strong>Product detail page</strong> image gallery with zoom (supports multi-image galleries drop <code>&lt;slug&gt;-2.jpeg</code> next to <code>&lt;slug&gt;.jpeg</code> and the seed picks it up). Quantity stepper. Add to cart. Wishlist toggle (signed-in only). Description / Additional info / Reviews tabs. Related products. Soft-404 with "did you mean…?" suggestions from <code>lib/product-suggest.js</code>.</p>
</li>
<li><p><strong>Cart</strong> quantity steppers, coupon apply (three coupons: ECO10, ECO20, FREE5), live totals. Cart persists to <code>localStorage</code> for guests; mirrored to the DB for signed-in users so it follows them across devices.</p>
</li>
<li><p><strong>Wishlist</strong> <strong>signed-in only</strong>. Middleware redirects anonymous visitors to <code>/login?next=/wishlist</code>.</p>
</li>
<li><p><strong>Checkout</strong> Bangladeshi Division/District/Thana selects (not US zip codes), address prefill for signed-in users with saved addresses, <strong>guest checkout allowed</strong> (captures email/name/phone/address, <code>userId</code> is null on the order). Five payment methods (COD, PayPal, Amazon, bKash, Nagad the schema fields exist; real gateway integration is TODO). Coupon apply. Thank-you screen with the order number.</p>
</li>
<li><p><strong>Deals landing pages</strong> (<code>/deals/&lt;slug&gt;</code>) one per promo banner. Shows only products whose <code>badge</code> or <code>tags</code> array matches the banner's <code>targetTag</code>. Copy-code control at the top.</p>
</li>
<li><p><strong>Order tracker</strong> (<code>/orders/lookup</code>) a guest enters their order number + email, gets the status. Signed-in users are redirected to <code>/dashboard/orders</code> for the full history.</p>
</li>
<li><p><strong>Multi-language plumbing</strong> (currently English-only; Bangla was removed but the plumbing stayed one JSON file to re-add it).</p>
</li>
<li><p><strong>Dark mode</strong> cookie-based, no flash. The server reads the <code>ecobazar-theme</code> cookie and sets <code>&lt;html class="dark"&gt;</code> before hydration.</p>
</li>
</ol>
<h3>Accounts &amp; auth</h3>
<ol>
<li><p><strong>Credentials sign-up / sign-in</strong> pick a username, use email + password. Log in with <strong>either the username or the email</strong> (my auth handler lowercases the identifier and does <code>findFirst({where: {OR: [{username}, {email}]}})</code>).</p>
</li>
<li><p><strong>Password reset flow</strong> email a one-time token, expires in 1 hour.</p>
</li>
<li><p><strong>Email verification</strong> issued at signup but not enforced at login (design choice; enforcing it before people confirm the mail transport is set up would lock everyone out).</p>
</li>
<li><p><strong>Optional Google + Facebook OAuth</strong> mounts only when the client ID + secret env vars are both non-empty. If not, the buttons don't render and there are no warnings.</p>
</li>
<li><p><strong>First-user-becomes-ADMIN</strong> the very first person to sign up on a fresh install is auto-promoted to admin, marked as super-admin (undeletable/undemotable).</p>
</li>
<li><p><strong>"Already signed in" guardrails</strong> hitting <code>/login</code> or <code>/register</code> while signed in shows a "you're already signed in as X" panel with a "continue to dashboard" link and a "sign out" link. <code>/unauthorized</code> branches too: anonymous visitors see log-in / create-account CTAs; signed-in users with the wrong role see "you don't have access to this page" with a dashboard link. No misleading "please log in" for people who are already logged in.</p>
</li>
<li><p><strong>Guest → user order linking</strong> this is a small but nice one. If a customer checks out as a guest, then later opens an account with the same email, all their prior guest orders are automatically attached to the new account on signup. They see their history in the dashboard on first login. Runs for both credentials and OAuth signups.</p>
</li>
</ol>
<h3>Order lifecycle</h3>
<ol>
<li><p><strong>Server-side cart</strong> Cart model, one row per user, keyed on <code>userId</code>. On login, the local guest cart is <em>merged</em> into the saved cart. On logout, the local cart is cleared. On subsequent reloads, the DB is authoritative (no accidental double-counting).</p>
</li>
<li><p><strong>Guarded atomic stock decrement</strong> the whole reason I need a replica set. More on this in §8.</p>
</li>
<li><p><strong>Order status timeline</strong> every status change (PENDING → PAID → SHIPPED → DELIVERED, or CANCELLED) is recorded as an append-only <code>OrderStatusEvent</code> with a timestamp, actor, and optional note. The customer sees the timeline in the order details modal.</p>
</li>
<li><p><strong>Order details modal</strong> customer and admin both see the item list (product, quantity, unit price, line total) + status timeline + totals block (subtotal, discount, shipping, total). Item names come from the DB but <em>prices are snapshotted</em> a product price change tomorrow doesn't retroactively change what's shown in yesterday's order.</p>
</li>
<li><p><strong>Terminal statuses</strong> DELIVERED and CANCELLED are terminal. Neither admin nor moderator can un-cancel or un-deliver an order. The one allowed exception: a customer's own return.</p>
</li>
<li><p><strong>15-day return window</strong> if a customer's order is DELIVERED and less than 15 days have passed since the DELIVERED event, they see a "Request return" button in the order details. Clicking it (with confirmation) flips the order to CANCELLED, restocks the items back to inventory, writes a timeline event noting "Return requested by customer", appends an audit log row. After 15 days the button disappears; the order stays DELIVERED forever.</p>
</li>
<li><p><strong>Write review after delivery</strong> customer sees a "Write review" CTA per item on a delivered order, which expands into a star rating + text form. Submitting creates an approved <code>Review</code> row (schema-enforced unique per (product, user)) and recomputes <code>Product.rating</code> as the running average. If they already reviewed the product, the CTA is replaced by "You reviewed this".</p>
</li>
</ol>
<h3>Dashboard (role-based)</h3>
<ol>
<li><p><strong>Role routing</strong> <code>/dashboard</code> reads the session role and renders <code>AdminDashboard</code>, <code>ModeratorDashboard</code>, or <code>CustomerDashboard</code>. Same URL, three different pages.</p>
</li>
<li><p><strong>Orders management</strong> everyone sees <code>/dashboard/orders</code> but the data is scoped server-side: customers see only their own; moderators see all (read-only, no status change); admins see all with an inline status dropdown.</p>
</li>
<li><p><strong>Product management</strong> moderator can create products but can only edit/delete products where <code>Product.createdById === user.id</code> (enforced in the server action, not the schema). Admin can edit anything.</p>
</li>
<li><p><strong>Image uploads</strong> three endpoints with different rules: <code>/api/upload</code> for product images (admin/mod, 4 MB), <code>/api/upload/avatar</code> for user avatars (any signed-in, 2 MB), and <code>/api/upload/banner</code> for promo banners (admin only, 6 MB). All validate the file magic bytes (not just MIME type), assign a hashed filename <code>&lt;timestamp&gt;-&lt;sha1&gt;.&lt;ext&gt;</code>, and pick the extension from the <em>validated</em> type so a <code>filename="x.html"</code> with <code>Content-Type: image/png</code> can't sneak into <code>/public</code> and get served as HTML from my origin.</p>
</li>
<li><p><strong>User management</strong> (admin only) promote/demote roles. Super-admin is untouchable.</p>
</li>
<li><p><strong>Promo banners</strong> (admin only) upload banner artwork, set placement (TOP / BELOW_LIST), set a <code>targetTag</code>, get a <code>/deals/&lt;slug&gt;</code> landing page for free.</p>
</li>
<li><p><strong>Hot Deals offers</strong> (admin only) pick a product, set a percentage off (1-90%), set an end time. While the offer is live, the discounted price is applied <em>everywhere</em> shop grid, product page, cart, checkout. The <code>Product.price</code> field is never rewritten, so expiry doesn't need a cleanup job.</p>
</li>
<li><p><strong>Profile change requests</strong> for the two "recovery channel" fields (email + phone), a change goes into an approval queue instead of applying instantly. Admin approves or rejects.</p>
</li>
<li><p><strong>Audit log</strong> (admin only) every privileged write appends a row with actor, action name, entity, entity ID, and JSON metadata.</p>
</li>
<li><p><strong>Settings page</strong> profile (name, username, avatar), password change, saved addresses (with default flag), appearance toggle. Currency section was here I removed it when I decided the store would be Taka-only.</p>
</li>
</ol>
<hr />
<h2>Architecture how the pieces fit together</h2>
<pre><code class="language-plaintext">Browser
   │
   ▼
Next.js server (Node 22, PM2)
   │
   ├─ App Router: server components render HTML on the server
   ├─ Server actions ("use server"): mutate data, called from client without a manual API
   ├─ Middleware (Edge): gates /dashboard/*, /wishlist* auth-check only, no DB access
   │
   ▼
Prisma Client
   │
   ▼
MongoDB (single-node replica set on localhost)
</code></pre>
<p><strong>Three enforcement layers for authorization.</strong> This is the load-bearing pattern:</p>
<ol>
<li><p><strong>Middleware</strong> (<code>middleware.js</code>) runs on the Edge. Checks <em>signed in or not</em>. Anonymous <code>/dashboard</code> visitors bounce to <code>/unauthorized</code>; anonymous <code>/wishlist</code> visitors bounce to <code>/login</code>. Middleware never touches Prisma or bcrypt (they can't run on the Edge runtime), it only reads the JWT.</p>
</li>
<li><p><strong>Server components / pages</strong> call <code>requireAuth()</code> or <code>requireRole()</code> from <code>lib/auth-helpers.js</code> to enforce the actual role per route.</p>
</li>
<li><p><strong>Server actions &amp; API routes</strong> re-check the role <em>again</em>, even though the route is already protected. Defense in depth. Self-service actions read <code>session.user.id</code> from the server session, never from client input.</p>
</li>
</ol>
<p>Why three layers? Because layer #1 can only know "signed in or not" (no DB access on the Edge), layer #2 enforces the specific role per page but doesn't help if someone hits your action from the outside, and layer #3 is your only real backstop against a bug in either of the first two.</p>
<p><strong>File extension convention.</strong> <code>.js</code> = server component or module. <code>.jsx</code> = client component (<code>"use client"</code> at the top). <code>"use client"</code> and <code>"use server"</code> are load-bearing.</p>
<p><strong>Two data sources don't confuse them.</strong></p>
<ul>
<li><p><code>lib/products-db.js</code> Prisma reads for customer pages (<code>listProducts</code>, <code>getProductBySlug</code>, <code>queryProducts</code>, <code>getPriceBounds</code>, etc.). Source of truth for the running app.</p>
</li>
<li><p><code>prisma/seed-data.js</code> the seed catalogue (12 categories + 59 products). Consumed by both <code>prisma/seed.js</code> (dev) and <code>prisma/seed.prod.js</code> (production). Not read at runtime by pages.</p>
</li>
</ul>
<hr />
<h2>React hooks used count + how each one is used</h2>
<p>I use <strong>every core React hook except</strong> <code>useLayoutEffect</code>. Here's what each one is for in this codebase, with a short example.</p>
<h3><code>useState</code> 149 uses</h3>
<p>The workhorse. Anywhere I need local component state. Modals, form fields, dropdown open/close, current tab, current page number, filter values, error/notice messages.</p>
<pre><code class="language-jsx">const [open, setOpen] = useState(false);
const [rating, setRating] = useState(5);
const [error, setError] = useState(null);
</code></pre>
<h3><code>useEffect</code> 30 uses</h3>
<p>Anywhere I need to synchronize with something outside React usually URL query strings, body scroll lock when a modal opens, or a debounced fetch for the shop's live filters.</p>
<pre><code class="language-jsx">// Debounced fetch of the current page from /api/products
useEffect(() =&gt; {
  const id = setTimeout(async () =&gt; {
    const res = await fetch(`/api/products?${params}`);
    setItems((await res.json()).items);
  }, 250);
  return () =&gt; clearTimeout(id);
}, [query, activeCat, maxPrice, minRating, sort, page]);
</code></pre>
<h3><code>useTransition</code> 36 uses</h3>
<p>For calling server actions without blocking the UI. React 19 makes this pretty clean.</p>
<pre><code class="language-jsx">const [pending, startTransition] = useTransition();

startTransition(async () =&gt; {
  const res = await submitReviewAction({ orderId, productId, rating, body });
  if (!res.ok) setError(res.error);
  else router.refresh();
});
</code></pre>
<p>The button's <code>disabled={pending}</code> and any inline spinner reads from <code>pending</code>.</p>
<h3><code>useReducer</code> 2 uses</h3>
<p>Just one important one: the cart. Cart state has many actions (add, remove, updateQty, setCoupon, clear, replace, merge) and living inside a <code>useState</code> object with lots of manual spread updates would be miserable. <code>useReducer</code> gives me one place where every mutation lives:</p>
<pre><code class="language-jsx">function cartReducer(state, action) {
  switch (action.type) {
    case "add":       return { ...state, items: mergeItems(state.items, action.item) };
    case "remove":    return { ...state, items: state.items.filter(i =&gt; i.slug !== action.slug) };
    case "updateQty": return { ...state, items: setQty(state.items, action.slug, action.qty) };
    // …
  }
}
</code></pre>
<h3><code>useRef</code> 23 uses</h3>
<p>For values that need to persist across renders without triggering a re-render. My favourite example is the "out-of-order fetch guard" on the shop page:</p>
<pre><code class="language-jsx">const reqId = useRef(0);
const mine = ++reqId.current;
const res = await fetch(...);
if (mine !== reqId.current) return; // a newer request superseded this one
setItems(await res.json());
</code></pre>
<p>Also used for the "first render seeded by server props, skip client fetch on mount" pattern:</p>
<pre><code class="language-jsx">const first = useRef(true);
useEffect(() =&gt; {
  if (first.current) { first.current = false; return; }
  // now fetch fresh
}, [query, ...]);
</code></pre>
<h3><code>useMemo</code> 7 uses</h3>
<p>Sparingly. Only when a computation is genuinely expensive AND runs on every render. In this codebase, I use it for filtering the current category list, resolving the theme's palette, and deriving product info from the cart items.</p>
<h3><code>useCallback</code> 15 uses</h3>
<p>Same principle as <code>useMemo</code> sparingly. Mostly used when passing callbacks down to memoized child components, or to stabilize a function reference used as a <code>useEffect</code> dependency.</p>
<h3><code>useContext</code> 8 uses (via 4 custom providers)</h3>
<p>Four context providers wrap the app in <code>app/layout.js</code>:</p>
<ul>
<li><p><code>ThemeProvider</code> dark mode.</p>
</li>
<li><p><code>LanguageProvider</code> i18n (currently English-only).</p>
</li>
<li><p><code>CurrencyProvider</code> currency display (currently pinned to BDT, but the plumbing is still there).</p>
</li>
<li><p><code>CartProvider</code> the big one. Cart + wishlist + toast system.</p>
</li>
</ul>
<p>Each has a hook: <code>useTheme()</code>, <code>useT()</code> (i18n used <strong>85 times</strong>), <code>useCart()</code> (<strong>22 uses</strong>).</p>
<pre><code class="language-jsx">const t = useT();
const { addItem, removeItem, items, coupon, toast } = useCart();
</code></pre>
<h3><code>useRouter</code> / <code>usePathname</code> / <code>useSearchParams</code> 31 / 4 / 6 uses</h3>
<p>From <code>next/navigation</code>. <code>useRouter().refresh()</code> re-runs the server component after a server action mutates data. <code>usePathname()</code> for highlighting the active nav item. <code>useSearchParams()</code> for reading URL state that the server also uses.</p>
<hr />
<h2>Authentication &amp; authorization deep dive</h2>
<p>Everything I know about auth I learned building this.</p>
<h3>Sign-in flow (credentials)</h3>
<ol>
<li><p>User types their identifier (<strong>username OR email</strong>) + password on <code>/login</code>.</p>
</li>
<li><p><code>LoginForm</code> calls <code>signIn("credentials", ...)</code>.</p>
</li>
<li><p>NextAuth calls my <code>Credentials.authorize()</code> in <code>lib/auth.js</code>:</p>
<ul>
<li><p>Normalize the identifier (<code>trim().toLowerCase()</code>).</p>
</li>
<li><p><strong>Rate-limit check first</strong>, before bcrypt. Per-account: 10 attempts / 15 min. Per-IP: 30 attempts / 15 min. If tripped, return the same generic failure a wrong password would.</p>
</li>
<li><p><code>prisma.user.findFirst({where: {OR: [{username}, {email}]}})</code>.</p>
</li>
<li><p><code>bcrypt.compare(password, user.passwordHash)</code>.</p>
</li>
<li><p>If ok: return <code>{id, email, name, image, role}</code>.</p>
</li>
</ul>
</li>
<li><p>NextAuth signs a JWT with those claims.</p>
</li>
<li><p>Subsequent requests read the JWT <strong>no DB hit</strong> for role checks on a normal request.</p>
</li>
<li><p>Every 5 minutes (<code>ROLE_TTL_MS</code>) the JWT re-verifies the role against the DB, so a demoted user's privileges expire within 5 min without needing to log them out.</p>
</li>
</ol>
<h3>Sessions (JWT, not DB)</h3>
<p>JWT strategy, not <code>SessionProvider</code>. Session lives in a cookie. Sessions expire on <em>inactivity</em>: 6 hours for customers, 12 hours for admins/moderators (<code>lib/session-policy.js</code>). The JWT carries a rolling <code>lastActivityAt</code>; past the limit, the token's identity is stripped and the middleware treats it as anonymous.</p>
<h3>Password hashing</h3>
<p><strong>bcrypt cost 12</strong> at signup, reset, and seed. There's an inconsistency in the settings password-change flow (cost 10 there) that I need to fix.</p>
<h3>Tokens</h3>
<p>Password reset and email verification tokens are stored in <code>VerificationToken</code> with a composite identifier of <code>&lt;purpose&gt;:&lt;email&gt;</code>. Single-use, expire in 1 hour. Issuing a new one deletes the prior one so a user asking for two reset emails can't use both.</p>
<h3>Authorization helpers</h3>
<p>Every server component and every server action calls one of these from <code>lib/auth-helpers.js</code>:</p>
<pre><code class="language-js">export async function requireAuth(nextPath = "/dashboard") {
  const user = await getCurrentUser();
  if (!user) redirect(`/unauthorized?next=${encodeURIComponent(nextPath)}`);
  return user;
}

export async function requireRole(roleOrRoles, nextPath = "/dashboard") {
  const user = await requireAuth(nextPath);
  const allowed = Array.isArray(roleOrRoles) ? roleOrRoles : [roleOrRoles];
  if (!allowed.includes(user.role)) redirect("/unauthorized");
  return user;
}
</code></pre>
<p>Usage:</p>
<pre><code class="language-js">// In a server action:
const actor = await requireRole(["ADMIN", "MODERATOR"], "/dashboard/orders");

// In a server component:
const user = await requireAuth("/dashboard/settings");
</code></pre>
<hr />
<h2>The checkout critical path (the scary one)</h2>
<p>This is the one you cannot get wrong.</p>
<p><strong>The problem:</strong> two customers hit "Place order" at exactly the same time, both wanting the last unit of Ilish fish. If I use naive read-then-write, both reads say <code>stock=1</code>, both writes decrement to <code>stock=0</code>, both orders succeed, and someone gets an angry email.</p>
<p><strong>The fix:</strong> a <strong>guarded atomic update</strong> inside a <code>prisma.$transaction</code>. This is why the whole app needs a MongoDB replica set Prisma's Mongo connector can only run transactions against replica sets.</p>
<pre><code class="language-js">await prisma.$transaction(async (tx) =&gt; {
  for (const l of lines) {
    const upd = await tx.product.updateMany({
      where: { id: l.productId, stock: { gte: l.qty } },  // ← guard
      data:  { stock: { decrement: l.qty } },
    });
    if (upd.count === 0) {
      throw new Error(`Out of stock: ${l.name}`);  // → transaction rolls back
    }
  }
  // ... create the order + items + PENDING status event
});
</code></pre>
<p>The magic is <code>where: { stock: { gte: qty } }</code>. If two writers race, MongoDB serializes them: whichever gets there first succeeds; the second one sees <code>stock=0</code>, its <code>where</code> clause doesn't match, <code>count === 0</code>, throws, transaction rolls back → no order, no stock change, cart is <em>not</em> cleared.</p>
<p>Other things the checkout does:</p>
<ul>
<li><p><strong>Prices are recomputed from the DB.</strong> The client sends only <code>{slug, qty}</code>. If a malicious client tries to send <code>{slug, qty, price: 1}</code> for a <code>৳1400</code> Hilsa, the server ignores the price and uses the DB value. Anti-tampering by design.</p>
</li>
<li><p><strong>Live Hot Deals offers are applied</strong> during price recomputation, so the discounted price shown in the cart is what the customer is charged.</p>
</li>
<li><p><strong>Line items are snapshotted.</strong> <code>OrderItem</code> stores <code>productName</code> and <code>unitPrice</code> as of the order a product renamed or repriced tomorrow doesn't change yesterday's order.</p>
</li>
<li><p><strong>Guest checkout allowed</strong> <code>userId</code> is nullable on <code>Order</code>. Guests get a thank-you screen with their order number and can look it up at <code>/orders/lookup</code>.</p>
</li>
<li><p><strong>Order numbers</strong> are <code>ECO-</code> + 8 CSPRNG characters. Collision → retry.</p>
</li>
</ul>
<hr />
<h2>Money how integer math beat floating point</h2>
<p><strong>Rule: never store money in a float.</strong> <code>0.1 + 0.2 !== 0.3</code> in JavaScript, and after a few million multiplications you have real bugs.</p>
<p>MongoDB's Prisma connector doesn't have a <code>Decimal</code> type. So I store <strong>integer poisha</strong> (1/100 of a Taka). A ৳14.99 product is <code>1499</code> in the DB.</p>
<p><code>lib/money.js</code> is the one place I convert:</p>
<pre><code class="language-js">export const toCents   = (taka)  =&gt; Math.round(Number(taka) * 100);
export const toDollars = (cents) =&gt; cents == null ? null : cents / 100;
export function formatMoney(cents) { /* returns "৳1,400.00" */ }
</code></pre>
<p>Rule of thumb: DB + server-side arithmetic in poisha; UI/forms/cart in Taka; only convert at the boundary.</p>
<p>The store is <strong>BDT-only</strong>. I had a multi-currency setup (BDT/USD/AED with admin-managed exchange rates and a <code>CurrencyProvider</code>), but it added complexity I didn't neethe shop is Bangladesh-only. I ripped out the switcher UI and made <code>getActiveCurrency()</code> return BDT unconditionally. The plumbing is dormant, not deleted one file flips it back on if I ever need it.</p>
<hr />
<h2>Post-delivery flow returns &amp; reviews</h2>
<p>Both of these are customer-callable server actions in <code>app/dashboard/orders/_customer-actions.js</code>, guarded by <code>requireAuth()</code> (not <code>requireRole()</code>).</p>
<h3>The 15-day return window</h3>
<p><code>lib/order-return.js</code> has the eligibility check:</p>
<pre><code class="language-js">export function canRequestReturn({ viewerId, order, now }) {
  if (!order)                           return { ok: false, reason: "notFound" };
  if (order.userId !== viewerId)        return { ok: false, reason: "notOwner" };
  if (order.status !== "DELIVERED")     return { ok: false, reason: "notDelivered" };

  const deadline = returnDeadline(order.history, now);
  if (!deadline)                        return { ok: false, reason: "notDelivered" };
  if (now &gt; deadline.getTime())         return { ok: false, reason: "windowClosed", deadline };

  return { ok: true, deadline };
}
</code></pre>
<p>The <code>deadline</code> is <code>deliveredAt + 15 days</code> where <code>deliveredAt</code> is the first DELIVERED event on the order's timeline. Same helper is used in TWO places: the server component computes it once to decide whether to render the button; the server action re-checks it before mutating (defense in depth never trust the client that it should be allowed).</p>
<p>When a customer clicks Request Return:</p>
<ol>
<li><p>Confirm dialog on the client.</p>
</li>
<li><p>Server action re-validates via <code>canRequestReturn</code>.</p>
</li>
<li><p>In one transaction: flip <code>Order.status</code> to <code>CANCELLED</code>, restock all items via the same <code>restockCancelledOrder</code> helper that admin cancellations use, write an <code>OrderStatusEvent</code> with note <code>"Return requested by customer"</code> and <code>actorId = user.id</code>, append an <code>AuditLog</code> row.</p>
</li>
<li><p><code>revalidatePath("/dashboard/orders")</code> so the UI updates without a hard refresh.</p>
</li>
</ol>
<p>After the 15-day window closes, the button hides on the client (<code>canReturn</code> from the server is false), and the server action rejects with <code>windowClosed</code> if someone tries to call it via curl.</p>
<h3>Reviews</h3>
<p><code>Review.@@unique([productId, userId])</code> in the schema means a user can only review a given product once. My <code>submitReviewAction</code>:</p>
<pre><code class="language-js">if (order.userId !== user.id)          return { ok: false, error: "This order isn't yours." };
if (order.status !== "DELIVERED")      return { ok: false, error: "You can only review delivered orders." };
if (order.items.length === 0)          return { ok: false, error: "That product wasn't in this order." };

const existing = await prisma.review.findUnique({
  where: { productId_userId: { productId, userId: user.id } },
});
if (existing) return { ok: false, error: "You've already reviewed this product." };

// Create + recompute Product.rating as running average
</code></pre>
<p>After write, I recompute <code>Product.rating</code> as the average of all approved reviews, rounded to one decimal (matches the display format in <code>ProductCard</code>). Auto-approved for now a moderation flow is a TODO.</p>
<hr />
<h2>Guest → user account: linking orders on signup</h2>
<p>The nicest little feature. A customer checks out as a guest at <code>/checkout</code> with email <code>asha@example.com</code>. Order gets saved with <code>userId: null</code> and <code>email: "asha@example.com"</code>.</p>
<p>Three weeks later, she decides to create an account with the same email. <code>lib/user-service.js</code>:</p>
<pre><code class="language-js">export async function claimGuestOrdersForUser(userId, email) {
  if (!userId || !email) return 0;
  try {
    const res = await prisma.order.updateMany({
      where: {
        userId: null,
        email:  { equals: email, mode: "insensitive" },
      },
      data: { userId },
    });
    return res.count;
  } catch {
    return 0;
  }
}
</code></pre>
<p>Called from BOTH the credentials signup route (<code>app/api/auth/signup/route.js</code>) and the OAuth <code>createUser</code> event (<code>lib/auth.js</code>). The <code>mode: "insensitive"</code> is important if she typed <code>ASHA@example.com</code> at checkout but <code>asha@example.com</code> at signup, we still catch it. Never throws a failure here doesn't block the signup response.</p>
<p>First login: she sees her three weeks' worth of guest orders in her dashboard. No support ticket, no manual link.</p>
<hr />
<h2>Deploying to a 1 GB VPS: what went wrong and how I fixed it</h2>
<p>This section is the honest one.</p>
<p>I picked a small <strong>OpenVZ VPS</strong> 1 GB RAM, 1 CPU, 9.8 GB disk, Ubuntu 24.04. Cheap, fine for a demo. Setup went smoothly:</p>
<ul>
<li><p>Installed Node.js 22, PM2, MongoDB 8.0.</p>
</li>
<li><p>Configured MongoDB as a single-node replica set on <code>127.0.0.1:27017</code> (no auth, localhost-only) with WiredTiger cache capped at 256 MB.</p>
</li>
<li><p>Set up nginx as a reverse proxy on port 80, then upgraded to Let's Encrypt on 443 with certbot (once DNS pointed at the box).</p>
</li>
<li><p>Created a non-root <code>ecobazar</code> user, cloned the repo, <code>npm ci</code>, <code>npm run build</code> first deploy worked.</p>
</li>
</ul>
<p><strong>Then I tried to redeploy.</strong> <code>npm ci</code> OOMed. Kernel killed random processes. Eventually killed sshd. Box became unreachable for 20 minutes until I could reboot from the provider's console.</p>
<p><strong>Root cause:</strong> OpenVZ containers have a <code>privvmpages</code> limit that blocks <code>fork()</code> under memory pressure even with visible free RAM in <code>free -h</code>. <code>npm ci</code> spawns dozens of processes for <code>npm-cli-install-scripts</code>. On a 1 GB container with MongoDB already using ~250 MB, the fork storm exceeds the limit. Plus swap is disallowed on OpenVZ (<code>swapon</code> returns "Operation not permitted").</p>
<p><strong>Failed fix #1:</strong> stop MongoDB during npm install. Still OOMed the fork limit isn't about free RAM, it's about virtual pages committed.</p>
<p><strong>Failed fix #2:</strong> local build on Windows, ship <code>.next/</code> and <code>node_modules/</code> via tar. Two problems:</p>
<ul>
<li><p>Windows npm creates <code>.bin/next</code> as a <strong>bash wrapper script</strong>, not a Linux symlink. When PM2 tried to run it, Node parsed it as JavaScript and threw <code>SyntaxError: missing ) after argument list</code>.</p>
</li>
<li><p>Turbopack's built <code>.next/</code> references <code>@prisma/client-&lt;hash&gt;</code> where the hash is computed against the local <code>node_modules</code> layout. A Linux <code>node_modules</code> computes a different hash → <code>Cannot find module '@prisma/client-2c3a283f134fdcb6'</code>.</p>
</li>
</ul>
<p>Both problems come from Windows and Linux producing different node_modules layouts. Local build → remote deploy only works if both machines match.</p>
<p><strong>The real fix:</strong> build on GitHub Actions.</p>
<hr />
<h2>The GitHub Actions auto-deploy pipeline</h2>
<p><code>.github/workflows/deploy.yml</code> runs on every push to <code>main</code>:</p>
<ol>
<li><p><code>ubuntu-24.04</code> runner (matches VPS exactly).</p>
</li>
<li><p><code>npm ci --legacy-peer-deps</code> (the <code>--legacy-peer-deps</code> is because next-auth's beta declares <code>peerDependencies: next@^14||15</code>; we're on next 16, works fine, npm just needs to be told to accept the mismatch).</p>
</li>
<li><p><code>npm run build</code> runners have 7 GB RAM, no OOM risk. I set dummy env vars for build-time because <code>lib/prisma.js</code> throws at import if <code>DATABASE_URL</code> is malformed:</p>
<pre><code class="language-yaml">env:
  DATABASE_URL: "mongodb://build.local:27017/build?replicaSet=rs0"
  NEXTAUTH_SECRET: "build-time-placeholder-not-used-at-runtime"
</code></pre>
<p>Every route is dynamic (<code>ƒ</code>), so no actual DB call fires during build. The URL just has to pass the shape check.</p>
</li>
<li><p><code>npm prune --omit=dev</code> strip test tooling from <code>node_modules</code>.</p>
</li>
<li><p>Install SSH key from <code>secrets.DEPLOY_SSH_KEY</code> (with a <code>tr -d '\r'</code> scrub because Windows-copied secrets sometimes have CRLF that breaks OpenSSH).</p>
</li>
<li><p><strong>Rsync</strong> <code>.next/</code> <strong>+</strong> <code>node_modules/</code> <strong>+</strong> <code>public/</code> <strong>+ source tree to the VPS as the</strong> <code>ecobazar</code> <strong>user.</strong> <code>-a</code> preserves symlinks (critical for <code>.bin/next</code>). <code>--delete-after</code> only prunes removed files after a successful transfer a mid-stream disconnect keeps the old tree intact.</p>
</li>
<li><p><code>pm2 restart ecobazar --update-env</code> (or first-time start with <code>--max-memory-restart 500M</code> so a runaway worker triggers a controlled restart before it OOMs the box).</p>
</li>
<li><p>Smoke test: curl <code>https://eco.shanto.dev/</code> and expect HTTP 200 within 25 s. Job fails red if not.</p>
</li>
</ol>
<p>Four repo secrets needed: <code>DEPLOY_SSH_KEY</code>, <code>DEPLOY_KNOWN_HOSTS</code>, <code>DEPLOY_HOST</code>, <code>DEPLOY_USER</code>.</p>
<p>I also added a nginx maintenance-page snippet: on <code>502/503/504</code> from the upstream, serve a friendly "we'll be right back" page instead of raw nginx errors. It sits dormant during normal operation and only appears when PM2 is down.</p>
<p><strong>The wiring took SEVEN failed deploys</strong> sed separators, SSH tilde expansion, <code>set -e</code> vs pipefail, missing <code>-i deploy_key</code> on the verify SSH but the final pipeline runs in ~4-6 minutes per deploy and I haven't had to think about it since.</p>
<hr />
<h2>What I learned</h2>
<p><strong>Concrete technical stuff:</strong></p>
<ul>
<li><p>Server components are the default in Next 16. Client components (<code>"use client"</code>) are the exception, not the rule. Most of my pages ship near-zero JavaScript for their rendered HTML.</p>
</li>
<li><p>Server actions (<code>"use server"</code>) let you call server code directly from client components without writing an API route. They're validated with Zod at the boundary and re-check auth every time.</p>
</li>
<li><p>The three-layer authorization pattern (middleware → server component → server action) beats any single layer. If one has a bug, the others catch it.</p>
</li>
<li><p>Race conditions are subtle. A <code>where: { stock: { gte: qty } }</code> predicate is the difference between "sometimes oversells" and "never oversells".</p>
</li>
<li><p>Money is integer minor units, always. <code>1499</code> not <code>14.99</code>.</p>
</li>
<li><p>Client-tampering is a real thing. If your checkout accepts a price from the client, you have a bug.</p>
</li>
<li><p>Every image path from a form is a possible XSS vector. Validate MIME + magic bytes + pick the extension from the validated type, never from the filename.</p>
</li>
</ul>
<p><strong>Deploy stuff I didn't know before:</strong></p>
<ul>
<li><p>1 GB VPS is fine to <em>run</em> a Next.js app on. It is not fine to <em>build</em> on.</p>
</li>
<li><p>Windows and Linux produce different <code>node_modules</code>. Shipping one to the other is a recipe for pain (bin-wrapper shells, Turbopack hash mismatches, Prisma engine mismatches).</p>
</li>
<li><p>Build on the same OS as the runtime. GitHub Actions runners are the free easy way.</p>
</li>
<li><p>Let's Encrypt auto-renewal via <code>certbot.timer</code> is a joy after ever setting up manual cert rotation.</p>
</li>
<li><p>PM2 <code>--max-memory-restart 500M</code> is a good guardrail when you're near the RAM ceiling.</p>
</li>
<li><p>Nginx <code>error_page 502 503 504 = @maintenance;</code> gives you a real "we'll be right back" page for the cost of two lines.</p>
</li>
</ul>
<p><strong>Meta stuff:</strong></p>
<ul>
<li><p>Writing docs as you go beats writing them at the end. I keep <code>README.md</code>, <code>DOCUMENTATION.md</code> and <code>CLAUDE.md</code> in sync with the code. Any feature I add without a doc note is a feature future-me will forget how to change.</p>
</li>
<li><p>Test what you fix. E2E tests broke every time I rebranded the catalogue, but they also caught the currency-symbol bug on the shop slider that I would have missed in prod.</p>
</li>
<li><p>The scariest bug is the one that fails silently. <code>rsync | tail</code> was silently swallowing rsync's non-zero exit for two failed deploys before I added <code>set -o pipefail</code>.</p>
</li>
</ul>
<hr />
<h2>What's next</h2>
<p>Things I know are on the roadmap:</p>
<ul>
<li><p><strong>Payment integration</strong> the schema has bKash, Nagad, PayPal, Amazon, COD fields. Only COD actually works. Wiring bKash next.</p>
</li>
<li><p><strong>Review moderation UI</strong> reviews auto-approve today. Admin approve/reject queue.</p>
</li>
<li><p><strong>Real transactional email</strong> <code>lib/mailer.js</code> logs to console. Swap for Resend/SES.</p>
</li>
<li><p><strong>Shared-store rate limiting</strong> currently in-memory (<code>lib/rate-limit.js</code>), so it doesn't coordinate across app instances. Move to Redis.</p>
</li>
<li><p><strong>Consolidate coupons</strong> the coupon table is duplicated between <code>CartContext.jsx</code> and <code>order-actions.js</code>. One shared constant.</p>
</li>
<li><p><strong>TypeScript migration</strong> probably. I'm ready.</p>
</li>
<li><p><strong>Distinct</strong> <code>RETURNED</code> <strong>status</strong> currently returns are recorded as <code>CANCELLED</code> with a note. A distinct enum value would be cleaner.</p>
</li>
</ul>
<hr />
<h2>Wrapping up</h2>
<p>This was my first full-stack project and I ended up with a real, deployed, working store 16,055 lines of code, 137 source files, 19 database models, 26 routes, 18 E2E test files, and a story I can actually tell about every decision. It works today at <a href="https://eco.shanto.dev">eco.shanto.dev</a> go put something in the cart.</p>
<p>If you're building your first full-stack app: don't be afraid of the deploy step. The build I was so proud of on my laptop was totally different from the build that actually needs to run on a Linux box. Skip that lesson by building on GitHub Actions from day one.</p>
<p>If this write-up helped, share it, or drop a line at <a href="https://eco.shanto.dev/contact">eco.shanto.dev/contact</a>. And if you're a hiring manager reading this hello 👋.</p>
<p>Shanto</p>
]]></content:encoded></item><item><title><![CDATA[Introduction to JavaScript]]></title><description><![CDATA[এই ব্লগ তাদের জন্য—

যারা JavaScript শেখা শুরু করেছে

যারা var, let, const নিয়ে কনফিউজ

যারা Interview-তে উত্তর দিতে পারে না

যারা মুখস্থ না করে বুঝে শিখতে চায়


যদি আপনি তাদের একজন হন, তাহলে স্বাগত]]></description><link>https://notes.shanto.dev/bn-js-p-1</link><guid isPermaLink="true">https://notes.shanto.dev/bn-js-p-1</guid><dc:creator><![CDATA[Jahid Hasan Shanto]]></dc:creator><pubDate>Mon, 13 Jul 2026 10:08:05 GMT</pubDate><content:encoded><![CDATA[<p><strong>এই ব্লগ তাদের জন্য—</strong></p>
<ul>
<li><p>যারা JavaScript শেখা শুরু করেছে</p>
</li>
<li><p>যারা var, let, const নিয়ে কনফিউজ</p>
</li>
<li><p>যারা Interview-তে উত্তর দিতে পারে না</p>
</li>
<li><p>যারা মুখস্থ না করে বুঝে শিখতে চায়</p>
</li>
</ul>
<p>যদি আপনি তাদের একজন হন, তাহলে স্বাগতম আপনাকে, আমি <a href="https://shanto.dev">শান্ত</a> আছি আপনাদের সাথে।</p>
]]></content:encoded></item><item><title><![CDATA[Laravel Basics]]></title><description><![CDATA[How to kick start a Laravel project?
First we need to go Laravel official website and open getting started page.
If you’re creating this application for the first time you need to install PHP, Composer and Laravel installer. In addition, you should i...]]></description><link>https://notes.shanto.dev/laravel-basics</link><guid isPermaLink="true">https://notes.shanto.dev/laravel-basics</guid><category><![CDATA[PHP]]></category><category><![CDATA[Laravel]]></category><dc:creator><![CDATA[Jahid Hasan Shanto]]></dc:creator><pubDate>Thu, 04 Sep 2025 12:17:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1756988220721/43aa7cf2-8819-4075-a753-705e8c846f79.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>How to kick start a Laravel project?</p>
<p>First we need to go <a target="_blank" href="https://laravel.com/">Laravel official website</a> and open getting started page.</p>
<p>If you’re creating this application for the first time you need to install PHP, Composer and Laravel installer. In addition, you should install either Node and NPM or Bun so that you can compile your application's frontend assets.</p>
<p>If you already have PHP and Composer installed, you may install the Laravel installer via Composer:</p>
<pre><code class="lang-php">composer <span class="hljs-keyword">global</span> <span class="hljs-keyword">require</span> laravel/installer
</code></pre>
<p>After you have installed PHP, Composer, and the Laravel installer, you're ready to create a new Laravel application. The Laravel installer will prompt you to select your preferred testing framework, database, and starter kit:</p>
<pre><code class="lang-php">laravel <span class="hljs-keyword">new</span> example-app
</code></pre>
<p>Once the application has been created, you can start Laravel's local development server, queue worker, and Vite development server using the <code>dev</code> Composer script:</p>
<pre><code class="lang-php">cd example-app
npm install &amp;&amp; npm run build
composer run dev
</code></pre>
<p>Once you have started the development server, your application will be accessible in your web browser at <a target="_blank" href="http://localhost:8000">http://localhost:8000</a>.</p>
<h3 id="heading-databases-and-migrations"><strong>Databases and Migrations</strong></h3>
<p>Now that you have created your Laravel application, you probably want to store some data in a database. By default, your application's <code>.env</code> configuration file specifies that Laravel will be interacting with an SQLite database.</p>
<p>During the creation of the application, Laravel created a <code>database/database.sqlite</code> file for you, and ran the necessary migrations to create the application's database tables.</p>
<p>If you prefer to use another database driver such as MySQL or PostgreSQL, you can update your <code>.env</code> configuration file to use the appropriate database. For example, if you wish to use MySQL, update your <code>.env</code> configuration file's <code>DB_*</code> variables like so:</p>
<pre><code class="lang-php">DB_CONNECTION=mysqlDB_HOST=<span class="hljs-number">127.0</span><span class="hljs-number">.0</span><span class="hljs-number">.1</span>
DB_PORT=<span class="hljs-number">3306</span>
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
</code></pre>
<p>If you choose to use a database other than SQLite, you will need to create the database and run your application's database migrations:</p>
<pre><code class="lang-php">php artisan migrate
</code></pre>
<h2 id="heading-understanding-class-accessors-and-traits-in-laravel">Understanding Class Accessors and Traits in Laravel</h2>
<h3 id="heading-what-is-a-class-accessor">🔹 What is a Class Accessor?</h3>
<p>In Laravel, a <strong>class accessor</strong> refers to a method defined within an Eloquent model that automatically transforms or formats attributes when they are retrieved from the database. Instead of manually applying formatting or transformations every time you access a value, accessors centralize this logic within the model itself.</p>
<p>Accessors are particularly useful for maintaining clean and readable code. They ensure that data is consistently presented in the desired format across your entire application. By using accessors, developers avoid repeating the same transformation logic in controllers, views, or other parts of the codebase. This makes applications more maintainable and helps enforce business rules at the model level.</p>
<p>In short, accessors provide a way to <strong>control the output of model attributes</strong>, ensuring that values are always displayed in a standardized and predictable manner.</p>
<hr />
<h3 id="heading-why-use-traits-in-laravel">🔹 Why Use Traits in Laravel?</h3>
<p>A <strong>trait</strong> in PHP and Laravel is a mechanism for reusing sets of methods across multiple classes. Since PHP does not support multiple inheritance, traits offer a way to share functionality between unrelated classes without duplicating code.</p>
<p>Laravel itself makes extensive use of traits. For instance, features like soft deletion, notification handling, and authorization are implemented as traits that can be easily added to models or classes. This approach encourages modular design, where specific pieces of functionality can be mixed into a class as needed.</p>
<p>The primary benefit of traits is <strong>code reusability</strong>. Instead of writing the same methods in different classes, developers can define them once in a trait and then use them wherever required. This reduces redundancy, keeps code organized, and makes it easier to maintain.</p>
<p>Traits also provide flexibility, as a single class can use multiple traits at the same time. This mimics some advantages of multiple inheritance while keeping PHP’s class structure simple and manageable.</p>
<hr />
<h3 id="heading-multiple-inheritance-in-laravel">🔹 Multiple Inheritance in Laravel</h3>
<p>PHP, and by extension Laravel, does not support multiple inheritance directly. A class can only extend one parent class at a time. However, traits fill this gap by allowing a class to “inherit” behavior from multiple sources.</p>
<p>Through traits, Laravel achieves the effect of multiple inheritance without introducing the complexity and conflicts that often come with it. Developers can combine multiple traits in a single class, gaining access to diverse functionality in a clean and controlled way.</p>
<hr />
<h3 id="heading-final-thoughts">✅ Final Thoughts</h3>
<ul>
<li><p><strong>Class Accessors</strong> help standardize how model attributes are presented, ensuring consistent formatting across your application.</p>
</li>
<li><p><strong>Traits</strong> promote code reusability and modularity, offering a way to include shared behavior across multiple classes.</p>
</li>
<li><p>While <strong>multiple inheritance</strong> is not possible in PHP, traits provide a powerful alternative, allowing Laravel applications to remain clean, flexible, and maintainable.</p>
</li>
<li><p><strong>Accessor:</strong> Transform attributes automatically when retrieving from a model.</p>
</li>
<li><p><strong>Trait:</strong> Reusable piece of code across classes (alternative to multiple inheritance).</p>
</li>
<li><p><strong>Multiple inheritance:</strong> Not allowed in PHP, but Traits act as a replacement.</p>
</li>
<li><p><strong>PHP does not support multiple inheritance</strong> <strong>directly</strong>.</p>
</li>
<li><p>A class <strong>can only extend one parent class</strong>.</p>
</li>
<li><p>But, <strong>Traits provide a workaround</strong>: a class can <code>use</code> multiple traits at the same time.</p>
</li>
<li><p>Single Inheritance (extend one class)</p>
</li>
<li><p>Multiple Traits (reuse many behaviors).</p>
</li>
</ul>
<h2 id="heading-what-is-an-unsigned-attribute">🔹 What is an <strong>Unsigned Attribute</strong>?</h2>
<p>In databases (like <strong>MySQL</strong>, which Laravel commonly uses), an <strong>unsigned attribute</strong> means that a <strong>numeric column cannot store negative values</strong>.</p>
<ul>
<li><p>Normally, an <code>INT</code> column can store both <strong>negative</strong> and <strong>positive</strong> numbers (for example, <code>-2,147,483,648</code> to <code>2,147,483,647</code>).</p>
</li>
<li><p>If you mark it as <strong>UNSIGNED</strong>, the column can only store <strong>zero and positive values</strong>, but the <strong>range of positive values doubles</strong> (for example, <code>0</code> to <code>4,294,967,295</code>).</p>
</li>
</ul>
<hr />
<h2 id="heading-why-use-unsigned">🔹 Why use UNSIGNED?</h2>
<ol>
<li><p><strong>Logical correctness</strong> → Some data should never be negative, such as:</p>
<ul>
<li><p>IDs (Primary Keys)</p>
</li>
<li><p>Age</p>
</li>
<li><p>Price</p>
</li>
<li><p>Quantity</p>
</li>
</ul>
</li>
<li><p><strong>Extended positive range</strong> → By disallowing negatives, the database allows a <strong>wider positive range</strong>.</p>
</li>
<li><p><strong>Consistency and validation</strong> → It prevents accidental insertion of invalid negative values.</p>
</li>
</ol>
<hr />
<h2 id="heading-unsigned-in-laravel-migrations">🔹 Unsigned in Laravel Migrations</h2>
<p>When defining migrations in Laravel, you can specify <code>unsigned()</code> on numeric columns.<br />For example:</p>
<ul>
<li><p><code>unsignedBigInteger</code> → commonly used for foreign keys and IDs.</p>
</li>
<li><p><code>unsignedDecimal</code>, <code>unsignedInteger</code>, etc.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Learn PHP Basics]]></title><description><![CDATA[What is scope resolution operator in PHP? The Scope Resolution Operator in PHP, also known as the "double colon" or ::, is a token that allows access to static, constant, and overridden properties or methods of a class. It provides a way to refer to ...]]></description><link>https://notes.shanto.dev/learn-php-basics</link><guid isPermaLink="true">https://notes.shanto.dev/learn-php-basics</guid><category><![CDATA[PHP]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Jahid Hasan Shanto]]></dc:creator><pubDate>Thu, 04 Sep 2025 11:49:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1756981546706/ff160090-1a35-46d0-809c-f1f91a0599b5.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<ol>
<li><p><strong>What is scope resolution operator in PHP?</strong><br /> The Scope Resolution Operator in PHP, also known as the "double colon" or <code>::</code>, is a token that allows access to static, constant, and overridden properties or methods of a class. It provides a way to refer to elements within a class's scope without needing an instance of that class.</p>
<p> <strong>Key uses of the Scope Resolution Operator:</strong></p>
<ul>
<li><strong>Accessing Static Properties and Methods:</strong> You can call static methods or access static properties directly using the class name followed by <code>::</code> and the method/property name.</li>
</ul>
</li>
</ol>
<pre><code class="lang-php">        <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span> </span>{
            <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> $staticProperty = <span class="hljs-string">"Hello"</span>;
            <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">staticMethod</span>(<span class="hljs-params"></span>) </span>{
                <span class="hljs-keyword">return</span> <span class="hljs-string">"World"</span>;
            }
        }
        <span class="hljs-keyword">echo</span> MyClass::$staticProperty; <span class="hljs-comment">// Output: Hello</span>
        <span class="hljs-keyword">echo</span> MyClass::staticMethod(); <span class="hljs-comment">// Output: World</span>
</code></pre>
<ul>
<li><strong>Accessing Constants:</strong> Class constants are accessed using the class name followed by <code>::</code> and the constant name.</li>
</ul>
<pre><code class="lang-php">        <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span> </span>{
            <span class="hljs-keyword">const</span> MY_CONSTANT = <span class="hljs-string">"PHP"</span>;
        }
        <span class="hljs-keyword">echo</span> MyClass::MY_CONSTANT; <span class="hljs-comment">// Output: PHP</span>
</code></pre>
<ul>
<li>Accessing Overridden Properties or Methods (using <code>parent</code>): Within a child class, you can use <code>parent::</code> to call a method or access a property from its immediate parent class, even if it has been overridden in the child class.</li>
</ul>
<pre><code class="lang-php">        <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ParentClass</span> </span>{
            <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params"></span>) </span>{
                <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello from Parent!"</span>;
            }
        }

        <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ChildClass</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ParentClass</span> </span>{
            <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params"></span>) </span>{
                <span class="hljs-keyword">return</span> <span class="hljs-built_in">parent</span>::sayHello() . <span class="hljs-string">" And from Child!"</span>;
            }
        }
        $obj = <span class="hljs-keyword">new</span> ChildClass();
        <span class="hljs-keyword">echo</span> $obj-&gt;sayHello(); <span class="hljs-comment">// Output: Hello from Parent! And from Child!</span>
</code></pre>
<ul>
<li>Referring to the Current Class (using <code>self</code>): Inside a class, <code>self::</code> can be used to refer to static properties, static methods, or constants defined within that same class.</li>
</ul>
<pre><code class="lang-php">        <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span> </span>{
            <span class="hljs-keyword">const</span> GREETING = <span class="hljs-string">"Greetings!"</span>;
            <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getGreeting</span>(<span class="hljs-params"></span>) </span>{
                <span class="hljs-keyword">return</span> <span class="hljs-built_in">self</span>::GREETING;
            }
        }
        <span class="hljs-keyword">echo</span> MyClass::getGreeting(); <span class="hljs-comment">// Output: Greetings!</span>
</code></pre>
<p><strong>Properties can also have different levels of visibility, controlling where they can be accessed</strong>:</p>
<ul>
<li><p><code>public</code>: Accessible from anywhere (inside and outside the class, and by child classes).</p>
</li>
<li><p><code>private</code>: Accessible only within the class where they are defined.</p>
</li>
<li><p><code>protected</code>: Accessible within the class where they are defined and by its child classes.</p>
</li>
</ul>
<h2 id="heading-what-is-a-variable-in-php">What is a Variable in PHP?</h2>
<p>A <strong>variable</strong> is a symbolic name that stores data. In PHP, variables always start with a <strong>dollar sign (</strong><code>$</code>) followed by the variable name.</p>
<p>Example:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
$name = <span class="hljs-string">"Jahid"</span>;   <span class="hljs-comment">// String</span>
$age = <span class="hljs-number">25</span>;         <span class="hljs-comment">// Integer</span>
$isStudent = <span class="hljs-literal">true</span>; <span class="hljs-comment">// Boolean</span>
<span class="hljs-meta">?&gt;</span>
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>$name</code> stores a <strong>string</strong> (<code>"Jahid"</code>)</p>
</li>
<li><p><code>$age</code> stores an <strong>integer</strong> (<code>25</code>)</p>
</li>
<li><p><code>$isStudent</code> stores a <strong>boolean</strong> (<code>true</code>)</p>
</li>
</ul>
<hr />
<h2 id="heading-rules-for-naming-variables">Rules for Naming Variables</h2>
<ol>
<li><p>A variable must start with a <strong>$</strong> sign.</p>
</li>
<li><p>The first character after <code>$</code> must be a <strong>letter</strong> or an <strong>underscore (_)</strong>.</p>
</li>
<li><p>Variable names are <strong>case-sensitive</strong> (<code>$Name</code> and <code>$name</code> are different).</p>
</li>
</ol>
<p>✅ Valid:</p>
<pre><code class="lang-php">$myVar = <span class="hljs-number">100</span>;
$_value = <span class="hljs-string">"Hello"</span>;
$Name = <span class="hljs-string">"PHP"</span>;
</code></pre>
<p>❌ Invalid:</p>
<pre><code class="lang-php">$<span class="hljs-number">1</span>name = <span class="hljs-string">"Wrong"</span>;  <span class="hljs-comment">// cannot start with a number</span>
$my-<span class="hljs-keyword">var</span> = <span class="hljs-number">20</span>;      <span class="hljs-comment">// cannot use a hyphen</span>
</code></pre>
<hr />
<h2 id="heading-variable-structure-in-php">Variable Structure in PHP</h2>
<p>In databases like <strong>MySQL</strong>, you define data types such as <code>VARCHAR</code>, <code>INT</code>, <code>BOOLEAN</code>, etc. In PHP, however, variables are <strong>loosely typed</strong>. That means you don’t have to declare the data type explicitly.</p>
<p>PHP automatically decides the type based on the value you assign. Let’s compare this to database structures.</p>
<hr />
<h3 id="heading-1-varchar-variable-character-string-php-string">1. VARCHAR (Variable Character String) → PHP String</h3>
<ul>
<li><p><strong>Database side</strong>: <code>VARCHAR(255)</code> means it can hold up to 255 characters, but uses only as much space as needed.</p>
</li>
<li><p><strong>PHP side</strong>: Strings are sequences of characters enclosed in <strong>single quotes (' ')</strong> or <strong>double quotes (" ")</strong>.</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
$greeting = <span class="hljs-string">"Hello, World!"</span>;
<span class="hljs-keyword">echo</span> $greeting; <span class="hljs-comment">// Output: Hello, World!</span>
<span class="hljs-meta">?&gt;</span>
</code></pre>
<p>🔹 PHP manages memory dynamically for strings, just like how <code>VARCHAR</code> works in databases.</p>
<hr />
<h3 id="heading-2-int-integer-php-integer">2. INT (Integer) → PHP Integer</h3>
<ul>
<li><p><strong>Database side</strong>: <code>INT</code> stores whole numbers.</p>
</li>
<li><p><strong>PHP side</strong>: An <strong>integer</strong> is a whole number, positive or negative, without decimals.</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
$age = <span class="hljs-number">30</span>;
$year = <span class="hljs-number">-2025</span>;
<span class="hljs-keyword">echo</span> $age + <span class="hljs-number">5</span>; <span class="hljs-comment">// Output: 35</span>
<span class="hljs-meta">?&gt;</span>
</code></pre>
<hr />
<h3 id="heading-3-decimal-float-php-float-double">3. DECIMAL / FLOAT → PHP Float (Double)</h3>
<ul>
<li><p><strong>Database side</strong>: <code>DECIMAL</code> or <code>FLOAT</code> is used for numbers with decimal points.</p>
</li>
<li><p><strong>PHP side</strong>: A <strong>float</strong> stores numbers with fractions or decimals.</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
$price = <span class="hljs-number">99.99</span>;
$pi = <span class="hljs-number">3.14159</span>;
<span class="hljs-keyword">echo</span> $pi * <span class="hljs-number">2</span>; <span class="hljs-comment">// Output: 6.28318</span>
<span class="hljs-meta">?&gt;</span>
</code></pre>
<hr />
<h3 id="heading-4-boolean-php-boolean">4. BOOLEAN → PHP Boolean</h3>
<ul>
<li><p><strong>Database side</strong>: <code>BOOLEAN</code> usually stores <code>0</code> (false) or <code>1</code> (true).</p>
</li>
<li><p><strong>PHP side</strong>: A <strong>boolean</strong> can be either <code>true</code> or <code>false</code>.</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
$isLoggedIn = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">if</span> ($isLoggedIn) {
    <span class="hljs-keyword">echo</span> <span class="hljs-string">"Welcome back!"</span>;
}
<span class="hljs-meta">?&gt;</span>
</code></pre>
<hr />
<h3 id="heading-5-date-datetime-php-date-amp-time-functions">5. DATE / DATETIME → PHP Date &amp; Time Functions</h3>
<ul>
<li><p><strong>Database side</strong>: <code>DATE</code>, <code>TIME</code>, <code>DATETIME</code> store calendar values.</p>
</li>
<li><p><strong>PHP side</strong>: PHP doesn’t have a specific <strong>date variable type</strong>, but it has functions and objects to handle dates.</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
$currentDate = date(<span class="hljs-string">"Y-m-d H:i:s"</span>);
<span class="hljs-keyword">echo</span> $currentDate; <span class="hljs-comment">// Output: 2025-09-04 17:35:00 (example)</span>
<span class="hljs-meta">?&gt;</span>
</code></pre>
<hr />
<h3 id="heading-6-null-php-null">6. NULL → PHP NULL</h3>
<ul>
<li><p><strong>Database side</strong>: <code>NULL</code> means "no value assigned."</p>
</li>
<li><p><strong>PHP side</strong>: <code>NULL</code> is a special type that represents an empty variable.</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
$myVar = <span class="hljs-literal">NULL</span>;
var_dump($myVar); <span class="hljs-comment">// Output: NULL</span>
<span class="hljs-meta">?&gt;</span>
</code></pre>
<hr />
<h2 id="heading-type-juggling-and-type-casting">Type Juggling and Type Casting</h2>
<p>One unique thing about PHP variables is <strong>type juggling</strong>. PHP automatically converts variables from one type to another when needed.</p>
<p>Example:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
$number = <span class="hljs-string">"100"</span>; <span class="hljs-comment">// This is a string</span>
$sum = $number + <span class="hljs-number">50</span>; <span class="hljs-comment">// PHP converts it to an integer</span>
<span class="hljs-keyword">echo</span> $sum; <span class="hljs-comment">// Output: 150</span>
<span class="hljs-meta">?&gt;</span>
</code></pre>
<p>You can also <strong>force type casting</strong>:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
$val = <span class="hljs-string">"50.25"</span>;
$intVal = (<span class="hljs-keyword">int</span>)$val;
<span class="hljs-keyword">echo</span> $intVal; <span class="hljs-comment">// Output: 50</span>
<span class="hljs-meta">?&gt;</span>
</code></pre>
<hr />
<h2 id="heading-variable-scope-in-php">Variable Scope in PHP</h2>
<p>The <strong>scope</strong> of a variable defines where it can be accessed.</p>
<ol>
<li><p><strong>Local Scope</strong> → Inside a function</p>
</li>
<li><p><strong>Global Scope</strong> → Outside functions</p>
</li>
<li><p><strong>Static Scope</strong> → Retains value inside a function between calls</p>
</li>
<li><p><strong>Superglobals</strong> → Special built-in variables (<code>$_POST</code>, <code>$_GET</code>, <code>$_SESSION</code>, etc.)</p>
</li>
</ol>
<p>Example:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
$globalVar = <span class="hljs-string">"Hello"</span>; <span class="hljs-comment">// Global</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">test</span>(<span class="hljs-params"></span>) </span>{
    $localVar = <span class="hljs-string">"World"</span>; <span class="hljs-comment">// Local</span>
    <span class="hljs-keyword">echo</span> $localVar;
}
test(); <span class="hljs-comment">// Output: World</span>
<span class="hljs-keyword">echo</span> $globalVar; <span class="hljs-comment">// Output: Hello</span>
<span class="hljs-meta">?&gt;</span>
</code></pre>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>Variables in PHP are <strong>flexible, dynamic, and powerful</strong>. Unlike databases where you must define fixed data types (<code>VARCHAR</code>, <code>INT</code>, <code>BOOLEAN</code>), PHP handles this automatically.</p>
<ul>
<li><p>Strings in PHP work similarly to <code>VARCHAR</code>.</p>
</li>
<li><p>Numbers map to <code>INT</code> or <code>FLOAT</code>.</p>
</li>
<li><p>Booleans represent true/false logic.</p>
</li>
<li><p>Dates require PHP functions or objects.</p>
</li>
<li><p>NULL values work the same way as databases.</p>
</li>
</ul>
<p>Understanding these concepts helps you write cleaner, more efficient PHP code — and also makes it easier to work with databases since you’ll know how PHP variables map to SQL data types.</p>
]]></content:encoded></item><item><title><![CDATA[The Grammar of PHP: Understanding the Language Structure]]></title><description><![CDATA[PHP (Hypertext Preprocessor) is one of the most widely used server-side scripting languages for web development. Like all programming languages, PHP has a defined grammar and syntax that dictate how code should be structured. In this blog, we will ex...]]></description><link>https://notes.shanto.dev/the-grammar-of-php-understanding-the-language-structure</link><guid isPermaLink="true">https://notes.shanto.dev/the-grammar-of-php-understanding-the-language-structure</guid><category><![CDATA[PHP]]></category><category><![CDATA[PHPUnit]]></category><category><![CDATA[php8]]></category><category><![CDATA[PHP development]]></category><dc:creator><![CDATA[Jahid Hasan Shanto]]></dc:creator><pubDate>Tue, 18 Mar 2025 03:15:30 GMT</pubDate><content:encoded><![CDATA[<p>PHP (Hypertext Preprocessor) is one of the most widely used server-side scripting languages for web development. Like all programming languages, PHP has a defined grammar and syntax that dictate how code should be structured. In this blog, we will explore the grammar of PHP, covering its syntax rules, elements, and best practices.</p>
<h2 id="heading-understanding-php-grammar">Understanding PHP Grammar</h2>
<p>The grammar of PHP refers to the rules that define how the language is written and interpreted by the PHP engine. These rules include syntax, keywords, operators, data types, and control structures.</p>
<h3 id="heading-1-php-syntax-basics">1. PHP Syntax Basics</h3>
<p>PHP scripts are typically embedded within HTML using <code>&lt;?php ... ?&gt;</code> tags. The syntax follows standard programming conventions, such as using semicolons (<code>;</code>) to terminate statements.</p>
<p>Example:</p>
<pre><code class="lang-plaintext">&lt;?php
    echo "Hello, World!";
?&gt;
</code></pre>
<h3 id="heading-2-variables-and-data-types">2. Variables and Data Types</h3>
<p>Variables in PHP are defined using the <code>$</code> symbol, and data types are dynamically assigned. PHP supports various data types, including:</p>
<ul>
<li><p><strong>Strings</strong>: <code>$name = "John";</code></p>
</li>
<li><p><strong>Integers</strong>: <code>$age = 25;</code></p>
</li>
<li><p><strong>Floats</strong>: <code>$price = 99.99;</code></p>
</li>
<li><p><strong>Booleans</strong>: <code>$isActive = true;</code></p>
</li>
<li><p><strong>Arrays</strong>: <code>$colors = ["Red", "Green", "Blue"];</code></p>
</li>
<li><p><strong>Objects</strong>: <code>class Car { public $brand; }</code></p>
</li>
<li><p><strong>NULL</strong>: <code>$var = null;</code></p>
</li>
</ul>
<h3 id="heading-3-operators-in-php">3. Operators in PHP</h3>
<p>Operators perform operations on variables and values. PHP includes:</p>
<ul>
<li><p><strong>Arithmetic Operators</strong>: <code>+</code>, <code>-</code>, <code>*</code>, <code>/</code>, <code>%</code></p>
</li>
<li><p><strong>Comparison Operators</strong>: <code>==</code>, <code>!=</code>, <code>&gt;</code>, <code>&lt;</code>, <code>&gt;=</code>, <code>&lt;=</code></p>
</li>
<li><p><strong>Logical Operators</strong>: <code>&amp;&amp;</code>, <code>||</code>, <code>!</code></p>
</li>
<li><p><strong>Assignment Operators</strong>: <code>=</code>, <code>+=</code>, <code>-=</code>, <code>*=</code>, <code>/=</code></p>
</li>
</ul>
<p>Example:</p>
<pre><code class="lang-plaintext">$a = 10;
$b = 20;
$sum = $a + $b;
echo $sum; // Output: 30
</code></pre>
<h3 id="heading-4-control-structures">4. Control Structures</h3>
<p>PHP provides conditional statements and loops to control the flow of execution.</p>
<ul>
<li><strong>If-Else Statement</strong>:</li>
</ul>
<pre><code class="lang-plaintext">if ($age &gt;= 18) {
    echo "Adult";
} else {
    echo "Minor";
}
</code></pre>
<ul>
<li><strong>Switch Statement</strong>:</li>
</ul>
<pre><code class="lang-plaintext">switch ($color) {
    case "red":
        echo "You chose red";
        break;
    case "blue":
        echo "You chose blue";
        break;
    default:
        echo "Unknown color";
}
</code></pre>
<ul>
<li><strong>Loops (For, While, Foreach)</strong>:</li>
</ul>
<pre><code class="lang-plaintext">for ($i = 0; $i &lt; 5; $i++) {
    echo "Number: $i";
}
</code></pre>
<h3 id="heading-5-functions-in-php">5. Functions in PHP</h3>
<p>Functions in PHP are defined using the <code>function</code> keyword and help in code reuse.</p>
<pre><code class="lang-plaintext">function greet($name) {
    return "Hello, " . $name . "!";
}
echo greet("Alice");
</code></pre>
<h3 id="heading-6-object-oriented-php">6. Object-Oriented PHP</h3>
<p>PHP supports object-oriented programming (OOP) with classes and objects.</p>
<pre><code class="lang-plaintext">class Car {
    public $brand;
    public function __construct($brand) {
        $this-&gt;brand = $brand;
    }
    public function getBrand() {
        return $this-&gt;brand;
    }
}
$car = new Car("Toyota");
echo $car-&gt;getBrand();
</code></pre>
<h3 id="heading-7-php-error-handling">7. PHP Error Handling</h3>
<p>PHP provides mechanisms to handle errors using <code>try-catch</code> blocks and the <code>error_reporting()</code> function.</p>
<pre><code class="lang-plaintext">try {
    throw new Exception("An error occurred");
} catch (Exception $e) {
    echo $e-&gt;getMessage();
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Understanding the grammar of PHP is essential for writing clean, efficient, and error-free code. By following PHP's syntax rules, utilizing proper control structures, and leveraging functions and OOP concepts, developers can create scalable and maintainable applications. Whether you are a beginner or an experienced developer, mastering PHP grammar will enhance your coding skills and improve the efficiency of your applications.</p>
]]></content:encoded></item><item><title><![CDATA[PHP 8: Features, Usages, and Key Elements]]></title><description><![CDATA[PHP (Hypertext Preprocessor) has been a dominant server-side scripting language for web development since its inception. With the release of PHP 8, developers gained access to powerful new features, optimizations, and improvements that enhance both p...]]></description><link>https://notes.shanto.dev/php-8-features</link><guid isPermaLink="true">https://notes.shanto.dev/php-8-features</guid><category><![CDATA[PHP]]></category><category><![CDATA[PHPUnit]]></category><category><![CDATA[PhpStorm]]></category><category><![CDATA[php frameworks]]></category><category><![CDATA[php programming]]></category><dc:creator><![CDATA[Jahid Hasan Shanto]]></dc:creator><pubDate>Mon, 17 Mar 2025 06:48:23 GMT</pubDate><content:encoded><![CDATA[<p>PHP (Hypertext Preprocessor) has been a dominant server-side scripting language for web development since its inception. With the release of PHP 8, developers gained access to powerful new features, optimizations, and improvements that enhance both performance and usability. In this blog, we will explore the significance of PHP, its primary usages, and some key elements introduced in PHP 8.</p>
<h2 id="heading-why-use-php">Why Use PHP?</h2>
<p>PHP is widely used for building dynamic web applications and websites due to its versatility, ease of use, and compatibility with various databases and servers. Some of the key reasons to use PHP include:</p>
<ul>
<li><p><strong>Open-source and Free</strong>: PHP is free to use and has a large community of developers.</p>
</li>
<li><p><strong>Cross-platform Compatibility</strong>: Runs on Windows, macOS, Linux, and various web servers like Apache and Nginx.</p>
</li>
<li><p><strong>Database Integration</strong>: Supports MySQL, PostgreSQL, MongoDB, and other databases.</p>
</li>
<li><p><strong>Easy to Learn</strong>: PHP has a straightforward syntax, making it accessible for beginners.</p>
</li>
<li><p><strong>Scalability</strong>: PHP can handle both small-scale and enterprise-level applications.</p>
</li>
<li><p><strong>Extensive Frameworks</strong>: Popular frameworks like Laravel, Symfony, and CodeIgniter enhance development efficiency.</p>
</li>
</ul>
<h2 id="heading-new-features-in-php-8">New Features in PHP 8</h2>
<p>PHP 8 introduced several new features and improvements that make coding more efficient and robust. Some of the notable features include:</p>
<h3 id="heading-1-just-in-time-jit-compilation">1. Just-In-Time (JIT) Compilation</h3>
<p>JIT improves performance by compiling PHP code into machine code at runtime, significantly boosting execution speed for computational tasks.</p>
<h3 id="heading-2-union-types">2. Union Types</h3>
<p>PHP 8 allows defining multiple data types for a single variable, improving type safety. Example:</p>
<pre><code class="lang-plaintext">function processInput(int|string $input) {
    return "Processed: " . $input;
}
</code></pre>
<h3 id="heading-3-named-arguments">3. Named Arguments</h3>
<p>Named arguments allow passing function arguments by name instead of position, improving readability.</p>
<pre><code class="lang-plaintext">function createUser(string $name, int $age) {
    return "$name is $age years old.";
}

echo createUser(age: 25, name: "John");
</code></pre>
<h3 id="heading-4-match-expression">4. Match Expression</h3>
<p>An improved alternative to <code>switch</code>, match expressions return values and support strict comparisons.</p>
<pre><code class="lang-plaintext">$grade = 'A';
$message = match ($grade) {
    'A' =&gt; 'Excellent',
    'B' =&gt; 'Good',
    'C' =&gt; 'Average',
    default =&gt; 'Failed'
};
</code></pre>
<h3 id="heading-5-constructor-property-promotion">5. Constructor Property Promotion</h3>
<p>This feature simplifies class constructors by reducing boilerplate code.</p>
<pre><code class="lang-plaintext">class User {
    public function __construct(private string $name, private int $age) {}
}
</code></pre>
<h3 id="heading-6-nullsafe-operator">6. Nullsafe Operator</h3>
<p>Instead of checking if a property exists before accessing it, PHP 8 allows using <code>?-&gt;</code> to prevent errors.</p>
<pre><code class="lang-plaintext">$user = null;
$name = $user?-&gt;profile?-&gt;name; // Avoids errors if profile is null
</code></pre>
<h3 id="heading-7-attributes">7. Attributes</h3>
<p>PHP 8 introduces native support for attributes (annotations) to define metadata for classes, methods, and properties.</p>
<pre><code class="lang-plaintext">#[Route("/home")]
class HomeController {}
</code></pre>
<h2 id="heading-common-usages-of-php">Common Usages of PHP</h2>
<p>PHP is extensively used in various applications, including:</p>
<h3 id="heading-1-web-development">1. Web Development</h3>
<p>PHP powers a vast number of websites, from simple blogs to complex web applications like Facebook and Wikipedia.</p>
<h3 id="heading-2-content-management-systems-cms">2. Content Management Systems (CMS)</h3>
<p>Popular CMS platforms like WordPress, Joomla, and Drupal are built using PHP.</p>
<h3 id="heading-3-e-commerce-applications">3. E-commerce Applications</h3>
<p>PHP frameworks are widely used in platforms like Magento, WooCommerce, and OpenCart for e-commerce development.</p>
<h3 id="heading-4-api-development">4. API Development</h3>
<p>With frameworks like Laravel, PHP can be used to develop RESTful APIs and web services.</p>
<h3 id="heading-5-command-line-scripts">5. Command-Line Scripts</h3>
<p>PHP can be used for automation scripts, cron jobs, and backend data processing.</p>
<h3 id="heading-6-game-development">6. Game Development</h3>
<p>Though not as popular as other languages for gaming, PHP can handle backend logic for multiplayer games and server-side scripting.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>PHP 8 brings significant improvements that make it more efficient, readable, and performant. Whether you are developing web applications, APIs, or content management systems, PHP remains a powerful and relevant programming language in today’s tech world. By leveraging PHP 8’s new features, developers can write cleaner, faster, and more maintainable code.</p>
]]></content:encoded></item><item><title><![CDATA[Client-Side vs. Server-Side Scripting/Programming & Apache]]></title><description><![CDATA[Introduction
In web development, scripting and programming occur on both the client-side and server-side, each playing a crucial role in delivering dynamic and interactive web experiences. Apache, one of the most widely used web servers, is essential...]]></description><link>https://notes.shanto.dev/client-side-vs-server-side-scriptingprogramming-and-apache</link><guid isPermaLink="true">https://notes.shanto.dev/client-side-vs-server-side-scriptingprogramming-and-apache</guid><category><![CDATA[PHP]]></category><category><![CDATA[php8]]></category><category><![CDATA[Laravel]]></category><category><![CDATA[Server side rendering]]></category><category><![CDATA[server side]]></category><category><![CDATA[Client-side rendering]]></category><category><![CDATA[client side validation]]></category><category><![CDATA[client-side]]></category><category><![CDATA[client-side storage]]></category><category><![CDATA[Client-Side Security]]></category><category><![CDATA[Scripting]]></category><category><![CDATA[scripting languages]]></category><category><![CDATA[Scripting vs Programming Languages]]></category><category><![CDATA[scripting language]]></category><category><![CDATA[apache]]></category><dc:creator><![CDATA[Jahid Hasan Shanto]]></dc:creator><pubDate>Sun, 16 Mar 2025 03:30:48 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>In web development, scripting and programming occur on both the client-side and server-side, each playing a crucial role in delivering dynamic and interactive web experiences. Apache, one of the most widely used web servers, is essential for handling server-side requests efficiently. This blog explores the differences between client-side and server-side scripting, their respective technologies, and how Apache contributes to the web development ecosystem.</p>
<hr />
<h2 id="heading-client-side-scriptingprogramming">Client-Side Scripting/Programming</h2>
<p>Client-side scripting refers to code execution on the user’s browser rather than on the web server. This allows for interactive elements, faster processing, and a dynamic user experience without requiring frequent communication with the server.</p>
<h3 id="heading-key-features">Key Features:</h3>
<ul>
<li><p>Executes in the user’s browser.</p>
</li>
<li><p>Reduces server load by handling tasks locally.</p>
</li>
<li><p>Enhances user experience with interactive features.</p>
</li>
<li><p>Limited access to system resources for security reasons.</p>
</li>
</ul>
<h3 id="heading-common-client-side-technologies">Common Client-Side Technologies:</h3>
<ul>
<li><p><strong>HTML</strong>: The structure of web pages.</p>
</li>
<li><p><strong>CSS</strong>: Styling and layout.</p>
</li>
<li><p><strong>JavaScript</strong>: The main scripting language for interactivity.</p>
</li>
<li><p><strong>Frameworks &amp; Libraries</strong>: React.js, Vue.js, Angular.js, jQuery.</p>
</li>
<li><p><strong>Web APIs</strong>: Fetch API, WebSockets, Local Storage.</p>
</li>
</ul>
<h3 id="heading-examples-of-client-side-scripts">Examples of Client-Side Scripts:</h3>
<ul>
<li><p>Form validation before submission.</p>
</li>
<li><p>Animations and effects (e.g., sliders, modals, tooltips).</p>
</li>
<li><p>Asynchronous content loading (AJAX, Fetch API).</p>
</li>
<li><p>Handling user interactions without reloading the page.</p>
</li>
</ul>
<hr />
<h2 id="heading-server-side-scriptingprogramming">Server-Side Scripting/Programming</h2>
<p>Server-side scripting refers to code that runs on the web server to process requests, manage databases, authenticate users, and generate dynamic web content before sending it to the client’s browser.</p>
<h3 id="heading-key-features-1">Key Features:</h3>
<ul>
<li><p>Executes on the web server.</p>
</li>
<li><p>Handles business logic, database interactions, and security.</p>
</li>
<li><p>Provides a secure environment for sensitive data processing.</p>
</li>
<li><p>Requires communication between the client and server for updates.</p>
</li>
</ul>
<h3 id="heading-common-server-side-technologies">Common Server-Side Technologies:</h3>
<ul>
<li><p><strong>PHP</strong>: A popular language for dynamic content (WordPress, Laravel).</p>
</li>
<li><p><strong>Node.js</strong>: JavaScript runtime for server-side execution.</p>
</li>
<li><p><strong>Python</strong>: Used with Django and Flask for web applications.</p>
</li>
<li><p><strong>Ruby on Rails</strong>: A framework for rapid application development.</p>
</li>
<li><p><strong>Java (Spring Boot)</strong>: A robust backend solution.</p>
</li>
<li><p><strong>C# (ASP.NET Core)</strong>: A high-performance framework for web applications.</p>
</li>
</ul>
<h3 id="heading-examples-of-server-side-scripts">Examples of Server-Side Scripts:</h3>
<ul>
<li><p>User authentication and session management.</p>
</li>
<li><p>Handling database operations (CRUD operations: Create, Read, Update, Delete).</p>
</li>
<li><p>Generating dynamic content (e.g., personalized dashboards, email templates).</p>
</li>
<li><p>Processing payments in e-commerce applications.</p>
</li>
</ul>
<hr />
<h2 id="heading-apache-the-backbone-of-server-side-scripting">Apache: The Backbone of Server-Side Scripting</h2>
<p>Apache HTTP Server, commonly known as Apache, is an open-source web server that efficiently handles HTTP requests and serves web applications. It is a core component in server-side scripting and works seamlessly with PHP, Python, and other backend technologies.</p>
<h3 id="heading-key-features-of-apache">Key Features of Apache:</h3>
<ul>
<li><p><strong>Cross-Platform Compatibility</strong>: Supports Windows, Linux, and macOS.</p>
</li>
<li><p><strong>Modular Architecture</strong>: Extendable with modules like mod_rewrite (URL redirection) and mod_ssl (secure connections).</p>
</li>
<li><p><strong>Virtual Hosting</strong>: Hosts multiple websites on a single server.</p>
</li>
<li><p><strong>Security Features</strong>: Supports SSL/TLS encryption, access control, and request filtering.</p>
</li>
</ul>
<h3 id="heading-how-apache-works-with-server-side-programming">How Apache Works with Server-Side Programming:</h3>
<ol>
<li><p>A user’s browser sends an HTTP request to the web server.</p>
</li>
<li><p>Apache processes the request and forwards it to a server-side script (e.g., PHP, Python, Node.js).</p>
</li>
<li><p>The script interacts with the database and processes the request.</p>
</li>
<li><p>Apache sends the dynamically generated response (HTML, JSON, etc.) back to the browser.</p>
</li>
</ol>
<h3 id="heading-setting-up-apache-with-php">Setting Up Apache with PHP:</h3>
<p>For Ubuntu/Linux:</p>
<pre><code class="lang-plaintext">sudo apt update
sudo apt install apache2 php libapache2-mod-php
</code></pre>
<p>For Windows (Using XAMPP):</p>
<ul>
<li><p>Download and install XAMPP.</p>
</li>
<li><p>Start Apache and MySQL services.</p>
</li>
<li><p>Place PHP files in the <code>htdocs</code> directory.</p>
</li>
</ul>
<p>To test PHP installation:</p>
<pre><code class="lang-plaintext">&lt;?php
phpinfo();
?&gt;
</code></pre>
<p>Save this as <code>info.php</code> and access it via <code>http://localhost/info.php</code>.</p>
<hr />
<h2 id="heading-client-side-vs-server-side-key-differences">Client-Side vs. Server-Side: Key Differences</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>Client-Side Scripting</td><td>Server-Side Scripting</td></tr>
</thead>
<tbody>
<tr>
<td>Execution</td><td>Browser (User’s device)</td><td>Web server</td></tr>
<tr>
<td>Speed</td><td>Faster, no server interaction required</td><td>Slower, requires server processing</td></tr>
<tr>
<td>Security</td><td>Less secure, exposed to users</td><td>More secure, runs on the server</td></tr>
<tr>
<td>Languages</td><td>HTML, CSS, JavaScript</td><td>PHP, Python, Node.js, Java, C#</td></tr>
<tr>
<td>Use Cases</td><td>UI enhancements, animations, form validation</td><td>Authentication, database interactions, dynamic content</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>Client-side and server-side scripting are both essential for building interactive and dynamic web applications. While client-side scripting enhances user experience, server-side scripting handles backend logic, security, and database operations. Apache serves as a crucial component in server-side development, efficiently managing HTTP requests and processing scripts. Understanding these concepts helps developers build scalable, secure, and high-performing web applications.</p>
<p>Do you prefer working on client-side or server-side development? Share your thoughts in the comments below!</p>
]]></content:encoded></item><item><title><![CDATA[Apache and PHP: A Powerful Combination for Web Development]]></title><description><![CDATA[Introduction
Apache and PHP are two of the most widely used technologies in web development. Apache serves as a powerful and flexible web server, while PHP is a popular server-side scripting language designed for creating dynamic web applications. Wh...]]></description><link>https://notes.shanto.dev/apache-and-php-a-powerful-combination-for-web-development</link><guid isPermaLink="true">https://notes.shanto.dev/apache-and-php-a-powerful-combination-for-web-development</guid><category><![CDATA[PHP]]></category><category><![CDATA[apache]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Jahid Hasan Shanto]]></dc:creator><pubDate>Sat, 15 Mar 2025 03:30:18 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Apache and PHP are two of the most widely used technologies in web development. Apache serves as a powerful and flexible web server, while PHP is a popular server-side scripting language designed for creating dynamic web applications. When combined, they provide a stable, secure, and scalable solution for hosting and running web applications. This blog will explore Apache and PHP in detail, including their functions, setup, configurations, and best practices.</p>
<hr />
<h2 id="heading-what-is-apache">What is Apache?</h2>
<p>Apache HTTP Server, commonly known as Apache, is an open-source web server developed by the Apache Software Foundation. It is one of the most popular web servers, used to serve websites and web applications across the internet.</p>
<h3 id="heading-key-features-of-apache">Key Features of Apache:</h3>
<ul>
<li><p><strong>Cross-Platform Compatibility</strong>: Runs on Windows, Linux, and macOS.</p>
</li>
<li><p><strong>Modular Architecture</strong>: Supports modules for enhanced functionality (e.g., mod_rewrite, mod_ssl).</p>
</li>
<li><p><strong>Scalability</strong>: Handles multiple concurrent connections efficiently.</p>
</li>
<li><p><strong>Security Features</strong>: Supports SSL/TLS encryption and access control.</p>
</li>
<li><p><strong>Customization</strong>: Configuration files (.htaccess, httpd.conf) allow fine-tuning.</p>
</li>
</ul>
<h3 id="heading-how-apache-works">How Apache Works:</h3>
<ol>
<li><p>A client (browser) sends an HTTP request to the server.</p>
</li>
<li><p>Apache processes the request and determines the appropriate response.</p>
</li>
<li><p>It serves static content (HTML, CSS, images) or passes the request to a scripting language (e.g., PHP) for dynamic processing.</p>
</li>
<li><p>The processed content is sent back to the client.</p>
</li>
</ol>
<hr />
<h2 id="heading-what-is-php">What is PHP?</h2>
<p>PHP (Hypertext Preprocessor) is a widely-used open-source server-side scripting language designed for web development. It is embedded in HTML and interacts with databases, making it an excellent choice for dynamic web applications.</p>
<h3 id="heading-key-features-of-php">Key Features of PHP:</h3>
<ul>
<li><p><strong>Ease of Use</strong>: Simple syntax for beginners.</p>
</li>
<li><p><strong>Database Support</strong>: Works with MySQL, PostgreSQL, MongoDB, and more.</p>
</li>
<li><p><strong>Cross-Platform</strong>: Runs on various operating systems.</p>
</li>
<li><p><strong>Integration with Apache</strong>: Works seamlessly with Apache web server.</p>
</li>
<li><p><strong>Security Features</strong>: Supports encryption and secure user authentication.</p>
</li>
</ul>
<h3 id="heading-common-uses-of-php">Common Uses of PHP:</h3>
<ul>
<li><p>Dynamic websites and web applications.</p>
</li>
<li><p>Content management systems (CMS) like WordPress.</p>
</li>
<li><p>E-commerce platforms.</p>
</li>
<li><p>API development.</p>
</li>
</ul>
<hr />
<h2 id="heading-lamp-wamp-and-mamp">LAMP, WAMP, and MAMP</h2>
<h3 id="heading-lamp-linux-apache-mysql-php">LAMP (Linux, Apache, MySQL, PHP)</h3>
<p>LAMP is a popular open-source software stack used for web application development. It consists of:</p>
<ul>
<li><p><strong>Linux</strong>: The operating system.</p>
</li>
<li><p><strong>Apache</strong>: The web server.</p>
</li>
<li><p><strong>MySQL</strong>: The database management system.</p>
</li>
<li><p><strong>PHP</strong>: The server-side scripting language.</p>
</li>
</ul>
<p>LAMP is widely used for developing and deploying scalable web applications.</p>
<h3 id="heading-wamp-windows-apache-mysql-php">WAMP (Windows, Apache, MySQL, PHP)</h3>
<p>WAMP is the Windows-based alternative to LAMP. It includes:</p>
<ul>
<li><p><strong>Windows</strong>: The operating system.</p>
</li>
<li><p><strong>Apache</strong>: The web server.</p>
</li>
<li><p><strong>MySQL</strong>: The database management system.</p>
</li>
<li><p><strong>PHP</strong>: The server-side scripting language.</p>
</li>
</ul>
<p>WAMP is commonly used by developers who work on Windows systems for local development and testing.</p>
<h3 id="heading-mamp-mac-apache-mysql-php">MAMP (Mac, Apache, MySQL, PHP)</h3>
<p>MAMP is designed for macOS users and includes:</p>
<ul>
<li><p><strong>MacOS</strong>: The operating system.</p>
</li>
<li><p><strong>Apache</strong>: The web server.</p>
</li>
<li><p><strong>MySQL</strong>: The database management system.</p>
</li>
<li><p><strong>PHP</strong>: The server-side scripting language.</p>
</li>
</ul>
<p>MAMP provides an easy-to-use environment for macOS developers to build and test PHP applications locally.</p>
<hr />
<h2 id="heading-setting-up-apache-and-php">Setting Up Apache and PHP</h2>
<h3 id="heading-step-1-install-apache">Step 1: Install Apache</h3>
<p>On Linux (Ubuntu/Debian):</p>
<pre><code class="lang-plaintext">sudo apt update
sudo apt install apache2
</code></pre>
<p>On Windows:</p>
<ul>
<li><p>Download Apache from the official site.</p>
</li>
<li><p>Install and configure it using the httpd.conf file.</p>
</li>
</ul>
<h3 id="heading-step-2-install-php">Step 2: Install PHP</h3>
<p>On Linux:</p>
<pre><code class="lang-plaintext">sudo apt install php libapache2-mod-php
</code></pre>
<p>On Windows:</p>
<ul>
<li><p>Download PHP and extract it.</p>
</li>
<li><p>Configure Apache to process PHP files by editing the httpd.conf file.</p>
</li>
</ul>
<h3 id="heading-step-3-restart-apache">Step 3: Restart Apache</h3>
<pre><code class="lang-plaintext">sudo systemctl restart apache2
</code></pre>
<h3 id="heading-step-4-test-php-installation">Step 4: Test PHP Installation</h3>
<p>Create a test file in <code>/var/www/html/</code> (Linux) or <code>htdocs</code> (Windows) directory:</p>
<pre><code class="lang-plaintext">&lt;?php
phpinfo();
?&gt;
</code></pre>
<p>Save it as <code>info.php</code> and access it via <code>http://localhost/info.php</code>.</p>
<hr />
<h2 id="heading-configuring-apache-and-php-for-better-performance">Configuring Apache and PHP for Better Performance</h2>
<h3 id="heading-apache-performance-optimization">Apache Performance Optimization:</h3>
<ul>
<li><p><strong>Enable Caching</strong>: Use <code>mod_cache</code> to store frequently accessed content.</p>
</li>
<li><p><strong>Enable Compression</strong>: Use <code>mod_deflate</code> or <code>mod_gzip</code> for faster content delivery.</p>
</li>
<li><p><strong>Optimize .htaccess Usage</strong>: Reduce processing overhead by minimizing .htaccess rules.</p>
</li>
<li><p><strong>Use Virtual Hosts</strong>: Host multiple sites efficiently on a single server.</p>
</li>
</ul>
<h3 id="heading-php-performance-optimization">PHP Performance Optimization:</h3>
<ul>
<li><p><strong>Enable OPcache</strong>: Stores precompiled script bytecode in memory for faster execution.</p>
</li>
<li><p><strong>Use FastCGI</strong>: Improves PHP performance by handling multiple requests efficiently.</p>
</li>
<li><p><strong>Reduce Unnecessary Extensions</strong>: Disable unused PHP extensions to save resources.</p>
</li>
<li><p><strong>Optimize Database Queries</strong>: Use prepared statements and indexing for faster data retrieval.</p>
</li>
</ul>
<hr />
<h2 id="heading-security-best-practices-for-apache-and-php">Security Best Practices for Apache and PHP</h2>
<h3 id="heading-apache-security">Apache Security:</h3>
<ul>
<li><p><strong>Disable Directory Listing</strong>: Prevent unauthorized users from viewing directory contents.</p>
<pre><code class="lang-plaintext">  Options -Indexes
</code></pre>
</li>
<li><p><strong>Restrict Access to Sensitive Files</strong>: Block access to .htaccess and configuration files.</p>
<pre><code class="lang-plaintext">  &lt;Files ".htaccess"&gt;
      Order Allow,Deny
      Deny from all
  &lt;/Files&gt;
</code></pre>
</li>
<li><p><strong>Enable HTTPS</strong>: Use SSL/TLS for encrypted connections.</p>
</li>
</ul>
<h3 id="heading-php-security">PHP Security:</h3>
<ul>
<li><p><strong>Disable Dangerous Functions</strong>: Restrict potentially harmful functions like <code>exec()</code>, <code>system()</code>, etc.</p>
<pre><code class="lang-plaintext">  disable_functions = exec,system,shell_exec
</code></pre>
</li>
<li><p><strong>Use Input Validation</strong>: Prevent SQL injection and XSS attacks.</p>
</li>
<li><p><strong>Enable Error Logging</strong>: Disable displaying errors in production and log them instead.</p>
<pre><code class="lang-plaintext">  display_errors = Off
  log_errors = On
</code></pre>
</li>
</ul>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>Apache and PHP together form a powerful foundation for web development, providing a stable, secure, and scalable environment. Apache efficiently serves web content, while PHP enables dynamic, database-driven applications. By optimizing configurations, improving security, and following best practices, developers can create high-performing, secure web applications.</p>
<p>Are you using Apache and PHP for your projects? Share your experiences and insights in the comments below!</p>
]]></content:encoded></item><item><title><![CDATA[Web Applications and Server-Side Programming]]></title><description><![CDATA[Introduction
Web applications have become an integral part of the digital landscape, enabling businesses, organizations, and individuals to offer services online. Behind every seamless web experience lies a robust server-side programming mechanism th...]]></description><link>https://notes.shanto.dev/web-applications-and-server-side-programming</link><guid isPermaLink="true">https://notes.shanto.dev/web-applications-and-server-side-programming</guid><category><![CDATA[PHP]]></category><category><![CDATA[webapplication]]></category><category><![CDATA[#Server-Side Scripting with PHP: Building Dynamic Websites]]></category><dc:creator><![CDATA[Jahid Hasan Shanto]]></dc:creator><pubDate>Fri, 14 Mar 2025 03:30:28 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Web applications have become an integral part of the digital landscape, enabling businesses, organizations, and individuals to offer services online. Behind every seamless web experience lies a robust server-side programming mechanism that processes requests, manages data, and ensures smooth communication between clients and servers. This blog explores web applications and server-side programming with key insights into their components, technologies, and best practices.</p>
<hr />
<h2 id="heading-what-is-a-web-application">What is a Web Application?</h2>
<p>A web application is a software program that runs in a web browser and interacts with users through the internet. Unlike traditional desktop applications, web applications do not require installation and can be accessed from any device with an internet connection.</p>
<h3 id="heading-key-characteristics">Key Characteristics:</h3>
<ul>
<li><p><strong>Cross-Platform Compatibility</strong>: Accessible on various devices (PCs, tablets, smartphones).</p>
</li>
<li><p><strong>Scalability</strong>: Can handle a growing number of users and requests.</p>
</li>
<li><p><strong>Centralized Updates</strong>: No need for manual updates on user devices.</p>
</li>
<li><p><strong>Interactivity</strong>: Dynamic user experiences using modern front-end technologies.</p>
</li>
</ul>
<p>Examples: Gmail, Facebook, Netflix, Twitter, and online banking platforms.</p>
<hr />
<h2 id="heading-understanding-server-side-programming">Understanding Server-Side Programming</h2>
<p>Server-side programming refers to the code execution on the web server rather than the user’s browser. It is responsible for processing requests, interacting with databases, managing authentication, and generating dynamic content.</p>
<h3 id="heading-core-responsibilities">Core Responsibilities:</h3>
<ul>
<li><p>Handling HTTP requests and responses.</p>
</li>
<li><p>Managing authentication and user sessions.</p>
</li>
<li><p>Performing CRUD (Create, Read, Update, Delete) operations with databases.</p>
</li>
<li><p>Implementing business logic and validation.</p>
</li>
<li><p>Securing data and preventing unauthorized access.</p>
</li>
</ul>
<h3 id="heading-popular-server-side-languages-and-frameworks">Popular Server-Side Languages and Frameworks:</h3>
<ul>
<li><p><strong>JavaScript (Node.js)</strong>: Fast, event-driven runtime with frameworks like Express.js.</p>
</li>
<li><p><strong>Python (Django, Flask)</strong>: Elegant syntax with a focus on rapid development.</p>
</li>
<li><p><strong>PHP (Laravel, CodeIgniter)</strong>: Widely used for content management systems.</p>
</li>
<li><p><strong>Ruby (Ruby on Rails)</strong>: Convention over configuration for rapid development.</p>
</li>
<li><p><strong>Java (Spring Boot)</strong>: Enterprise-level performance and security.</p>
</li>
<li><p><strong>C# (ASP.NET Core)</strong>: Microsoft-backed, high-performance framework.</p>
</li>
</ul>
<hr />
<h2 id="heading-how-web-applications-work-the-client-server-model">How Web Applications Work: The Client-Server Model</h2>
<ol>
<li><p><strong>Client Request</strong>: A user interacts with a web page, sending a request to the server.</p>
</li>
<li><p><strong>Server Processing</strong>: The server-side script processes the request, interacts with the database, and prepares a response.</p>
</li>
<li><p><strong>Response to Client</strong>: The server sends the response (HTML, JSON, XML) back to the client’s browser.</p>
</li>
<li><p><strong>Rendering &amp; Display</strong>: The browser interprets the response and displays the updated content to the user.</p>
</li>
</ol>
<hr />
<h2 id="heading-databases-in-server-side-programming">Databases in Server-Side Programming</h2>
<p>Most web applications rely on databases to store, retrieve, and manipulate data efficiently.</p>
<h3 id="heading-types-of-databases">Types of Databases:</h3>
<ul>
<li><p><strong>Relational Databases (SQL-based)</strong>:</p>
<ul>
<li><p>MySQL</p>
</li>
<li><p>PostgreSQL</p>
</li>
<li><p>Microsoft SQL Server</p>
</li>
</ul>
</li>
<li><p><strong>NoSQL Databases (Schema-less)</strong>:</p>
<ul>
<li><p>MongoDB</p>
</li>
<li><p>Firebase</p>
</li>
<li><p>CouchDB</p>
</li>
</ul>
</li>
</ul>
<hr />
<h2 id="heading-security-best-practices-in-server-side-programming">Security Best Practices in Server-Side Programming</h2>
<p>Security is crucial to prevent cyber threats and data breaches. Implement these best practices:</p>
<ul>
<li><p><strong>Use HTTPS</strong>: Encrypt communication between clients and servers.</p>
</li>
<li><p><strong>Sanitize User Input</strong>: Prevent SQL injection and cross-site scripting (XSS) attacks.</p>
</li>
<li><p><strong>Use Authentication &amp; Authorization</strong>: Implement secure login systems (JWT, OAuth, or session-based authentication).</p>
</li>
<li><p><strong>Validate Requests</strong>: Ensure proper data validation to prevent API abuse.</p>
</li>
<li><p><strong>Implement Rate Limiting</strong>: Protect against denial-of-service (DoS) attacks.</p>
</li>
</ul>
<hr />
<h2 id="heading-scalability-and-performance-optimization">Scalability and Performance Optimization</h2>
<p>For high-traffic applications, optimizing performance is critical:</p>
<ul>
<li><p><strong>Load Balancing</strong>: Distribute traffic across multiple servers.</p>
</li>
<li><p><strong>Caching</strong>: Use Redis or Memcached to reduce database queries.</p>
</li>
<li><p><strong>Asynchronous Processing</strong>: Handle background tasks with job queues (Celery, BullMQ).</p>
</li>
<li><p><strong>Optimize Database Queries</strong>: Indexing and query optimization for faster execution.</p>
</li>
<li><p><strong>Content Delivery Networks (CDN)</strong>: Cache static assets closer to users.</p>
</li>
</ul>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>Web applications are a powerful tool for delivering online services, and server-side programming plays a crucial role in ensuring efficiency, security, and scalability. Whether you’re developing a small business website or a large-scale enterprise solution, understanding backend technologies and best practices is key to building a robust and secure web application.</p>
<p>Are you currently working on a web application? Share your experiences and challenges in the comments below!</p>
]]></content:encoded></item><item><title><![CDATA[What Is PHP?]]></title><description><![CDATA[PHP (Hypertext Preprocessor) is a widely-used, open-source server-side scripting language primarily designed for web development. It is used to create dynamic and interactive websites and web applications. PHP is especially known for its ability to g...]]></description><link>https://notes.shanto.dev/what-is-php</link><guid isPermaLink="true">https://notes.shanto.dev/what-is-php</guid><category><![CDATA[PHP]]></category><category><![CDATA[Hello World]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Jahid Hasan Shanto]]></dc:creator><pubDate>Wed, 05 Mar 2025 03:58:15 GMT</pubDate><content:encoded><![CDATA[<p><strong>PHP</strong> (Hypertext Preprocessor) is a widely-used, open-source server-side scripting language primarily designed for web development. It is used to create dynamic and interactive websites and web applications. PHP is especially known for its ability to generate HTML content, interact with databases, and handle forms, sessions, and cookies.</p>
<h3 id="heading-key-features-of-php">Key Features of PHP:</h3>
<ol>
<li><p><strong>Server-Side Scripting</strong>: PHP code is executed on the server, and the result is sent to the client (the user’s browser) as plain HTML. This allows developers to create dynamic content that can change based on user interactions, database queries, or other inputs.</p>
</li>
<li><p><strong>Open Source</strong>: PHP is free to use, and its source code is open for modification. This has contributed to its widespread adoption and the growth of a large, supportive community.</p>
</li>
<li><p><strong>Database Integration</strong>: PHP works seamlessly with various databases, particularly MySQL, to store and retrieve data for web applications. It allows for efficient handling of data-driven websites, such as content management systems (CMS), e-commerce sites, and social platforms.</p>
</li>
<li><p><strong>Cross-Platform</strong>: PHP is platform-independent, which means it can run on multiple operating systems, including Windows, Linux, and macOS. It also supports integration with various web servers like Apache and Nginx.</p>
</li>
<li><p><strong>Extensive Libraries and Frameworks</strong>: PHP has many frameworks (like Laravel, Symfony, CodeIgniter) and libraries that make development faster and more efficient. These frameworks offer pre-built modules and features that help developers create robust web applications more easily.</p>
</li>
<li><p><strong>Dynamic Web Pages</strong>: PHP can generate dynamic content based on variables and conditions. For example, it can display different content based on the time of day, user input, or database information.</p>
</li>
<li><p><strong>Forms and User Input Handling</strong>: PHP is commonly used to process form data submitted by users on websites. It can handle form submissions, validate input, and even send email notifications.</p>
</li>
<li><p><strong>Session Management</strong>: PHP allows you to track users across multiple pages (session management), which is essential for features like user logins, shopping carts, and personalized content.</p>
</li>
<li><p><strong>Security</strong>: PHP provides a variety of tools and functions for web security, such as input sanitization and encryption, which help protect against attacks like SQL injection, cross-site scripting (XSS), and cross-site request forgery (CSRF).</p>
</li>
</ol>
<h3 id="heading-common-uses-of-php">Common Uses of PHP:</h3>
<ul>
<li><p><strong>Web Development</strong>: PHP is widely used to build websites, blogs, and content management systems (e.g., WordPress, Joomla, Drupal).</p>
</li>
<li><p><strong>E-commerce</strong>: Many e-commerce websites use PHP (e.g., Magento, WooCommerce) to handle product listings, shopping carts, and payment processing.</p>
</li>
<li><p><strong>Web Applications</strong>: PHP powers many web applications, including social media platforms, customer relationship management (CRM) systems, and enterprise applications.</p>
</li>
<li><p><strong>API Integration</strong>: PHP can be used to build or consume APIs (Application Programming Interfaces), making it ideal for integrating with third-party services or exposing your own services to other applications.</p>
</li>
</ul>
<h3 id="heading-basic-example-of-php-code">Basic Example of PHP Code:</h3>
<p>Here’s a simple PHP script that outputs "Hello, World!" on a web page:</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
<span class="hljs-keyword">echo</span> <span class="hljs-string">"Hello, World!"</span>;
<span class="hljs-meta">?&gt;</span>
</code></pre>
<h3 id="heading-how-php-works">How PHP Works:</h3>
<ol>
<li><p><strong>Write PHP Code</strong>: You write PHP scripts, which are usually embedded inside HTML files. PHP code starts with <code>&lt;?php</code> and ends with <code>?&gt;</code>.</p>
</li>
<li><p><strong>Request to Server</strong>: When a user requests a page, the server processes the PHP code.</p>
</li>
<li><p><strong>PHP Executes</strong>: The server executes the PHP code, which could include things like fetching data from a database, performing calculations, or generating dynamic content.</p>
</li>
<li><p><strong>Output to Browser</strong>: After the PHP code is executed, the server sends the resulting HTML (or other content) to the user's browser to display.</p>
</li>
</ol>
<h3 id="heading-why-use-php">Why Use PHP?</h3>
<ul>
<li><p><strong>Popularity</strong>: PHP powers over 75% of websites on the internet, including major platforms like Facebook, Wikipedia, and WordPress.</p>
</li>
<li><p><strong>Easy to Learn</strong>: PHP is relatively easy to pick up, especially for beginners in web development.</p>
</li>
<li><p><strong>Cost-Effective</strong>: Since PHP is open-source, there are no licensing fees, making it a cost-effective solution for web development.</p>
</li>
<li><p><strong>Community Support</strong>: PHP has a large and active community that contributes to frameworks, tutorials, libraries, and troubleshooting.</p>
</li>
</ul>
<p>In summary, <strong>PHP</strong> is a versatile, powerful, and well-supported programming language for building dynamic websites and web applications. It’s essential for server-side scripting, offering capabilities that are critical for modern web development.</p>
]]></content:encoded></item><item><title><![CDATA[Steps to Initialize a GitHub Repository]]></title><description><![CDATA[1. Create a GitHub Repository:

Go to GitHub.

Log in to your account (or sign up if you don’t have one).

In the upper-right corner, click the "+" icon and select New repository.

Fill in the repository details:

Repository Name: Choose a name for y...]]></description><link>https://notes.shanto.dev/steps-to-initialize-a-github-repository</link><guid isPermaLink="true">https://notes.shanto.dev/steps-to-initialize-a-github-repository</guid><category><![CDATA[GitHub]]></category><category><![CDATA[repository]]></category><category><![CDATA[repo]]></category><category><![CDATA[website]]></category><dc:creator><![CDATA[Jahid Hasan Shanto]]></dc:creator><pubDate>Tue, 04 Mar 2025 07:31:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1741070063484/d83a8fe2-8d33-4818-827d-2e8ab5e268f3.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h4 id="heading-1-create-a-github-repository"><strong>1. Create a GitHub Repository:</strong></h4>
<ul>
<li><p>Go to <a target="_blank" href="https://github.com">GitHub</a>.</p>
</li>
<li><p>Log in to your account (or sign up if you don’t have one).</p>
</li>
<li><p>In the upper-right corner, click the "+" icon and select <strong>New repository</strong>.</p>
</li>
<li><p>Fill in the repository details:</p>
<ul>
<li><p><strong>Repository Name</strong>: Choose a name for your repository.</p>
</li>
<li><p><strong>Description</strong> (optional): A short description of your repository.</p>
</li>
<li><p><strong>Visibility</strong>: Choose either <strong>Public</strong> or <strong>Private</strong> based on your needs.</p>
</li>
<li><p>Optionally, initialize with a README, <code>.gitignore</code>, or choose a license.</p>
</li>
</ul>
</li>
<li><p>Click <strong>Create repository</strong>.</p>
</li>
</ul>
<h4 id="heading-2-set-up-git-locally"><strong>2. Set Up Git Locally:</strong></h4>
<p>If you haven’t already, you need to set up Git on your local machine.</p>
<ul>
<li><p><strong>Install Git</strong>: <a target="_blank" href="https://git-scm.com/">Download and install Git</a> for your operating system.</p>
</li>
<li><p><strong>Set up Git</strong> (if you haven't already):</p>
<pre><code class="lang-plaintext">  git config --global user.name "Your Name"
  git config --global user.email "your_email@example.com"
</code></pre>
</li>
</ul>
<h4 id="heading-3-initialize-a-local-repository"><strong>3. Initialize a Local Repository:</strong></h4>
<p>If your project is not already a Git repository, you need to initialize it.</p>
<ul>
<li><p>Navigate to your project folder:</p>
<pre><code class="lang-plaintext">  cd path/to/your/project
</code></pre>
</li>
<li><p>Initialize the local repository:</p>
<pre><code class="lang-plaintext">  git init
</code></pre>
</li>
</ul>
<h4 id="heading-4-add-files-to-git"><strong>4. Add Files to Git:</strong></h4>
<ul>
<li><p>Add all your files to the staging area:</p>
<pre><code class="lang-plaintext">  git add .
</code></pre>
</li>
<li><p>Commit your files:</p>
<pre><code class="lang-plaintext">  git commit -m "Initial commit"
</code></pre>
</li>
</ul>
<h4 id="heading-5-link-your-local-repository-to-github"><strong>5. Link Your Local Repository to GitHub:</strong></h4>
<ul>
<li><p>Copy the URL of your GitHub repository (it should look like <code>https://github.com/username/repository-name.git</code>).</p>
</li>
<li><p>Add the remote origin to your local Git repository:</p>
<pre><code class="lang-plaintext">  git remote add origin https://github.com/username/repository-name.git
</code></pre>
</li>
</ul>
<h4 id="heading-6-push-your-code-to-github"><strong>6. Push Your Code to GitHub:</strong></h4>
<ul>
<li><p>Push your changes to the GitHub repository:</p>
<pre><code class="lang-plaintext">  git push -u origin master
</code></pre>
<p>  If you created the repository with a README or other files already initialized, you might need to pull first:</p>
<pre><code class="lang-plaintext">  git pull origin master --allow-unrelated-histories
</code></pre>
<p>  Then push again:</p>
<pre><code class="lang-plaintext">  git push origin master
</code></pre>
</li>
</ul>
<h3 id="heading-done">Done! 🎉</h3>
<p>Your project should now be live on GitHub. You can refresh your GitHub repository page to see your files uploaded.</p>
<p>Let me know if you need more help!</p>
]]></content:encoded></item><item><title><![CDATA[How to setup a backend project with Node.js, Express, and CORS]]></title><description><![CDATA[Introduction
Welcome to Your Complete Guide for Building a Server-Side Environment with Node.js, Express, and CORS
This guide walks you through the foundational steps of setting up a server-side environment using Node.js and Express to create efficie...]]></description><link>https://notes.shanto.dev/how-to-setup-a-backend-project-with-nodejs-express-and-cors</link><guid isPermaLink="true">https://notes.shanto.dev/how-to-setup-a-backend-project-with-nodejs-express-and-cors</guid><category><![CDATA[Node.js]]></category><category><![CDATA[Express]]></category><category><![CDATA[CORS]]></category><dc:creator><![CDATA[Jahid Hasan Shanto]]></dc:creator><pubDate>Wed, 13 Nov 2024 16:57:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1731517007461/d4554b2b-1f0e-4064-b061-c4e9ecd70376.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction"><strong>Introduction</strong></h2>
<h3 id="heading-welcome-to-your-complete-guide-for-building-a-server-side-environment-with-nodejs-express-and-cors"><strong>Welcome to Your Complete Guide for Building a Server-Side Environment with Node.js, Express, and CORS</strong></h3>
<p>This guide walks you through the foundational steps of setting up a server-side environment using Node.js and Express to create efficient, scalable backend services. Whether you're aiming to build an API, a server-rendered app with Next.js, or simply looking to learn backend basics, this tutorial will cover the essential middleware and frameworks needed to get started.</p>
<p>You'll find detailed instructions on:</p>
<ol>
<li><p>Setting up your Node.js environment</p>
</li>
<li><p>Installing and configuring popular frameworks and middleware such as Express, CORS, and Nodemon</p>
</li>
<li><p>Creating a responsive API and handling requests from different origins</p>
</li>
<li><p>Tips for integrating frontend tools like Next.js for server-side rendering</p>
</li>
</ol>
<p>Each section is designed to guide you step-by-step with code snippets, best practices, and helpful explanations. By the end, you'll have a fully functional server and the foundational knowledge to expand further as your project grows.</p>
<h2 id="heading-prerequisites"><strong>Prerequisites</strong></h2>
<p>Here's an overview of creating a simple server using Node.js, Express, CORS, and Nodemon. This server setup is often used to handle requests, serve data, and act as a backend for web applications.</p>
<ol>
<li><p><strong>Node.js:</strong> Ensure you have Node.js installed (install from <a target="_blank" href="https://nodejs.org/en">Node.js</a> website).</p>
</li>
<li><p><strong>Express:</strong> A minimal and flexible Node.js web application framework.</p>
</li>
<li><p><strong>CORS:</strong> Middleware that enables cross-origin resource sharing.</p>
</li>
<li><p><strong>Nodemon:</strong> A utility that restarts the server automatically when files change.</p>
</li>
</ol>
<h2 id="heading-step-1-initialize-a-new-project"><strong>Step 1: Initialize a New Project</strong></h2>
<p>In your terminal, create a new directory and navigate to it. Initialize the project by running:</p>
<pre><code class="lang-bash">npm init -y
</code></pre>
<p>This command generates a <code>package.json</code> file to manage your project dependencies.</p>
<h2 id="heading-step-2-install-dependencies"><strong>Step 2: Install Dependencies</strong></h2>
<p>Install the required packages:</p>
<pre><code class="lang-bash">npm install express cors &amp;&amp; npm install --save-dev nodemon
</code></pre>
<ul>
<li><p><strong>express</strong>: For handling HTTP requests and responses.</p>
</li>
<li><p><strong>cors</strong>: To allow requests from other origins, which is important for frontend-backend communication.</p>
</li>
<li><p><strong>nodemon</strong>: To restart the server automatically when you save changes (useful for development).</p>
</li>
</ul>
<h2 id="heading-usage"><strong>Usage</strong></h2>
<p>After Prerequisites, use the following command to start the server:</p>
<p><code>npm start</code></p>
<h2 id="heading-examples"><strong>Examples</strong></h2>
<p>Here are some examples demonstrating the key functionalities:</p>
]]></content:encoded></item></channel></rss>