DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
API security

Is Base64 URL Safe? Base64url, Padding, Encoding, and Security Explained

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Ordinary Base64 is not automatically safe to put in every URL. Standard Base64 uses + and /, characters that have structural meaning in URLs. The URL-safe variant, conventionally called base64url, replaces + with - and / with _. Padding with = is a separate decision: keep it unless the protocol explicitly allows you to omit it.

Even base64url is not a universal permission to paste an arbitrary string into any URL location. A path segment, query parameter, fragment, HTTP header, and a signed token can each have different grammar and escaping rules. Always follow the specification used by the receiving application.

Base64 and base64url are different encodings

Both formats represent binary data as text by splitting input into 24-bit groups and emitting four 6-bit symbols. The difference is the alphabet used for the final two values.

Property Standard Base64 Base64url
Value 62 + -
Value 63 / _
Padding = when required, unless a specification says otherwise = when required, unless a specification says otherwise
Whitespace and invalid characters The decoder should reject characters outside the selected alphabet unless the referring specification explicitly defines another behavior

RFC 4648 specifically says base64url should not be treated as the same encoding as ordinary “base64” or referred to only as “base64.” A library option named base64url, urlsafe_b64encode, or equivalent is therefore preferable to manually replacing characters after an ordinary encoding.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why ordinary Base64 can break a URL

Slash in a path

In a URL path, / separates segments. If an ordinary Base64 value contains a slash and you concatenate it into a path, the server may see two segments instead of one value. Percent-encoding the slash as %2F can preserve the character, but only if the application decodes that component exactly once and treats the result as data.

Plus in a query

Many form-style query parsers interpret + as a space. A Base64 value copied into a query string can therefore be changed before your application reads it. Percent-encoding the plus as %2B, or using base64url, avoids that ambiguity.

Equals padding

= is a reserved character in URI syntax and commonly separates a query parameter name from its value. In a query value it should be percent-encoded when necessary by your URL builder. Some token formats permit omitted padding because the original length can be inferred; others require the padding. Removing it merely because a string is going into a URL is not a general rule.

What “URL-safe” means in each URL component

RFC 3986 defines URI components and a percent-encoding mechanism for characters that are outside an allowed set or are being used as delimiters. The right operation depends on where the value goes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Path segment: use base64url or percent-encode an ordinary Base64 value. Do not let a raw slash become a segment delimiter.
  • Query parameter value: pass the value through a URL/query builder rather than string concatenation. This correctly escapes plus signs, equals signs, ampersands, question marks, and other delimiters.
  • Fragment: apply the fragment grammar and escaping rules; do not assume query-string behavior.
  • Header or protocol token: follow that protocol’s token definition. A protocol may accept base64url with padding, without padding, or both.
  • Signed links and serialized tokens: use the exact alphabet, padding policy, byte encoding, and canonicalization required by the verifier. A one-character difference changes the signed bytes.

Padding: retain it or remove it?

Base64 encodes complete three-byte groups as four characters. If the final group is one or two bytes, = characters indicate the missing output positions. RFC 4648 says encoders must include appropriate padding unless the referring specification explicitly states that it may be omitted. The RFC notes that omission can be useful when data length is implicit, because it avoids encoding = in a URI.

Keep padding when

  • The API, token format, or library documents padded Base64 or does not document unpadded input.
  • The decoder needs padding to determine the final quantum.
  • You are exchanging values with multiple implementations and want the conventional RFC 4648 representation.

Omit padding only when

  • The specification explicitly permits unpadded base64url.
  • The consumer can recover the original length or otherwise defines how to restore padding.
  • Both producer and consumer agree on the canonical form, including how a decoder handles lengths that are invalid modulo four.

Do not remove padding and hope the other side will repair it. If a protocol allows unpadded input, implement its documented restoration rule and reject impossible lengths rather than silently guessing.

Encoding and decoding examples

JavaScript in Node.js

Node.js supports the URL-safe alphabet directly with the base64url encoding label. The result is unpadded; use ordinary base64 if your protocol requires padding.

const value = "binary data";
const encoded = Buffer.from(value, "utf8").toString("base64url");
console.log(encoded);

const decoded = Buffer.from(encoded, "base64url").toString("utf8");
console.log(decoded);

When constructing a URL, still use URL and URLSearchParams:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const token = Buffer.from("binary data").toString("base64url");
const url = new URL("https://example.test/download");
url.searchParams.set("token", token);
console.log(url.href);

Python

import base64

raw = b"binary data"
encoded = base64.urlsafe_b64encode(raw).decode("ascii")
print(encoded)                 # padded base64url

decoded = base64.urlsafe_b64decode(encoded)
assert decoded == raw

If your protocol explicitly requires an unpadded value, remove only trailing padding after encoding and restore it before decoding:

unpadded = encoded.rstrip("=")
padded = unpadded + "=" * (-len(unpadded) % 4)
assert base64.urlsafe_b64decode(padded) == raw

Browser JavaScript

btoa() and atob() use ordinary Base64 and operate on byte-like strings, not arbitrary Unicode text. Convert Unicode to UTF-8 bytes first, then translate the alphabet deliberately.

function toBase64Url(text) {
  const bytes = new TextEncoder().encode(text);
  let binary = "";
  for (const byte of bytes) binary += String.fromCharCode(byte);
  return btoa(binary)
    .replace(/+/g, "-")
    .replace(///g, "_")
    .replace(/=+$/, "");
}

function fromBase64Url(value) {
  const base64 = value.replace(/-/g, "+").replace(/_/g, "+")
    .replace(/-/g, "+").replace(/_/g, "/");
  const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
  const binary = atob(padded);
  return Uint8Array.from(binary, c => c.charCodeAt(0));
}

In production, prefer a well-maintained library or a platform API that explicitly supports base64url. Test Unicode, empty input, one-byte and two-byte inputs, and malformed lengths.

cURL and command-line workflows

For shell scripts, use a tool that documents its URL-safe mode, or encode ordinary Base64 and perform the two alphabet substitutions only when the target protocol defines that exact transformation. Avoid unquoted values: shell expansion and URL metacharacters can alter the data.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Base64 is encoding, not encryption

Base64 changes representation; it does not provide computational confidentiality. Anyone who receives the string can decode it. The format can visually hide a password or token payload, but it is not a security boundary. Use authenticated encryption or a properly designed secure protocol for secrets, and use HTTPS to protect data in transit. Do not place credentials or long-lived secrets in URLs merely because they are Base64-encoded; URLs can appear in browser history, server logs, referrer data, analytics systems, and support records.

Protocol-specific rules matter

There is no universal “safe” switch that overrides a protocol’s grammar. RFC 7235, for example, defines an HTTP authentication token syntax that can carry base64url with or without padding and excludes whitespace. That is an example of a protocol making an explicit choice, not a rule that every URL accepts both forms.

Before implementing, record these requirements:

  • Which bytes are encoded, and in what character encoding?
  • Is the alphabet ordinary Base64 or base64url?
  • Is padding required, optional, or forbidden?
  • Where is the value placed: path, query, fragment, header, cookie, or body?
  • Must the value be percent-encoded by a URL builder?
  • Are whitespace and non-alphabet characters rejected?
  • Is a canonical spelling required for signatures or cache keys?

Troubleshooting common failures

“Invalid character” or “malformed Base64”

The producer and consumer may use different alphabets, or the value may contain copied whitespace. Confirm whether -/_ or +// is expected, reject unexpected characters, and do not silently discard them unless the protocol says to.

The decoded value is corrupted after a URL round trip

Look for a raw + converted to a space, a slash interpreted as a path separator, or an ampersand ending a query value. Use base64url for token formats and a URL API for query parameters; inspect the exact URL received by the server.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Decoder complains about length

Base64 text has a length relationship to four-character quanta. An unpadded value may require protocol-defined padding restoration, while a length that leaves a remainder of one when divided by four cannot represent valid Base64 without missing data. Reject it instead of guessing.

Signature verification fails

Signatures cover bytes, not a visually similar decoded object. Differences in padding, alphabet, percent-encoding order, Unicode normalization, or JSON serialization can change the signed input. Canonicalize exactly as the signing specification requires before verification.

Unicode decodes incorrectly

Base64 operates on bytes. Encode text as UTF-8 before Base64 conversion and decode the resulting bytes as UTF-8 only when that is the agreed character encoding. Browser btoa() is not a general Unicode encoder.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Testing checklist for an implementation

  1. Test empty input and inputs of one, two, and three bytes.
  2. Include data that produces the standard alphabet’s + and /.
  3. Test padded and unpadded forms only where the protocol allows them.
  4. Round-trip through the exact URL component used in production.
  5. Verify that query parsing does not turn plus signs into spaces.
  6. Reject invalid characters, impossible lengths, and unexpected whitespace.
  7. Compare byte-for-byte output with an independent implementation.
  8. Check that logs, analytics, and error messages do not expose sensitive decoded content.

Or skip the browser setup

If your actual goal is obtaining a clean screenshot of a URL rather than transporting an encoded value, ScreenshotNeo provides a single-call API. It accepts cookie and consent banners before capture, removes more than 60 known consent platforms plus newsletter popups and chat widgets, and lets you turn each cleanup step off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed; response headers identify the page verdict and whether the request was billed. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Example (see the ScreenshotNeo API documentation):

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

There is a free allowance of 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots, and every feature is included on every plan. Create a free ScreenshotNeo account.

Best Value
Sale
The Web Application Hacker's Handbook: Finding and Exploiting Security Flaws
  • Comes with secure packaging
  • It can be a gift item
  • Easy to read text

Frequently Asked Questions

Can I put ordinary Base64 in a URL query parameter?

Yes, if you correctly percent-encode it with a URL/query builder and the receiving application decodes it as intended. Base64url is usually less error-prone for token values because it avoids plus and slash.

Is base64url always unpadded?

No. The alphabet change and padding policy are separate. Keep or omit = according to the protocol.

Does URL encoding make Base64 secret?

No. Percent-encoding and Base64 are reversible representations, not encryption.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should a decoder accept both Base64 and base64url?

Only when the protocol explicitly permits both. Accepting unexpected alphabets or characters can hide corruption and create security inconsistencies.

Quick Recap

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.