Explain Codes LogoExplain Codes Logo

How do I URL encode something in Node.js?

javascript
url-encoding
node-js
encoding-functions
Alex KataevbyAlex Kataev·Sep 28, 2024
TLDR

JavaScript's built-in function, encodeURIComponent, is an easy and effective tool for URL encoding in Node.js. This function transforms special characters into their proper URL-safe forms:

const encodedPhrase = encodeURIComponent('Say hi!'); console.log(encodedPhrase); // 'Say%20hi%21'

Voilà! Your special characters, even spaces and punctuation, are now packed and ready for a safe journey on the web highway!

Picking the right encoding function

You have several encoding tools in your arsenal, selecting the right one depends on your specific encoding needs.

Using encodeURIComponent for encoding data parameters

The encodeURIComponent function catches most of the special characters that need percent encoding in a URL fragment or a query string.

console.log(encodeURIComponent('&, =, #, ?, %')); // %26%2C%20%3D%2C%20%23%2C%20%3F%2C%20%25

Using encodeURI for encoding the entire URL

To encode a full URL, use encodeURI. It handles reserved characters (/, :, ?) with care, keeping them intact.

const url = encodeURI('http://example.com?name=John Doe&job=developer'); console.log(url); // http://example.com?name=John%20Doe&job=developer // Who knew John Doe was a developer? 😄

Using querystring.escape for Node.js specific URL-safe encoding

The Node.js built-in module querystring provides a method called escape. This method transforms a string into a URL-safe format.

const querystring = require('querystring'); console.log(querystring.escape('node=js&npm=i_love_it')); // node%3Djs%26npm%3Di_love_it // We all love npm, don't we? 😉

Pro tips for encoding

Advanced encoding with URI.js library

For complex encoding scenarios, the URI.js library supports a range of options: conversion between URI and IRI, encoding non-Latin characters using punycode, and more.

const URI = require('urijs'); const url = URI('http://welcome.to/javasworld'); console.log(url.normalize()); // http://welcome.to/javasworld, still the same country 😜

Beware of SQL injection risk

Remember to sanitize any inputs used in SQL queries to prevent SQL injection attacks. Ensure they're not just encoded, but free from malicious content.

// Little Bobby Tables strikes again 😈 const userInput = "Robert'); DROP TABLE Students;--"; const safeInput = encodeURIComponent(userInput); // Now safe to use in a URL. Crisis averted! 🙌