Convert Base64-encoded strings to Uint8Array for processing binary data in Lambda functions. Useful for handling encoded payloads, binary data in API responses, or working with AWS services that return Base64-encoded data.
Convert a base64 string to a Uint8Array.
/**
* Convert a base64 string to a Uint8Array.
* The input string must be a valid base64 string, otherwise an error will be thrown.
* The encoding parameter is optional and defaults to 'utf-8'.
*
* @param input - The base64 string to convert to a Uint8Array
* @param encoding - The encoding of the input string (optional, default: 'utf-8')
* @returns Uint8Array representation of the decoded base64 string
* @throws TypeError if input has incorrect padding or is invalid base64
*/
function fromBase64(input: string, encoding?: BufferEncoding): Uint8Array;Usage Examples:
import { fromBase64 } from '@aws-lambda-powertools/commons/utils/base64';
// Basic usage - decode base64 string
const encodedValue = 'aGVsbG8gd29ybGQ=';
const decoded = fromBase64(encodedValue);
// Result: Uint8Array containing the decoded bytes
// Convert to string if needed
const textDecoder = new TextDecoder();
const text = textDecoder.decode(decoded);
console.log(text); // 'hello world'
// With explicit encoding
const encodedData = 'SGVsbG8gV29ybGQ=';
const decodedData = fromBase64(encodedData, 'base64');The fromBase64 function throws TypeError in the following cases:
try {
const result = fromBase64('invalid-base64!!!');
} catch (error) {
if (error instanceof TypeError) {
console.error('Invalid base64 input:', error.message);
}
}