Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

encodeBase64Url

Encodes a string into a base64url-safe format. Removes padding and replaces unsafe characters.

TypeScript
Copied!
1/**
2 * Encodes a string into a base64url-safe format.
3 * Removes padding and replaces unsafe characters.
4 *
5 * @param input - The input string to encode.
6 * @returns A base64url-encoded string.
7 */
8export function encodeBase64Url(input: string): string {
9  const base64 = Buffer.from(input, 'utf-8').toString('base64');
10  return base64
11    .replace(/\+/g, '-')
12    .replace(/\//g, '_')
13    .replace(/=+$/, '');
14}
  • URL-Safe Output

    Transforms standard Base64 into a variant that avoids characters (+, /, =) which are problematic in URLs.

  • Compact Encoding

    Omits padding (=), resulting in a shorter output that's ideal for tokens or query parameters.

  • Cross-Platform Compatibility

    Generates output that's safe to embed in URLs, HTTP headers, cookies, and filenames without additional encoding.

  • Efficient Conversion

    Uses native Buffer functionality for encoding, ensuring fast performance in both Node.js and compatible environments.

Tests | Examples

TypeScript
Copied!
1test('encodeBase64Url - encodes simple text', () => {
2  expect(encodeBase64Url('hello')).toBe('aGVsbG8');
3});
4
5test('encodeBase64Url - encodes string with special characters', () => {
6  expect(encodeBase64Url('hello+world/')).toBe('aGVsbG8rd29ybGQv');
7});
8
9test('encodeBase64Url - removes trailing equals', () => {
10  expect(encodeBase64Url('foo')).toBe('Zm9v');
11});
12
13test('encodeBase64Url - handles unicode characters', () => {
14  expect(encodeBase64Url('✓ check')).toBe('4pyTIMOgY2hlY2s');
15});
16
17test('encodeBase64Url - empty string', () => {
18  expect(encodeBase64Url('')).toBe('');
19});

Common Use Cases

  • JWT (JSON Web Token) Encoding

    Base64url is the standard encoding for JWT headers and payloads.

  • Generating Safe URL Tokens

    Encode session tokens, activation links, or password reset codes that won’t break when used in URLs.

  • Embedding Data in URLs or QR Codes

    Safely include encoded data in links or QR payloads without encoding overhead.

  • Filename-Safe Identifiers

    Create identifiers that can be safely used as filenames on most file systems.

  • Interoperability with Web APIs

    Communicate with services (e.g. OAuth, OpenID) that expect base64url encoding instead of regular Base64.

Codebase: Utilities -> Encoding -> encodeBase64Url | Yevhen Klymentiev