How to Encode URL in Node.js: Simple Guide with Examples
In Node.js, you can encode URLs using the built-in
encodeURIComponent() function to safely encode parts of a URL. For full URLs, you can use the URL class to construct and encode URLs properly.Syntax
The main methods to encode URLs in Node.js are:
encodeURIComponent(string): Encodes a URI component by escaping characters that have special meaning.encodeURI(string): Encodes a full URI but leaves some characters like:/?#intact.new URL(input, base): Creates a URL object that automatically encodes components when you set them.
javascript
encodeURIComponent(component) encodeURI(uri) const url = new URL(input, base);
Example
This example shows how to encode a query parameter safely using encodeURIComponent and how to build a full URL using the URL class.
javascript
const searchTerm = 'Node.js & URL encoding'; // Encode a query parameter const encodedTerm = encodeURIComponent(searchTerm); console.log('Encoded query parameter:', encodedTerm); // Build a full URL with encoded query const baseUrl = 'https://example.com/search'; const url = new URL(baseUrl); url.searchParams.set('q', encodedTerm); console.log('Full encoded URL:', url.toString());
Output
Encoded query parameter: Node.js%20%26%20URL%20encoding
Full encoded URL: https://example.com/search?q=Node.js%20%26%20URL%20encoding
Common Pitfalls
Common mistakes include:
- Using
encodeURI()to encode query parameters, which does not encode characters like&and=, causing errors. - Double encoding already encoded strings, which leads to incorrect URLs.
- Not encoding user input before adding it to URLs, risking broken URLs or security issues.
javascript
const wrong = encodeURI('Node.js & URL encoding'); console.log('Wrong encoding:', wrong); const right = encodeURIComponent('Node.js & URL encoding'); console.log('Right encoding:', right);
Output
Wrong encoding: Node.js%20&%20URL%20encoding
Right encoding: Node.js%20%26%20URL%20encoding
Quick Reference
| Function/Class | Purpose | When to Use |
|---|---|---|
| encodeURIComponent(string) | Encodes individual URI components | Encode query parameters or path segments |
| encodeURI(string) | Encodes full URI but leaves some chars intact | Encode full URLs without query parameters |
| URL class | Builds and encodes full URLs | Construct URLs with multiple parts safely |
Key Takeaways
Use encodeURIComponent() to safely encode query parameters or parts of URLs.
Use the URL class to build and encode full URLs with multiple components.
Avoid encodeURI() for query parameters as it leaves some characters unencoded.
Never double encode strings; encode only once before using in URLs.
Always encode user input before adding it to URLs to prevent errors and security issues.