URL Handling

Back

Loading concept...

🏠 The Address Book of the Internet

A Story About Finding Your Way

Imagine you want to visit your friend’s house. You need their address, right? Something like:

123 Main Street, Apartment 4B, Funnytown, with a note saying “bring cookies”

On the internet, websites have addresses too! We call them URLs (Uniform Resource Locators). And just like a real address has parts (street, city, apartment), a URL has parts too!


🎯 What You’ll Learn

  1. URL Class — Your address decoder tool
  2. URL Parts — Breaking down internet addresses
  3. Query Strings — Special notes attached to addresses

📦 The URL Class: Your Magic Address Book

Think of Node.js’s URL class like a magic magnifying glass. You give it any internet address, and it breaks it apart so you can see every piece clearly!

Creating Your First URL

const myURL = new URL(
  'https://shop.example.com:8080/toys/cars?color=red&size=big#details'
);

That’s it! One line, and now you have a super-powered address you can explore.

What Makes This Special?

Without the URL class, you’d have to write lots of code to figure out:

  • Where does the website name end?
  • What’s that ? doing there?
  • What about the #?

The URL class does all this work for you! 🎉


🧩 URL Parts: The Building Blocks

Let’s break down our example address piece by piece. It’s like taking apart a LEGO house to see all the bricks!

https://shop.example.com:8080/toys/cars?color=red&size=big#details
graph TD A["Full URL"] --> B["Protocol: https"] A --> C["Host: shop.example.com"] A --> D["Port: 8080"] A --> E["Path: /toys/cars"] A --> F["Query: color=red&size=big"] A --> G["Hash: details"]

🔐 Protocol (The Delivery Method)

console.log(myURL.protocol);
// Output: 'https:'

What is it? How the message gets delivered.

  • https: = Super safe, locked delivery 🔒
  • http: = Regular delivery (not locked)

Real Life: Like choosing between a locked mailbox vs. open mailbox!


🏢 Host (The Building Name)

console.log(myURL.host);
// Output: 'shop.example.com:8080'

console.log(myURL.hostname);
// Output: 'shop.example.com'

What is it? The name of the building (website) you’re visiting.

  • host = Building name + room number
  • hostname = Just the building name

🚪 Port (The Door Number)

console.log(myURL.port);
// Output: '8080'

What is it? Which door to knock on.

Most websites use default doors:

  • https uses door 443 (you don’t need to type it)
  • http uses door 80

When you see :8080, it means “use a special door”!


🛤️ Pathname (The Room Inside)

console.log(myURL.pathname);
// Output: '/toys/cars'

What is it? Once you’re in the building, which room do you want?

Like walking through a store:

  1. Enter the store → /
  2. Go to toys section → /toys
  3. Find the cars area → /toys/cars

❓ Search/Query (Special Instructions)

console.log(myURL.search);
// Output: '?color=red&size=big'

What is it? Extra notes you’re sending. “I want the RED one, and make it BIG!”


🏷️ Hash (Jump to Spot)

console.log(myURL.hash);
// Output: '#details'

What is it? A bookmark inside the page. “Take me straight to the details section!”


🔍 Query Strings: The Special Notes

Query strings are like order forms. They tell the website exactly what you want!

The Format

?name=value&another=something
  • Starts with ?
  • Each instruction is name=value
  • Multiple instructions separated by &

Using searchParams (The Easy Way!)

Node.js gives you searchParams — a magical helper for reading and writing these notes.

Reading Values

const url = new URL(
  'https://shop.com/search?item=teddy&color=brown'
);

// Get one value
console.log(url.searchParams.get('item'));
// Output: 'teddy'

console.log(url.searchParams.get('color'));
// Output: 'brown'

Adding New Values

url.searchParams.append('size', 'large');

console.log(url.search);
// Output: '?item=teddy&color=brown&size=large'

Changing Values

url.searchParams.set('color', 'pink');

console.log(url.search);
// Output: '?item=teddy&color=pink&size=large'

Removing Values

url.searchParams.delete('size');

console.log(url.search);
// Output: '?item=teddy&color=pink'

Checking If Something Exists

console.log(url.searchParams.has('item'));
// Output: true

console.log(url.searchParams.has('price'));
// Output: false

🎪 Real-World Examples

Example 1: YouTube Video Link

const video = new URL(
  'https://youtube.com/watch?v=abc123&t=120'
);

console.log(video.hostname);
// 'youtube.com'

console.log(video.searchParams.get('v'));
// 'abc123' (the video ID)

console.log(video.searchParams.get('t'));
// '120' (start at 120 seconds)

Example 2: Building a Search URL

const search = new URL('https://google.com/search');

search.searchParams.set('q', 'cute puppies');
search.searchParams.set('safe', 'on');

console.log(search.href);
// 'https://google.com/search?q=cute+puppies&safe=on'

Notice how spaces become +! The URL class handles this automatically. 🪄


🏆 Quick Summary

Part Example What It Means
Protocol https: How to deliver safely
Hostname shop.com Which website
Port 8080 Which door
Pathname /toys/cars Which page
Search ?color=red Special requests
Hash #details Jump to section

💡 Pro Tips

Tip 1: Always Use new URL()

It catches mistakes and handles tricky characters for you!

// This works perfectly!
const url = new URL('https://site.com/hello world');
console.log(url.href);
// 'https://site.com/hello%20world'

Tip 2: Combine Base + Path

const base = 'https://api.example.com';
const full = new URL('/users/123', base);

console.log(full.href);
// 'https://api.example.com/users/123'

Tip 3: Loop Through All Query Params

const url = new URL(
  'https://shop.com?a=1&b=2&c=3'
);

for (const [key, value] of url.searchParams) {
  console.log(`${key} = ${value}`);
}
// a = 1
// b = 2
// c = 3

🎬 The End!

You now know how to:

✅ Create URLs with the URL class ✅ Read every part of a URL ✅ Work with query strings like a pro

URLs are everywhere on the internet. Now you can read them, build them, and change them with confidence!

You’re now a URL Detective! 🕵️‍♀️

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.