<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kingson Ejikeme on Medium]]></title>
        <description><![CDATA[Stories by Kingson Ejikeme on Medium]]></description>
        <link>https://medium.com/@kingsonejikeme_31625?source=rss-3893db93baa9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RqDD4Hb3V0b8YrD5</url>
            <title>Stories by Kingson Ejikeme on Medium</title>
            <link>https://medium.com/@kingsonejikeme_31625?source=rss-3893db93baa9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 10:07:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kingsonejikeme_31625/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[API Encryption in Next.js: Keep Your Data Safe ]]></title>
            <link>https://medium.com/@kingsonejikeme_31625/api-encryption-in-next-js-keep-your-data-safe-efdf94c0eae9?source=rss-3893db93baa9------2</link>
            <guid isPermaLink="false">https://medium.com/p/efdf94c0eae9</guid>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nextjs-tutorial]]></category>
            <category><![CDATA[encryption-api]]></category>
            <dc:creator><![CDATA[Kingson Ejikeme]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 03:11:43 GMT</pubDate>
            <atom:updated>2024-09-10T03:11:43.766Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y1aJlX-B-oNcIYe9QE6EUg.jpeg" /><figcaption>Next.js APIsecurity</figcaption></figure><p>Hello there 🖐! I’m Kingson, and today I’ll guide you through the steps to encrypt API responses and payloads in Next.js. Let’s get started!</p><h3>Why API Encryption?</h3><p>API encryption encodes data between a client and an API to prevent unauthorized access or alteration, using cryptographic algorithms to protect against interception and cyberattacks.</p><p>Say you have some keys or data you wouldn’t want users and/or hackers to get from their browsers.</p><p>This is solved making api calls server-side. This could be either using server actions in Next js(&gt;14.0.0) or the api route. However this doesn’t completely solve the problem as the payload being sent and received on the client-side is visible in the browser.</p><p>This can be solved by encrypting the payload and response.</p><h3>Setting Up Project</h3><p>Let’s begin by setting up a Next.js project. Open your terminal and run the following command to create the Next.js folder architecture:</p><pre>npx create-next-app@latest</pre><p>You will be prompted with a series of questions. Provide the following answers:</p><ul><li>What is your project named? &lt;<strong>name your project</strong>&gt;</li><li>Would you like to use TypeScript? <strong>Yes</strong></li><li>Would you like to use ESLint? <strong>Yes</strong></li><li>Would you like to use Tailwind CSS? <strong>Yes</strong></li><li>Would you like to use the src/ directory? <strong>Yes</strong></li><li>Would you like to use the App Router? (recommended) <strong>Yes</strong></li><li>Would you like to customize the default import alias (@/*)? <strong>No</strong></li></ul><h3>Installing Dependencies</h3><p>First, we install axios.</p><pre>npm install axios</pre><h3>Encrypting Data: The Basics</h3><p>We’ll be using symmetric key encryption with AES-GCM from the Web Crypto API.</p><p>1. <strong>How Symmetric Encryption Works</strong>: Symmetric key encryption basically means the same key is used for encryption and decryption(Ensure your key is not saved in your code but in your .env).</p><p>2. <strong>Why AES-GCM is Your Friend</strong>: AES-GCM is a standard that ensures the data is not only encrypted but also hasn’t been tampered with.</p><h3>Creating Your Encryption Function</h3><p>The first function we’d define is the encryption function.<br>Here’s how it works;</p><ol><li><strong>Create a Random IV (Initialization Vector)</strong>: The code first creates a random sequence of numbers called an <strong>IV</strong> (Initialization Vector). This IV is like a unique, random “salt” that makes sure the same message doesn’t always get encrypted in the same way. It adds extra randomness for security.</li><li><strong>Encode the Plain Data</strong>: Next, the text you want to encrypt (the <strong>plainData</strong>) gets converted into a format the computer can work with, called a <strong>byte array</strong>. Computers deal with numbers, not plain text, so we have to convert the text to a numeric form using a <strong>TextEncoder</strong>.</li><li><strong>Prepare the Encryption Key</strong>: You need an <strong>encryption key</strong>, which is like a password that locks (encrypts) and unlocks (decrypts) the data. This key is turned into something the browser’s encryption tools can use via a method called crypto.subtle.importKey. The encryption algorithm used here is <strong>AES-GCM</strong>, which is a highly secure and efficient method.</li><li><strong>Encrypt the Data</strong>: Once the key and the IV are ready, the code encrypts the message using <strong>AES-GCM</strong>. This step turns the original readable data into a string of random-looking numbers and letters, which is the <strong>encryptedData</strong>. Without the right key and IV, no one can turn this back into the original message.</li><li><strong>Return the Encrypted Data and IV</strong>: The encrypted data and the IV are then converted into a <strong>base64</strong> format, which is just a way of representing binary data as text, making it easier to store or send.</li></ol><p>When this process is done, the result is a scrambled version of your original message (encryptedData) and the IV used to create it. You’ll need both the IV and the encryption key later to decrypt (unscramble) the message.</p><pre>const encryptData = async (plainData: string, encryptionKey: string) =&gt; {<br>  // Generate a random 96-bit initialization vector (IV)<br>  const initVector = crypto.getRandomValues(new Uint8Array(12));<br><br>  // Encode the data to be encrypted<br>  const encodedData = new TextEncoder().encode(plainData);<br><br>  // Prepare the encryption key<br>  const cryptoKey = await crypto.subtle.importKey(<br>    &quot;raw&quot;,<br>    Buffer.from(encryptionKey, &quot;base64&quot;),<br>    {<br>      name: &quot;AES-GCM&quot;,<br>      length: 256,<br>    },<br>    true,<br>    [&quot;encrypt&quot;, &quot;decrypt&quot;]<br>  );<br><br>  // Encrypt the encoded data with the key<br>  const encryptedData = await crypto.subtle.encrypt(<br>    {<br>      name: &quot;AES-GCM&quot;,<br>      iv: initVector,<br>    },<br>    cryptoKey,<br>    encodedData<br>  );<br><br>  // Return the encrypted data and the IV, both in base64 format<br>  return {<br>    encryptedData: Buffer.from(encryptedData).toString(&quot;base64&quot;),<br>    initVector: Buffer.from(initVector).toString(&quot;base64&quot;),<br>  };<br>};<br><br>const handleEncryption = async (data: any) =&gt; {<br>  return await encryptData(<br>    JSON.stringify({ data }),<br>    process.env.NEXT_PUBLIC_SECRET_KEY!<br>  );<br>};<br><br>export {handleEncryption}</pre><h3>Decryption Demystified</h3><p>The second function we’ll define is the decryption function. Here’s how it works:</p><ol><li><strong>Prepare the Decryption Key</strong>: To decrypt the message, you need the same key that was used to encrypt it. This key is like a password that allows you to unlock (decrypt) the data. The key is converted into a form the browser’s decryption tools can use, just like it was during encryption. This is done using a method called crypto.subtle.importKey, and we use the same encryption algorithm, <strong>AES-GCM</strong>, for consistency.</li><li><strong>Decode the Encrypted Data</strong>: The encrypted data and IV (Initialization Vector) you have are first converted from base64 format back into binary data. Base64 is a way of encoding data as text so it can be easily transmitted or stored. We need to revert this encoding to get back to the original binary format used in the encryption process.</li><li><strong>Decrypt the Data</strong>: Using the key and the IV, the code decrypts the scrambled message (the encryptedData) using <strong>AES-GCM</strong>. This process reverses the encryption, turning the scrambled data back into its original readable form (plainData). If the key and IV match those used during encryption, the decryption will be successful.</li><li><strong>Return the Decrypted Data</strong>: Finally, the decrypted data is converted back into a readable text format so you can use it as needed.</li></ol><h3>Summary:</h3><p>The decryption function reverses the encryption process. It uses the same key and IV that were used to encrypt the message to turn the scrambled data back into its original, readable form.</p><pre>const decryptData = async (<br>  encryptedData: string,<br>  initVector: string,<br>  encryptionKey: string<br>) =&gt; {<br>  // Prepare the decryption key<br>  const cryptoKey = await crypto.subtle.importKey(<br>    &quot;raw&quot;,<br>    Buffer.from(encryptionKey, &quot;base64&quot;),<br>    {<br>      name: &quot;AES-GCM&quot;,<br>      length: 256,<br>    },<br>    true,<br>    [&quot;encrypt&quot;, &quot;decrypt&quot;]<br>  );<br><br>  try {<br>    // Decrypt the encrypted data using the key and IV<br>    const decodedData = await crypto.subtle.decrypt(<br>      {<br>        name: &quot;AES-GCM&quot;,<br>        iv: Buffer.from(initVector, &quot;base64&quot;),<br>      },<br>      cryptoKey,<br>      Buffer.from(encryptedData, &quot;base64&quot;)<br>    );<br><br>    // Decode and return the decrypted data<br>    return new TextDecoder().decode(decodedData);<br>  } catch (error) {<br>    return JSON.stringify({ payload: null });<br>  }<br>};<br><br>const handleDecryption = async ({ encryptedData, initVector }: any) =&gt; {<br>  const decryptedString = await decryptData(<br>    encryptedData!,<br>    initVector!,<br>    process.env.NEXT_PUBLIC_SECRET_KEY!<br>  );<br><br>  const responseData = JSON.parse(decryptedString)?.data;<br><br>  return responseData;<br>};</pre><h3><strong>Server Actions in Practice</strong></h3><p>In our example, we will be using server actions to make calls to our APIs.<br>Defining our server action;</p><pre>&quot;use server&quot;<br>import { fetchPutRequest, handleEncryption, handleDecryption } from &quot;./utils&quot;; <br>import { IApiRequest } from &quot;@/types&quot;;<br>import lodash from &quot;lodash&quot;;<br><br>export const updateUserInformation = async ({ endpointUrl, requestData, requestOptions }: IApiRequest) =&gt; {<br>  try {<br>    // Decrypt the incoming payload<br>    const decryptedData = await processDecryption(requestData);<br>    <br>    // Perform the PUT request<br>    const response = await fetchPutRequest({ url: endpointUrl, body: decryptedData });<br><br>    // Encrypt the response data excluding specific fields<br>    const sanitizedResponse = await handleEncryption(<br>      // filter out unwanted fields<br>      lodash.omit(data, [&quot;request&quot;, &quot;config&quot;])<br>    );<br><br>    return sanitizedResponse;<br>  } catch (error) {<br>    // Encrypt error details<br>    const errorResponse = await handleEncryption({<br>      errorInfo: {<br>        data: error?.response?.data,<br>        statusText: error?.response?.statusText,<br>        statusCode: error?.response?.status,<br>      }<br>    });<br><br>    return errorResponse;<br>  }<br>};</pre><h3><strong>Client-Side Integration</strong></h3><ul><li><strong>Build the ResourceUpdater Component</strong>: Create a React component to interact with your server-side encryption functions.</li><li><strong>Handle Responses and Errors</strong>: Manage the results and errors from your encrypted API calls effectively.</li></ul><pre>&quot;use client&quot;<br>import { useState } from &#39;react&#39;;<br>import { updateUserInformation } from &#39;@/path/to/the/server/actions&#39;;<br><br>const ResourceUpdater = () =&gt; {<br>  const [response, setResponse] = useState&lt;string | null&gt;(null);<br>  const [error, setError] = useState&lt;string | null&gt;(null);<br><br>  const handleUpdate = async () =&gt; {<br>    try {<br>      // Define your endpoint URL and payload<br>      const endpointUrl = &#39;/api/resource/update&#39;;<br>      const requestData = {<br>        uniqueId: &quot;00000000-0000-0000-00000000&quot;,<br>        topSecret: &quot;I love parrots.&quot;<br>      };<br>      const requestOptions = {<br>        // Optional request options<br>      };<br><br>      // Call the server action<br>      const result = await updateUserInformation({<br>        endpointUrl,<br>        requestData,<br>        requestOptions,<br>      });<br><br>      // Handle the result<br>      setResponse(result);<br>      setError(null);<br>    } catch (err) {<br>      // Handle errors<br>      setResponse(null);<br>      setError(&#39;An error occurred while updating the resource.&#39;);<br>    }<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={handleUpdate}&gt;Update Resource&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ResourceUpdater;</pre><p><strong>Summary</strong></p><p>We explored methods to safeguard our web applications by encrypting sensitive data during network communications, ensuring that unauthorized parties cannot access or decipher the information from the client application. With these measures in place, users and hackers alike are unable to intercept, read, or tamper with the encrypted data, thereby enhancing the security of your application’s communication channels.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efdf94c0eae9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>