Node.js URL Module

Node.js URL Module

The URL module helps you work with URLs—parsing, formatting, and resolving URL strings.

It is a built-in module, so no installation is required.


Import URL Module


Or using ES Modules:



📌 1. Parse a URL

Using url.parse() (Legacy but widely used)


 

Output:

example.com
/products
mobile

📌 2. Modern Way: Using URL Class (Recommended)


 


📌 3. URL Properties

Property Description Example
hostname Domain name example.com
pathname Path /products
search Query string ?category=mobile
searchParams Key/value query params .get("category")
protocol URL protocol https:
port Port number 3000
hash Fragment #section1

📌 4. Working With Query Parameters

Get a query parameter


Add a parameter


Delete a parameter



📌 5. Format URL Back to String



📌 6. Example: Parse URL inside Node.js HTTP Server


 

Test URL:

http://localhost:3000/?name=Vipul

Output:

Hello, Vipul

🎯 Where URL Module is Used

✔ Creating APIs
✔ Reading query params
✔ Redirecting users
✔ Validating URLs
✔ Routing in servers
✔ Web scraping

You may also like...