"use client"; import { useState, useCallback, useId } from "react"; import ToolLayout from "@/components/ToolLayout"; export default function Base64Page() { const inputId = useId(); const outputId = useId(); const [input, setInput] = useState(""); const [output, setOutput] = useState(""); const [error, setError] = useState(null); const [copied, setCopied] = useState(false); const [urlSafe, setUrlSafe] = useState(false); const [splitLines, setSplitLines] = useState(false); const [lastAction, setLastAction] = useState<"encode" | "decode" | null>(null); const encodeBase64 = useCallback((text: string, isUrlSafe: boolean, isSplit: boolean) => { if (!text) { setOutput(""); setError(null); return; } try { const bytes = new TextEncoder().encode(text); let binary = ""; for (let i = 0; i < bytes.length; i++) { binary += String.fromCharCode(bytes[i]); } let base64 = btoa(binary); if (isUrlSafe) { base64 = base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } if (isSplit && base64.length > 76) { base64 = base64.match(/.{1,76}/g)?.join("\n") || base64; } setOutput(base64); setError(null); setLastAction("encode"); } catch (err) { setError(err instanceof Error ? err.message : "Failed to encode input."); setOutput(""); } }, []); const decodeBase64 = useCallback((text: string) => { if (!text.trim()) { setOutput(""); setError(null); return; } try { let cleaned = text.trim().replace(/\s+/g, ""); cleaned = cleaned.replace(/-/g, "+").replace(/_/g, "/"); while (cleaned.length % 4 !== 0) { cleaned += "="; } if (!/^[A-Za-z0-9+/=]+$/.test(cleaned)) { throw new Error("Invalid Base64 string: Contains characters outside the Base64 alphabet."); } const binary = atob(cleaned); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) { bytes[i] = binary.charCodeAt(i); } try { const decoded = new TextDecoder("utf-8", { fatal: true }).decode(bytes); setOutput(decoded); } catch { setOutput(binary); } setError(null); setLastAction("decode"); } catch (err) { setError( err instanceof Error ? err.message : "Invalid Base64 string. Please check your input and try again." ); setOutput(""); } }, []); const handleEncode = () => { encodeBase64(input, urlSafe, splitLines); }; const handleDecode = () => { decodeBase64(input); }; const handleCopy = async () => { if (!output) return; try { await navigator.clipboard.writeText(output); setCopied(true); setTimeout(() => setCopied(false), 2000); } catch { const textArea = document.createElement("textarea"); textArea.value = output; document.body.appendChild(textArea); textArea.select(); document.execCommand("copy"); document.body.removeChild(textArea); setCopied(true); setTimeout(() => setCopied(false), 2000); } }; const handleSwap = () => { const temp = output; setInput(temp); setOutput(input); setError(null); if (lastAction === "encode") { setLastAction("decode"); } else if (lastAction === "decode") { setLastAction("encode"); } }; const handleClear = () => { setInput(""); setOutput(""); setError(null); setLastAction(null); }; const loadSample = (type: "text" | "unicode" | "base64") => { setError(null); if (type === "text") { const sample = "Hello, Developer! DevToolbox makes Base64 encoding fast and easy."; setInput(sample); encodeBase64(sample, urlSafe, splitLines); } else if (type === "unicode") { const sample = "Unicode test: 🚀 🌍 Привет! こんにちは 你好 €100 — café & naïve."; setInput(sample); encodeBase64(sample, urlSafe, splitLines); } else { const sample = "SGVsbG8sIFdvcmxkISBUaGlzIGlzIGEgZGVjb2RlZCBCYXNlNjQgbWVzc2FnZS4="; setInput(sample); decodeBase64(sample); } }; const inputBytes = new TextEncoder().encode(input).length; const outputBytes = new TextEncoder().encode(output).length; return ( Base64 Encode & Decode Online — DevToolbox
{/* Controls Bar */}
{/* Sample buttons */}
Samples:
{/* Options */}
{/* Error Notification */} {error && (

Decoding Error

{error}

)} {/* Two-Column Editor Grid */}
{/* Input Area */}
{input.length} chars | {inputBytes} bytes