<?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 Nazar on Medium]]></title>
        <description><![CDATA[Stories by Nazar on Medium]]></description>
        <link>https://medium.com/@nazardubovyk?source=rss-fc8da44ff6c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*d5Vt93eM0NiLtyEb7d5O2w.jpeg</url>
            <title>Stories by Nazar on Medium</title>
            <link>https://medium.com/@nazardubovyk?source=rss-fc8da44ff6c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:17:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nazardubovyk/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[Plaid Integration With Next.js 14: Step-by — Step Guide]]></title>
            <link>https://medium.com/@nazardubovyk/step-by-step-guide-to-integrate-plaid-with-next-js-14-app-router-356b547b5a4a?source=rss-fc8da44ff6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/356b547b5a4a</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[plaid-api]]></category>
            <category><![CDATA[plaid]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Nazar]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 13:40:46 GMT</pubDate>
            <atom:updated>2024-09-26T12:52:20.718Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9E7Pn1OeUiLjYf-_tn85yw.png" /></figure><h3>1. Create a Plaid Account</h3><p><strong>Create a Plaid Account</strong> First, we need to create an account on <a href="https://plaid.com/en-eu/">Plaid</a> and obtain our client ID, secret, and environment variables to set up the <strong>Plaid integration</strong>.</p><h3>2. Install Required Packages</h3><p>Let’s install the necessary packages:</p><pre>yarn add plaid react-plaid-link axios</pre><h3>3. Configure Environment Variables</h3><p>Create a .env.local file in the root directory of your project and add the following variables to configure the <strong>Plaid development environment</strong>:</p><pre>PLAID_CLIENT_ID=your-client-id<br>PLAID_SECRET=your-secret<br>PLAID_ENV=sandbox</pre><h3>4. Create API Endpoints in the App Router and plaid integration</h3><p>To start the <strong>Plaid integration</strong>, we need to generate a Link Token.</p><p>Create a file app/api/plaid/create-link-token/route.ts:</p><pre>import { NextRequest, NextResponse } from &#39;next/server&#39;;<br>import { Configuration, PlaidApi, PlaidEnvironments, Products, CountryCode } from &#39;plaid&#39;;<br><br>const config = new Configuration({<br>  basePath: PlaidEnvironments[process.env.PLAID_ENV as keyof typeof PlaidEnvironments],<br>  baseOptions: {<br>    headers: {<br>      &#39;PLAID-CLIENT-ID&#39;: process.env.PLAID_CLIENT_ID || &#39;&#39;,<br>      &#39;PLAID-SECRET&#39;: process.env.PLAID_SECRET || &#39;&#39;,<br>    },<br>  },<br>});<br>const client = new PlaidApi(config);<br>export async function POST(req: NextRequest) {<br>  try {<br>    const { client_user_id } = await req.json();<br>    const response = await client.linkTokenCreate({<br>      user: { client_user_id },<br>      client_name: &#39;Name your App&#39;,<br>      products: [<br>        Products.Auth,<br>        Products.Transactions,<br>      ],<br>      country_codes: [CountryCode.Us],<br>      language: &#39;en&#39;,<br>    });<br>    return NextResponse.json({ link_token: response.data.link_token });<br>  } catch (error) {<br>    return NextResponse.json({ error: &#39;Error generating link token&#39; }, { status: 500 });<br>  }<br>}</pre><h4>Exchange Public Token for Access Token</h4><p>Create a file app/api/plaid/exchange-token/route.ts:</p><pre>import { NextRequest, NextResponse } from &#39;next/server&#39;; <br>import { Configuration, PlaidApi, PlaidEnvironments, Products, CountryCode } from &#39;plaid&#39;;<br><br>const client = new PlaidApi(config);<br>export async function POST(req: NextRequest) {<br>  const { public_token } = await req.json();<br>  try {<br>    const response = await client.itemPublicTokenExchange({ public_token });<br>    const { access_token } = response.data;<br>    return NextResponse.json({ access_token });<br>  } catch (error) {<br>    return NextResponse.json({ error: &#39;Error exchanging public token&#39; }, { status: 500 });<br>  }<br>}</pre><h3>5. Create a Frontend Component to Connect Plaid Link</h3><p>Now we create the Plaid Link component.</p><p>For example, create a file app/(auth)/plaid-link/page.tsx:</p><pre>&quot;use client&quot;<br>import { useState, useEffect } from &#39;react&#39;;<br>import { usePlaidLink } from &#39;react-plaid-link&#39;;<br>import axios from &#39;axios&#39;;<br>const PlaidLinkComponent = () =&gt; {<br>  const [linkToken, setLinkToken] = useState&lt;string | null&gt;(null);<br>  useEffect(() =&gt; {<br>    const createLinkToken = async () =&gt; {<br>      try {<br>        const response = await axios.post(&#39;/api/plaid/create-link-token&#39;, {<br>          client_user_id: &#39;your-unique-user-id&#39;, // Replace with actual user ID<br>        });<br>        setLinkToken(response.data.link_token);<br>      } catch (error) {<br>        console.error(&#39;Error generating link token:&#39;, error);<br>      }<br>    };<br>    createLinkToken();<br>  }, []);<br>  const onSuccess = async (public_token: string) =&gt; {<br>    try {<br>      const response = await axios.post(&#39;/api/plaid/exchange-token&#39;, {<br>        public_token,<br>      });<br>      console.log(&#39;Access Token:&#39;, response.data.access_token);<br>    } catch (error) {<br>      console.error(&#39;Error exchanging public token:&#39;, error);<br>    }<br>  };<br>  const { open, ready } = usePlaidLink({<br>    token: linkToken!,<br>    onSuccess,<br>  });<br>  return (<br>    &lt;div&gt;<br>      {linkToken &amp;&amp; (<br>        &lt;button onClick={open} disabled={!ready}&gt;<br>          Connect Bank<br>        &lt;/button&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>};<br>export default PlaidLinkComponent;</pre><h3>6. Testing</h3><p>Plaid provides a sandbox environment for testing within the <strong>Plaid development environment</strong>. Use the following test credentials when testing in sandbox mode:</p><ul><li><strong>Username</strong>: user_good</li><li><strong>Password</strong>: pass_good</li><li>Select any bank from the list that appears.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=356b547b5a4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Speech-to-Text with OpenAI in Next.js 14 | Medium]]></title>
            <link>https://medium.com/@nazardubovyk/creating-voice-input-with-openai-api-and-next-js-14-ff398c60e5b4?source=rss-fc8da44ff6c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff398c60e5b4</guid>
            <category><![CDATA[openai-api]]></category>
            <category><![CDATA[speech-to-text-api]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Nazar]]></dc:creator>
            <pubDate>Mon, 27 Nov 2023 17:47:05 GMT</pubDate>
            <atom:updated>2023-11-28T16:16:37.685Z</atom:updated>
            <content:encoded><![CDATA[<h3>Article Outline</h3><p><strong>1. Project Initialization</strong></p><ul><li>Initializing Next.js</li><li>Installing necessary dependencies such as openai</li></ul><p><strong>2. Creating the `useRecordVoice` Hook</strong></p><ul><li>Developing a hook for voice recording</li><li>Utilizing the MediaRecorder API</li></ul><p><strong>3. Creating the Button Component</strong></p><ul><li>Building a button component for controlling voice recording</li></ul><p><strong>4.</strong> <strong>Checking Functionality</strong></p><ul><li>Running the project and verifying essential functions</li></ul><p><strong>5. Setting up the Speech Recognition API</strong></p><ul><li>Creating an API endpoint for processing audio data and interacting with the OpenAI API</li></ul><p><strong>6. Additional Features and Enhancements</strong></p><ul><li>Developing helper functions for audio and base64 conversion</li><li>Implementing additional features to obtain textual output</li></ul><h3>1. Project Initialization</h3><p>To start, initialize a Next.js project and install necessary dependencies, including openai.</p><p><a href="https://nextjs.org/docs/getting-started/installation">Initializing a Next.js project</a></p><pre>npx create-next-app my-voice-app</pre><p>Installing necessary dependencies ( <a href="https://www.npmjs.com/package/openai/v/4.0.0-beta.0">openai</a> v4, <a href="https://www.npmjs.com/package/dotenv">dotenv</a> )</p><pre>npm install openai dotenv</pre><h3>2. Creating the useRecordVoice Hook</h3><p>Create a hook for convenient voice recording and use the MediaRecorder API.</p><pre>import { useEffect, useState, useRef } from &quot;react&quot;;<br><br>export const useRecordVoice = () =&gt; {<br>  // State to hold the media recorder instance<br>  const [mediaRecorder, setMediaRecorder] = useState(null);<br><br>  // State to track whether recording is currently in progress<br>  const [recording, setRecording] = useState(false);<br><br>  // Ref to store audio chunks during recording<br>  const chunks = useRef([]);<br><br>  // Function to start the recording<br>  const startRecording = () =&gt; {<br>    if (mediaRecorder) {<br>      mediaRecorder.start();<br>      setRecording(true);<br>    }<br>  };<br><br>  // Function to stop the recording<br>  const stopRecording = () =&gt; {<br>    if (mediaRecorder) {<br>      mediaRecorder.stop(); <br>      setRecording(false);<br>    }<br>  };<br><br>  // Function to initialize the media recorder with the provided stream<br>  const initialMediaRecorder = (stream) =&gt; {<br>    const mediaRecorder = new MediaRecorder(stream);<br><br>    // Event handler when recording starts<br>    mediaRecorder.onstart = () =&gt; {<br>      chunks.current = []; // Resetting chunks array<br>    };<br><br>    // Event handler when data becomes available during recording<br>    mediaRecorder.ondataavailable = (ev) =&gt; {<br>      chunks.current.push(ev.data); // Storing data chunks<br>    };<br><br>    // Event handler when recording stops<br>    mediaRecorder.onstop = () =&gt; {<br>      // Creating a blob from accumulated audio chunks with WAV format<br>      const audioBlob = new Blob(chunks.current, { type: &quot;audio/wav&quot; });<br>      console.log(audioBlob, &#39;audioBlob&#39;)<br><br>      // You can do something with the audioBlob, like sending it to a server or processing it further<br>    };<br><br>    setMediaRecorder(mediaRecorder);<br>  };<br><br>  useEffect(() =&gt; {<br>    if (typeof window !== &quot;undefined&quot;) {<br>      navigator.mediaDevices<br>        .getUserMedia({ audio: true })<br>        .then(initialMediaRecorder);<br>    }<br>  }, []); <br><br>  return { recording, startRecording, stopRecording<br> };<br>};</pre><h3>3. Creating the Button Component</h3><p>Develop a button component for starting and stopping voice recording.</p><pre>&quot;use client&quot;;<br><br>import { useRecordVoice } from &quot;@/hooks/useRecordVoice&quot;;<br>import { IconMicrophone } from &quot;@/app/components/IconMicrophone&quot;;<br><br>const Microphone = () =&gt; {<br>  const { startRecording, stopRecording } = useRecordVoice();<br><br>  return (<br>    // Button for starting and stopping voice recording<br>    &lt;button<br>      onMouseDown={startRecording}    // Start recording when mouse is pressed<br>      onMouseUp={stopRecording}        // Stop recording when mouse is released<br>      onTouchStart={startRecording}    // Start recording when touch begins on a touch device<br>      onTouchEnd={stopRecording}        // Stop recording when touch ends on a touch device<br>      className=&quot;border-none bg-transparent w-10&quot;<br>    &gt;<br>      {/* Microphone icon component */}<br>      &lt;IconMicrophone /&gt;<br>    &lt;/button&gt;<br>  );<br>};<br><br>export { Microphone };</pre><h3>4. Checking Functionality</h3><p>Run the project and check basic functionality.</p><pre>npm run dev</pre><p>Open <a href="http://localhost:3000/">http://localhost:3000/</a> in your browser and ensure that the microphone permission prompt appears.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*spdQ-SMSTLRYfN5vEysesA.png" /></figure><p>Next, the microphone indicator should light up in your browser tab, indicating that you did everything right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*3G3MnKVGSBSXGcPGijxbAQ.png" /></figure><p>Next, hold down the <em>microphone</em> and say anything, after which you should see something similar to this in the <em>console</em>, only yours may be different in <em>size.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*RubGQp5scy_QegTjukPEnA.png" /></figure><h3>5. Setting up the Speech Recognition API</h3><p>Create an API endpoint for processing audio data and interacting with the OpenAI API.</p><p>In the <strong><em>src/app/api/speechToText/route.js</em></strong> folder, I will create the <strong><em>speechToText</em></strong> api.</p><pre>import { NextResponse } from &quot;next/server&quot;;<br>import fs from &quot;fs&quot;;<br>import * as dotenv from &quot;dotenv&quot;; <br>import OpenAI from &quot;openai&quot;;<br>import { env } from &quot;../../config/env&quot;;<br><br>dotenv.config();<br><br>const openai = new OpenAI({<br>  apiKey: env.OPENAI_API_KEY,<br>});<br><br>export async function POST(req) {<br>  const body = await req.json();<br><br>  const base64Audio = body.audio;<br><br>  // Convert the base64 audio data to a Buffer<br>  const audio = Buffer.from(base64Audio, &quot;base64&quot;);<br><br>  // Define the file path for storing the temporary WAV file<br>  const filePath = &quot;tmp/input.wav&quot;;<br><br>  try {<br>    // Write the audio data to a temporary WAV file synchronously<br>    fs.writeFileSync(filePath, audio);<br><br>    // Create a readable stream from the temporary WAV file<br>    const readStream = fs.createReadStream(filePath);<br><br>    const data = await openai.audio.transcriptions.create({<br>      file: readStream,<br>      model: &quot;whisper-1&quot;,<br>    });<br><br>    // Remove the temporary file after successful processing<br>    fs.unlinkSync(filePath);<br><br>    return NextResponse.json(data);<br>  } catch (error) {<br>    console.error(&quot;Error processing audio:&quot;, error);<br>    return NextResponse.error();<br>  }<br>}</pre><p>In short, what happens here is that we create a file into which we write base64Audio and then read it and, after a successful request, delete the file.</p><blockquote>Also, be sure to create a <strong>tmp</strong> folder on the same level as <strong>src </strong>and add .<strong>gitignore</strong> so that you can commit this folder and push.</blockquote><h3>6. Additional Features and Enhancements</h3><p>Add helper functions for audio and base64 conversion and improve functionality.</p><p><strong><em>blobToBase64</em></strong></p><pre>//callback - where we want to get result<br>const blobToBase64 = (blob, callback) =&gt; {<br>  const reader = new FileReader();<br>  reader.onload = function () {<br>    const base64data = reader?.result?.split(&quot;,&quot;)[1];<br>    callback(base64data);<br>  };<br>  reader.readAsDataURL(blob);<br>};<br><br>export { blobToBase64 };</pre><p><strong><em>createMediaStream</em></strong></p><pre>// Function to calculate the peak level from the analyzer data<br>const getPeakLevel = (analyzer) =&gt; {<br>  // Create a Uint8Array to store the audio data<br>  const array = new Uint8Array(analyzer.fftSize);<br><br>  // Get the time domain data from the analyzer and store it in the array<br>  analyzer.getByteTimeDomainData(array);<br><br>  // Calculate the peak level by finding the maximum absolute deviation from 127<br>  return (<br>    array.reduce((max, current) =&gt; Math.max(max, Math.abs(current - 127)), 0) /<br>    128<br>  );<br>};<br><br>const createMediaStream = (stream, isRecording, callback) =&gt; {<br>  // Create a new AudioContext<br>  const context = new AudioContext();<br><br>  // Create a media stream source node from the input stream<br>  const source = context.createMediaStreamSource(stream);<br><br>  // Create an analyzer node for audio analysis<br>  const analyzer = context.createAnalyser();<br><br>  // Connect the source node to the analyzer node<br>  source.connect(analyzer);<br><br>  // Function to continuously analyze audio data and invoke the callback<br>  const tick = () =&gt; {<br>    // Calculate the peak level using the getPeakLevel function<br>    const peak = getPeakLevel(analyzer);<br><br>    if (isRecording) {<br>      callback(peak);<br><br>      // Request the next animation frame for continuous analysis<br>      requestAnimationFrame(tick);<br>    }<br>  };<br><br>  // Start the continuous analysis loop<br>  tick();<br>};<br><br>export { createMediaStream };</pre><blockquote>You can learn more about the built-in <strong>requestAnimationFrame</strong> js method <a href="https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame"><strong>here</strong></a><strong>.</strong></blockquote><p>Great now let’s use our <strong>helpers</strong> and <strong>speechToText</strong> api in <strong>useRecordVoice.</strong></p><pre>&quot;use client&quot;;<br>import { useEffect, useState, useRef } from &quot;react&quot;;<br>import { blobToBase64 } from &quot;@/utils/blobToBase64&quot;;<br>import { createMediaStream } from &quot;@/utils/createMediaStream&quot;;<br><br>export const useRecordVoice = () =&gt; {<br>  const [text, setText] = useState(&quot;&quot;);<br>  const [mediaRecorder, setMediaRecorder] = useState(null);<br>  const [recording, setRecording] = useState(false);<br>  const isRecording = useRef(false);<br>  const chunks = useRef([]);<br><br>  const startRecording = () =&gt; {<br>    if (mediaRecorder) {<br>      isRecording.current = true;<br>      mediaRecorder.start();<br>      setRecording(true);<br>    }<br>  };<br><br>  const stopRecording = () =&gt; {<br>    if (mediaRecorder) {<br>      isRecording.current = false;<br>      mediaRecorder.stop();<br>      setRecording(false);<br>    }<br>  };<br><br>  const getText = async (base64data) =&gt; {<br>    try {<br>      const response = await fetch(&quot;/api/speechToText&quot;, {<br>        method: &quot;POST&quot;,<br>        headers: {<br>          &quot;Content-Type&quot;: &quot;application/json&quot;,<br>        },<br>        body: JSON.stringify({<br>          audio: base64data,<br>        }),<br>      }).then((res) =&gt; res.json());<br>      const { text } = response;<br>      setText(text);<br>    } catch (error) {<br>      console.log(error);<br>    }<br>  };<br><br>  const initialMediaRecorder = (stream) =&gt; {<br>    const mediaRecorder = new MediaRecorder(stream);<br><br>    mediaRecorder.onstart = () =&gt; {<br>      createMediaStream(stream)<br>      chunks.current = [];<br>    };<br><br>    mediaRecorder.ondataavailable = (ev) =&gt; {<br>      chunks.current.push(ev.data);<br>    };<br><br>    mediaRecorder.onstop = () =&gt; {<br>      const audioBlob = new Blob(chunks.current, { type: &quot;audio/wav&quot; });<br>      blobToBase64(audioBlob, getText);<br>    };<br><br>    setMediaRecorder(mediaRecorder);<br>  };<br><br>  useEffect(() =&gt; {<br>    if (typeof window !== &quot;undefined&quot;) {<br>      navigator.mediaDevices<br>        .getUserMedia({ audio: true })<br>        .then(initialMediaRecorder);<br>    }<br>  }, []);<br><br>  return { recording, startRecording, stopRecording, text };<br>};</pre><p>After that, go to our <strong>Microphone</strong> component and add the output of our text.</p><pre>const Microphone = () =&gt; {<br>  const { startRecording, stopRecording, text } = useRecordVoice();<br><br>  return (<br>    &lt;div className=&quot;flex flex-col justify-center items-center&quot;&gt;<br>      &lt;button<br>        onMouseDown={startRecording}<br>        onMouseUp={stopRecording}<br>        onTouchStart={startRecording}<br>        onTouchEnd={stopRecording}<br>        className=&quot;border-none bg-transparent w-10&quot;<br>      &gt;<br>        &lt;IconMicrophone /&gt;<br>      &lt;/button&gt;<br>      &lt;p&gt;{text}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export { Microphone };</pre><p>Save your changes and restart the server.</p><p>Next, go to the <a href="http://localhost:3000/">http://localhost:3000/</a> and do the following:</p><ol><li>Press the microphone button</li><li>And say, “Hello world”</li></ol><p><strong>Result:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*QG3-L6WGfPmMetGwX5rPnQ.png" /></figure><p>That’s it! You should now have a fully functional voice input in your Next.js project.</p><p>Link to GitHub where you can learn more about the structure and code <a href="https://github.com/ZaharBerku/openai-speech-to-text"><strong>here</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff398c60e5b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>