0
0
NodejsHow-ToBeginner · 3 min read

How to Decode URL in Node.js: Simple Guide with Examples

In Node.js, you can decode a URL using the built-in decodeURIComponent() or decodeURI() functions. Use decodeURIComponent() to decode parts of a URL like query parameters, and decodeURI() to decode a full URL string.
📐

Syntax

decodeURIComponent(encodedURIComponent): Decodes a URL-encoded component, such as query parameters or path segments.

decodeURI(encodedURI): Decodes a full encoded URL but does not decode reserved characters like #, ?, or &.

javascript
decodeURIComponent(encodedURIComponent)
decodeURI(encodedURI)
💻

Example

This example shows how to decode an encoded URL component and a full encoded URL string using Node.js built-in functions.

javascript
const encodedComponent = 'Hello%20World%21';
const decodedComponent = decodeURIComponent(encodedComponent);

const encodedURL = 'https%3A%2F%2Fexample.com%2Fsearch%3Fq%3Dnode.js%2520url%2520decode';
const decodedURL = decodeURI(encodedURL);

console.log('Decoded Component:', decodedComponent);
console.log('Decoded URL:', decodedURL);
Output
Decoded Component: Hello World! Decoded URL: https://example.com/search?q=node.js%20url%20decode
⚠️

Common Pitfalls

1. Using decodeURI() on URL components: It won't decode characters like %26 (&) or %3F (?). Use decodeURIComponent() for parts like query parameters.

2. Double decoding: Decoding an already decoded string can cause errors or unexpected characters.

3. Passing invalid encoded strings: If the string is not properly encoded, decoding functions throw URIError. Always handle errors or validate input.

javascript
try {
  const badString = '%E0%A4%A'; // Invalid encoding
  console.log(decodeURIComponent(badString));
} catch (error) {
  console.error('Error decoding:', error.message);
}

// Correct usage
const goodString = '%E0%A4%A6';
console.log(decodeURIComponent(goodString));
Output
Error decoding: URI malformed द
📊

Quick Reference

FunctionUse CaseDecodes Reserved Characters?
decodeURIComponent()Decode URL parts like query parameters or path segmentsYes
decodeURI()Decode full URL string without decoding reserved charactersNo

Key Takeaways

Use decodeURIComponent() to decode individual URL parts like query parameters.
Use decodeURI() to decode a full URL but reserved characters remain encoded.
Avoid double decoding to prevent errors or corrupted strings.
Always handle errors when decoding to catch malformed input.
Node.js built-in functions make URL decoding simple and reliable.