When working with Node.js, understanding how to handle URLs is essential. Whether you’re building an API, a website, or a simple server, you’ll need to process incoming requests, access query strings, route different pages, and sometimes manipulate URLs.
This blog will cover everything you need to know about handling URLs in Node.js. We’ll cover URL parsing, query strings, dynamic routing, and practical examples for each.
What is a URL?
A URL (Uniform Resource Locator) is a web address that specifies the location of a resource on the internet. It typically consists of the following components:
https://example.com:8080/path/to/page?name=John&age=30#about
URL Breakdown:
Part | Example | Description |
---|---|---|
Protocol | https:// | Specifies the protocol (HTTP/HTTPS/FTP) |
Host | example.com | The domain name of the server |
Port | :8080 | (Optional) Port number for the server |
Pathname | /path/to/page | Location of the file/resource on the server |
Query | ?name=John&age=30 | Extra parameters sent with the request |
Fragment | #about | A specific part of the page to jump to |
Setting up Your First Node.js Server
To handle URLs, we first need a server to process incoming HTTP requests.
Create a New File
- Create a new folder for your project:
mkdir node-url-handling
cd node-url-handling
2. Initialize the project:
npm init -y
3. Create a file named server.js
.
4. Add the following basic server code to server.js
:
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, this is your first Node.js server handling URLs!');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
5. Run the server:
node server.js
6. Open http://localhost:3000/ in your browser to see the message.
Handling URLs in Node.js
1- Parsing URLs
To extract useful parts of the URL (like the path, query string, and more), Node.js provides the built-in URL
module.
Example: Parsing a URL
const http = require('http');
const { URL } = require('url'); // Import the URL module
const server = http.createServer((req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);
res.setHeader('Content-Type', 'application/json');
res.writeHead(200);
res.end(JSON.stringify({
pathname: url.pathname,
searchParams: Object.fromEntries(url.searchParams)
}));
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Try This:
Visit:
http://localhost:3000/products?category=books&price=low
Output:
{
"pathname": "/products",
"searchParams": {
"category": "books",
"price": "low"
}
}
2- Extracting URL Components
You can extract specific parts of a URL like pathname, query parameters, hash, etc.
Example: Extract Components
const { URL } = require('url');
const url = new URL('https://example.com:8080/path/to/page?name=John&age=30#about');
console.log('Protocol:', url.protocol); // 'https:'
console.log('Host:', url.host); // 'example.com:8080'
console.log('Hostname:', url.hostname); // 'example.com'
console.log('Port:', url.port); // '8080'
console.log('Pathname:', url.pathname); // '/path/to/page'
console.log('Search Query:', url.search); // '?name=John&age=30'
console.log('Search Params:', Object.fromEntries(url.searchParams)); // { name: 'John', age: '30' }
console.log('Hash:', url.hash); // '#about'
3- Handling Query Strings
Query strings are the part of a URL that comes after ?
. They are used to pass information to the server.
Extract Query Parameters
The URLSearchParams object provides an easy way to work with query strings.
Example: Extract Query Parameters
const http = require('http');
const { URL } = require('url');
const server = http.createServer((req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);
const name = url.searchParams.get('name');
const age = url.searchParams.get('age');
res.setHeader('Content-Type', 'text/plain');
res.end(`Hello, ${name || 'Guest'}! Your age is ${age || 'unknown'}.`);
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Test the URL:
http://localhost:3000/?name=John&age=30
Output:
Hello, John! Your age is 30.
4- Handling URL Routing
Routing allows you to define what happens when a user visits different paths like /home
, /about
, etc.
Example: Handle Routes
const http = require('http');
const server = http.createServer((req, res) => {
const path = req.url;
if (path === '/') {
res.end('Welcome to the Home Page');
} else if (path === '/about') {
res.end('This is the About Page');
} else if (path === '/contact') {
res.end('Welcome to the Contact Page');
} else {
res.statusCode = 404;
res.end('404 - Page Not Found');
}
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Test the following URLs:
- http://localhost:3000/ — Home Page
- http://localhost:3000/about — About Page
- http://localhost:3000/contact — Contact Page
- http://localhost:3000/anythingelse — 404 Page
5- Handling Dynamic URLs
Sometimes you need to handle routes like /user/123
or /product/456
.
Example: Dynamic Routes
const http = require('http');
const server = http.createServer((req, res) => {
const path = req.url;
const matches = path.match(/^\/user\/(\d+)$/); // Capture a dynamic "id" from the URL
if (matches) {
const userId = matches[1];
res.end(`User Profile for User ID: ${userId}`);
} else {
res.statusCode = 404;
res.end('404 - Page Not Found');
}
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Test the URL:
http://localhost:3000/user/123
Output:
User Profile for User ID: 123
Best Practices
- Use Express.js for Routing: Manually parsing URLs gets tedious. Express.js makes it simple.
- Sanitize User Inputs: Never trust query parameters — validate and sanitize them.
- Use Middleware: Middleware can log requests, handle errors, and do security checks.
- Handle Edge Cases: Handle 404, 500, and other errors gracefully.
Final Words
Handling URLs in Node.js is a crucial skill for web developers. It forms the backbone of routing, APIs, and query string handling. With this knowledge, you can create robust applications that respond to user requests.
If you have any questions or want to explore other Node.js concepts, feel free to ask.
Happy coding! 😊
Comments