Hello Sunil

Base64 Encoding and Decoding in Next.js: Using btoa and atob

When working with web applications, you might encounter scenarios where you need to encode or decode strings into Base64 format. This is where JavaScript’s btoa and atob methods come in handy.

In this blog, we’ll explore what these methods do and how you can use them in a Next.js app with real-life examples.

btoa (Binary to ASCII)

The btoa function encodes a string into Base64. This can be particularly useful when transmitting data that might include special characters, such as in query parameters or HTTP headers.

Syntax:

const base64Encoded = btoa("Hello, World!");
console.log(base64Encoded); // Outputs: "SGVsbG8sIFdvcmxkIQ=="

atob (ASCII to Binary)

The atob function decodes a Base64-encoded string back to its original form.

Syntax:

const originalString = atob("SGVsbG8sIFdvcmxkIQ==");
console.log(originalString); // Outputs: "Hello, World!"
  • Encoding data for transmission: When sending data via APIs or storing it in cookies, Base64 encoding ensures the data remains intact.
  • Decoding received Base64 data: When receiving encoded data from an external source or API, decoding it back into a readable format is essential.

While btoa and atob work seamlessly in the browser, they’re not natively available in Node.js. For server-side operations in Next.js, you’ll need to use the Buffer API for Base64 encoding and decoding.

Let’s dive into two examples demonstrating how to use btoa and atob in a Next.js application.

This example demonstrates a simple encoder/decoder tool for user input on the client side.

import { useState } from "react";

export default function Base64App() {
  const [input, setInput] = useState("");
  const [encoded, setEncoded] = useState("");
  const [decoded, setDecoded] = useState("");

  const handleEncode = () => setEncoded(btoa(input));
  const handleDecode = () => setDecoded(atob(encoded));

  return (
    <div style={{ padding: "20px" }}>
      <h1>Base64 Encoder/Decoder</h1>
      <input
        type="text"
        placeholder="Enter text"
        value={input}
        onChange={(e) => setInput(e.target.value)}
      />
      <button onClick={handleEncode}>Encode</button>
      <button onClick={handleDecode}>Decode</button>

      <h2>Encoded: {encoded}</h2>
      <h2>Decoded: {decoded}</h2>
    </div>
  );
}

How It Works:

  • Users input a string in the text field.
  • Clicking “Encode” converts the input into a Base64-encoded string using btoa.
  • Clicking “Decode” decodes the Base64 string back to its original form using atob.

Here’s how you can handle Base64 encoding and decoding on the server side in Next.js using the Buffer API.

export async function getServerSideProps() {
  const text = "Secure Data";
  const encoded = Buffer.from(text).toString("base64");
  const decoded = Buffer.from(encoded, "base64").toString("utf-8");

  return {
    props: { encoded, decoded },
  };
}

export default function ServerBase64({ encoded, decoded }) {
  return (
    <div style={{ padding: "20px" }}>
      <h1>Server-Side Base64 Encoding/Decoding</h1>
      <p>Encoded: {encoded}</p>
      <p>Decoded: {decoded}</p>
    </div>
  );
}

How It Works:

  • Buffer is used to encode and decode the text on the server side.
  • The encoded and decoded strings are passed as props to the React component and displayed to the user.

Both btoa and atob only support ASCII strings. To handle non-ASCII characters (e.g., Unicode), you need additional encoding.

const encoded = btoa(unescape(encodeURIComponent("こんにちは")));
const decoded = decodeURIComponent(escape(atob(encoded)));

console.log(encoded); // Outputs: "JUUzJTgzJUFBJUUzJTgzJTlCJUUzJTgzJUJGJUUzJTgzJTlE"
console.log(decoded); // Outputs: "こんにちは"
  • Browser Compatibility: btoa and atob are browser-specific methods and not available in Node.js environments.
  • Use Buffer for Server-Side Encoding: When working on server-side operations in Next.js, always use the Buffer API.
  • Security: Base64 is an encoding technique, not encryption. For sensitive data, use proper encryption methods.

The btoa and atob methods offer simple and effective ways to encode and decode data in Base64 format. Whether you’re working on the client side or the server side in a Next.js app, these methods can handle many use cases efficiently.

By understanding their limitations and leveraging the Buffer API where necessary, you can confidently integrate Base64 encoding into your applications.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Similar articles you may like

Sunil Pradhan

Hi there 👋 I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.

Add comment

Stay Updated

Want to be notified when our article is published? Enter your email address below to be the first to know.

Sunil Pradhan

Hi there 👋 I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.