Node.js: Code Outside the Browser / Building a Basic Server-Side Application (Without Framework)

Parsing Variables from URLs

🎯 Goal of This Note

Use the url module to parse the query string (like ?id=0) from the request URL, and use that data to build the product detail page dynamically.


πŸ”— Step 1: Parsing the URL

πŸ“¦ Recall the url module was imported earlier:

index.js

const url = require('url');

πŸ” Logging the Raw URL and Parsed Result

console.log(req.url);
console.log(url.parse(req.url, true));
  • 🌐 req.url gives the raw path, e.g : /product?id=0

  • πŸ” Passing true as the second argument to url.parse() tells it to parse the query string into an object as well (not just leave it as raw text).

πŸ“¦ What url.parse(req.url, true) Returns

The result is an object containing (among other things):

  • 🏷️ query β€” an object like { id: '0' } (parsed from the part after ?)

  • πŸ›£οΈ pathname β€” just the path portion, e.g. /product

πŸ’‘ The part of the URL after ? (like id=0) is called the query string.


🧩 Step 2: Extracting query and pathname with Destructuring

  • ✨ Instead of manually accessing properties, use object destructuring:

const { query, pathname } = url.parse(req.url, true);

πŸ” How This Works

  • ✨ This creates two new variables β€” query and pathname β€” automatically pulled from the matching property names in the parsed URL object.

  • πŸ›£οΈ pathname will be /product.

  • 🏷️ query will be an object like { id: '0' }.

πŸ”„ Update the Routing

  • πŸ› οΈ Replace the earlier req.url usage with pathname:

  • Change pathName to pathname everywhere in the code

//product page
if (pathname === '/product') {
  console.log(query); // e.g., { id: '0' }
  // ... build the product page here
}

πŸ” Step 3: Finding the Correct Product

  • πŸ“š Since dataObject is an array of products, and each product's position in the array matches its id, you can directly access the right product like this:

const product = dataObj[query.id];

πŸ” How This Works

  • 🏷️ query.id holds the ID value from the URL (e.g., '0', '1', '2', etc.).

  • πŸ“š This is used as an index into the dataObject array to retrieve the matching product.

  • πŸ₯¦ Example: if query.id is 2, it retrieves the third product in the array (index 2) β€” in this case, the broccoli.


πŸ› οΈ Step 4: Generating the Final Output

  • πŸ”„ Replace the /product page code with this:

} else if (pathname === '/product') {
  res.writeHead(200, { 'Content-type': 'text/html' });

  const product = dataObj[query.id];
  const output = replaceTemplate(tempProduct, product);

  res.end(output);

πŸ” How This Works

  • πŸ“„ tempProduct β€” the raw product detail template (loaded once at startup).

  • πŸ“¦ product β€” the specific product object found in Step 3.

  • πŸ”„ replaceTemplate() fills in all the placeholders (%PRODUCTNAME%, %IMAGE%, %PRICE%, etc.) with that product's actual data.

  • πŸ“€ The final HTML (output) is sent back as the response, with the correct Content-Type: text/html header.


πŸ§ͺ Step 5: Testing

  1. πŸ”„ Restart the server and reload the browser.

  2. πŸ–±οΈ Clicking a product link from the overview page (e.g., /product?id=0) now correctly displays that product's detail page. πŸŽ‰


βœ… Step 6: Verifying Everything Works Dynamically

  • 🌱 Testing a non-organic product confirms the organic badge correctly appears/disappears based on the JSON data β€” exactly as intended.

  • πŸ“„βœ¨ All content on both the overview and product pages is now fully dynamic, driven entirely by the data.json file.


πŸŽ‰ Project Status: Complete!

At this point, the Node Farm project is functionally complete:

  • 🏠 Overview page β€” lists all products dynamically from JSON.

  • πŸ“¦ Product detail page β€” shows individual product data based on the URL's id query parameter.

  • 🌐 API route (/api) β€” returns raw JSON data.

  • ❌ 404 handling β€” for undefined routes.

πŸ’‘ Note: Much of the more "confusing" logic (like destructuring, .map(), regex, template functions) is really just general JavaScript, not something unique to Node.js β€” reinforcing that learning Node.js also strengthens core JavaScript skills.


🎯 Key Takeaways

πŸ“Œ Concept

🎯 Purpose

πŸ”— url.parse(req.url, true)

Parses the request URL into a structured object; true also parses the query string into an object

🏷️ query

Object containing URL query parameters (e.g., { id: '0' })

πŸ›£οΈ pathname

The path portion of the URL, without the query string (e.g., /product)

🧩 Object destructuring (const { query, pathname } = ...)

Cleanly extracts specific properties into standalone variables

πŸ“¦ dataObject[query.id]

Uses the ID from the URL as an array index to find the matching product

πŸ”„ replaceTemplate(tempProduct, product)

Reuses the same function from the overview page to fill in the product detail template