Lesson 18 of 50 – URL Module
36% Completed
36%

Node.js URL Module

The Node.js URL module helps us create, read, and modify URLs. We can use it to access the protocol, hostname, pathname, query parameters, and other parts of a URL.

Remember: A URL is the address of a resource on the internet or on a local server. Node.js provides the built-in URL class for working with URLs.

1. What Is a URL?

URL stands for Uniform Resource Locator. It identifies the location of a resource and may include query parameters or a fragment.

Example: Parts of a URL
https://www.example.com:8080/products?id=25&category=books#details
Part Value Meaning
Protocol https: Communication protocol.
Hostname www.example.com Host or domain name.
Port 8080 Optional network port.
Pathname /products Path of the requested resource.
Query string ?id=25&category=books Additional key-value parameters.
Fragment #details Reference to a section or location.

2. Using the URL Class

Modern Node.js provides the global URL class. We can create a URL object by passing a valid absolute URL.

Example: Create a URL Object
const myURL = new URL(
    'https://www.example.com/products?id=25'
);

console.log(myURL.href);
console.log(myURL.hostname);
console.log(myURL.pathname);
Output:
https://www.example.com/products?id=25
www.example.com
/products

The URL object parses the address into separate properties that we can access in our program.

3. Important URL Properties

Property Purpose
href Returns the complete serialized URL.
protocol Returns the protocol, such as https:.
hostname Returns the hostname.
port Returns the explicit port, if present.
pathname Returns the path of the URL.
search Returns the query string, including ?.
hash Returns the fragment, including #.
origin Returns the scheme, hostname, and applicable port.
Example: Display URL Properties
const myURL = new URL(
    'https://example.com:8080/student/profile?id=10#info'
);

console.log('Protocol:', myURL.protocol);
console.log('Hostname:', myURL.hostname);
console.log('Port:', myURL.port);
console.log('Pathname:', myURL.pathname);
console.log('Search:', myURL.search);
console.log('Hash:', myURL.hash);
console.log('Origin:', myURL.origin);
Output:
Protocol: https:
Hostname: example.com
Port: 8080
Pathname: /student/profile
Search: ?id=10
Hash: #info
Origin: https://example.com:8080

4. Working with Query Parameters

Query parameters are values included after the question mark (?) in a URL. The searchParams property lets us read, add, update, and delete these parameters.

Example: Read Query Parameters
const myURL = new URL(
    'https://example.com/student?id=101&name=Rahul'
);

console.log(myURL.searchParams.get('id'));
console.log(myURL.searchParams.get('name'));
Output:
101
Rahul

The get() method returns the value associated with the requested parameter, or null if the parameter does not exist.

5. Add and Update Query Parameters

Example: Add a New Parameter
const myURL = new URL('https://example.com/courses');

myURL.searchParams.set('course', 'Node.js');
myURL.searchParams.set('duration', '6 months');

console.log(myURL.href);
Output:
https://example.com/courses?course=Node.js&duration=6+months

The set() method adds a parameter or replaces its existing value.

6. Delete Query Parameters

Example: Remove a Parameter
const myURL = new URL(
    'https://example.com/products?id=25&category=books'
);

myURL.searchParams.delete('category');

console.log(myURL.href);
Output:
https://example.com/products?id=25

The delete() method removes the specified query parameter.

7. Using the URL Module with require()

The URL class is available globally, but we can also import URL-related utilities from the built-in url module.

Example: Import URL
const { URL } = require('url');

const myURL = new URL('https://example.com/about');

console.log(myURL.pathname);
Output:
/about

Both the global URL class and the imported URL class provide the standard URL API.

8. Using a Base URL for Relative Paths

If we want to create a URL from a relative path, we must provide a base URL.

Example: Relative URL
const myURL = new URL(
    '/courses/nodejs',
    'https://example.com'
);

console.log(myURL.href);
console.log(myURL.pathname);
Output:
https://example.com/courses/nodejs
/courses/nodejs
Creating a URL from a relative path without a valid base URL causes a TypeError.

9. Practical Example: Student Search URL

Suppose we want to create a URL for searching student records. We can add the student's ID and name as query parameters.

Complete Program
const myURL = new URL('https://example.com/students');

myURL.searchParams.set('studentId', 'ST101');
myURL.searchParams.set('name', 'Amit Kumar');
myURL.searchParams.set('course', 'Full Stack Development');

console.log('Complete URL:', myURL.href);
console.log('Student ID:', myURL.searchParams.get('studentId'));
console.log('Student Name:', myURL.searchParams.get('name'));
console.log('Course:', myURL.searchParams.get('course'));
Output:
Complete URL: https://example.com/students?studentId=ST101&name=Amit+Kumar&course=Full+Stack+Development
Student ID: ST101
Student Name: Amit Kumar
Course: Full Stack Development

Save the code as url_example.js and run: node url_example.js.

10. Important URL Methods and Properties

Method / Property Purpose
new URL(input, base) Creates and parses a URL.
url.href Returns the complete URL.
url.hostname Returns the hostname.
url.pathname Returns the URL path.
url.searchParams.get() Reads a query parameter.
url.searchParams.set() Adds or updates a query parameter.
url.searchParams.delete() Removes a query parameter.
url.searchParams.has() Checks whether a parameter exists.

📝 Practical Assignment

Create a Student URL Program
Write a Node.js program that:
  1. Creates a URL for https://soopropathshala.com/students.
  2. Adds a student ID parameter.
  3. Adds the student's name and course.
  4. Displays the complete URL.
  5. Displays the pathname and hostname.
  6. Reads the student ID using searchParams.get().
  7. Deletes the course parameter and prints the updated URL.

Challenge: Create a URL using a relative path and a base URL, then display the final URL.


🧠 Quiz – URL Module

Select the correct answer for each question.

1. What does URL stand for?

2. Which property gives the pathname of a URL?

3. Which method reads a query parameter?