Base64 encode/decode · Guide

Decode Base64 Angular: Encoding and Decoding in Angular Apps

Angular has no Base64 helper of its own — you use the browser APIs. What Angular adds is a sanitizer that will silently blank a decoded data URI unless you tell it the value is trusted.

Encoding and decoding

The browser built-ins work as usual, wrapped in a service for reuse. Handle Unicode explicitly, since btoa throws above U+00FF:

TypeScript
@Injectable({ providedIn: 'root' })
export class Base64Service {
  encode(value: string): string {
    return btoa(String.fromCharCode(...new TextEncoder().encode(value)));
  }

  decode(value: string): string {
    return new TextDecoder().decode(
      Uint8Array.from(atob(value), (c) => c.charCodeAt(0))
    );
  }
}

The sanitizer

Binding a data: URI straight into [src] gets it stripped, and the console shows a sanitization warning. Mark it trusted explicitly — and only for values you produced:

TypeScript
constructor(private sanitizer: DomSanitizer) {}

imageUrl(b64: string): SafeUrl {
  return this.sanitizer.bypassSecurityTrustUrl(
    'data:image/png;base64,' + b64
  );
}

bypassSecurityTrustUrl disables Angular XSS protection for that value. Never pass user-supplied strings through it — a data:text/html payload becomes executable markup.

Decoding a JWT payload

JWT segments are base64url, so translate the alphabet and restore padding before decoding:

TypeScript
decodeJwtPayload(token: string): unknown {
  const part = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
  const padded = part.padEnd(part.length + ((4 - (part.length % 4)) % 4), '=');
  return JSON.parse(this.decode(padded));
}

This reads the claims; it does not verify the signature. Never make an authorisation decision in the browser based on a decoded token — the server must verify it.

Frequently asked questions

Why is my image blank?

Angular sanitized the data URI. Wrap it with bypassSecurityTrustUrl, and only for values you generated.

Do I need a Base64 npm package?

No. atob and btoa cover it; add a TextEncoder step for Unicode.

Is decoding a JWT in Angular safe?

Reading claims for display is fine. Trusting them for access control is not — only the server can verify the signature.

Ready to try it?

Open the free browser-based Base64 encode/decode and apply what you just read — no sign-up, runs locally.

Open the Base64 encode/decode tool