Start a project
Node JS 4 min read

Handling URLs in Node.js

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,…

Handling URLs in Node.js
// on this page
  1. What is a URL?
  2. Setting up Your First Node.js Server
  3. Create a New File
  4. Handling URLs in Node.js
  5. 1- Parsing URLs
  6. 2- Extracting URL Components
  7. Example: Extract Components
  8. 3- Handling Query Strings
  9. Extract Query Parameters
  10. 4- Handling URL Routing
  11. Example: Handle Routes
  12. 5- Handling Dynamic URLs
  13. Example: Dynamic Routes
  14. Best Practices
  15. Final Words

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.

01What 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:

PartExampleDescription
Protocolhttps://Specifies the protocol (HTTP/HTTPS/FTP)
Hostexample.comThe domain name of the server
Port:8080(Optional) Port number for the server
Pathname/path/to/pageLocation of the file/resource on the server
Query?name=John&age=30Extra parameters sent with the request
Fragment#aboutA specific part of the page to jump to

02Setting up Your First Node.js Server

To handle URLs, we first need a server to process incoming HTTP requests.

Create a New File

  1. 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.

03Handling 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"
  }
}

042- 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'

053- 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.
// skip the reading, get the result
I'll build this for your business and handle what's technical.One call, a written scope, and the work delivered in weekly milestones.
Start a project →

064- 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:

075- 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

08Best Practices

  1. Use Express.js for Routing: Manually parsing URLs gets tedious. Express.js makes it simple.
  2. Sanitize User Inputs: Never trust query parameters — validate and sanitize them.
  3. Use Middleware: Middleware can log requests, handle errors, and do security checks.
  4. Handle Edge Cases: Handle 404, 500, and other errors gracefully.

09Final 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

Leave a comment

// your email is never published

Reading about it is good.
Having it built is better.

Booking platforms, business systems, online stores and AI assistants — scoped on one call, built in weekly milestones.

// you pay as each milestone is delivered
share