<?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 Awa Dieudonne on Medium]]></title>
        <description><![CDATA[Stories by Awa Dieudonne on Medium]]></description>
        <link>https://medium.com/@dieudonneawa7?source=rss-62b1eded11ae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wKaoZOrG7K2AWGWpU6NM5w.jpeg</url>
            <title>Stories by Awa Dieudonne on Medium</title>
            <link>https://medium.com/@dieudonneawa7?source=rss-62b1eded11ae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 17:52:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dieudonneawa7/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[How to build a GPT-3 powered chatbot in Next.js]]></title>
            <link>https://dieudonneawa7.medium.com/how-to-build-a-gpt-3-powered-chatbot-in-next-js-78e0107a99fb?source=rss-62b1eded11ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/78e0107a99fb</guid>
            <category><![CDATA[gpt-3]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[chatbot-development]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Awa Dieudonne]]></dc:creator>
            <pubDate>Thu, 09 Feb 2023 13:08:52 GMT</pubDate>
            <atom:updated>2023-02-09T13:15:50.623Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2TU-H3zS2be29xDzCfMsAw.png" /></figure><p>This tutorial will guide you through the process of building a chatbot using Next.js and GPT-3’s API from OpenAI that can understand and respond to user queries similar to the way ChatGPT does it.</p><blockquote><strong>Check out the full article originally published on </strong><a href="https://awacreates.com/blog/build-a-chatbot-using-gpt-3s-api-and-nextjs"><strong>Awa Creates</strong></a></blockquote><p>If you don’t know what GPT-3 is, head over to the <a href="https://beta.openai.com/docs/models/gpt-3">Open AI GPT-3 documentation</a>.</p><p>By the end of this tutorial, you should have a fully functional chatbot that can understand and respond to a wide range of user queries.</p><p>Whether you’re a developer looking to add a new tool to your skill set [just like me], or a business owner looking to improve customer engagement, this tutorial is for you.</p><h3>Setup Next.js and Chakra UI project</h3><p>The following prerequisites are required for us to start building our GPT bot:</p><ol><li>A Next.js application. If you don’t have one, you can create a new Next.js app using the following command:<br>`npx create-next-app my-chatbot`<br>Or you can simply clone one of the <a href="https://vercel.com/templates/next.js">Next.js starter templates from vercel</a>.</li><li>Chakra UI configured on the Next.js application. You can follow this link to set it up: <a href="https://chakra-ui.com/getting-started/nextjs-guide">Next.js Chakra installation guide</a>.</li><li>Configure a Chakra UI theme for the application. You can do that by creating a theme.js file in the src folder and pasting the following code:</li></ol><pre>// theme.ts<br>import { extendTheme, theme as defaultTheme } from &quot;@chakra-ui/react&quot;;<br><br>const fonts = {<br>  heading:<br>    &quot;-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif&quot;,<br>  body: &quot;-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif&quot;,<br>};<br><br>export const colors = {<br>  ...defaultTheme.colors,<br>  blue: {<br>    500: &quot;#5686f5&quot;,<br>    400: &quot;#1c2433&quot;,<br>  },<br>  &quot;button-color&quot;: &quot;#222730&quot;,<br>  &quot;border-color&quot;: &quot;#2b303b&quot;,<br>  &quot;main-bg&quot;: &quot;#16181d&quot;,<br>  &quot;main-color&quot;: &quot;#bbc3d3&quot;<br>};<br><br>const theme = extendTheme({<br>  ...defaultTheme,<br>  colors,<br>  fonts,<br>});<br><br>export default theme;</pre><p>We’ve extended the chakra theme with some custom colors and fonts for our application.</p><h3>What is GPT-3?</h3><p>GPT-3 (Generative Pre-training Transformer 3) is a cutting-edge language processing model developed by OpenAI. It uses machine-learning techniques to generate human-like text.</p><h3>How was GPT-3 trained?</h3><p>Training GPT-3 involved a deep learning technique called <a href="https://en.wikipedia.org/wiki/Transformer_(machine_learning_model)">Transformer architecture</a> and unsupervised learning on a massive amount of text data gotten from the internet.</p><p>The text data is pre-processed and tokenized into individual words or chunks of characters and then fed into the Transformer network, which uses self-attention mechanisms to generate a representation of the input text. This representation is then used to predict the next word in the sequence based on previous words.</p><p>The text data used to train GPT-3 is obtained from the internet, specifically from websites, books, and other digital documents. OpenAI uses web scraping techniques to collect a large amount of text data, which is then pre-processed to clean and filter the data for quality and relevance.</p><p>The pre-processing step involves removing irrelevant information such as HTML tags, special characters, and non-text elements. The text data that remains after removing the irrelevant information is then tokenized into individual words or sub-words, and the resulting sequence of tokens is used as input for the training process.</p><h3>Setup Open AI in Next.js and generate API key</h3><p>In order to setup Open AI in our next.js project, we are going to install the openai node.js library from npm using the command:</p><pre>yarn add openai</pre><blockquote><strong><em>Important note:</em></strong><em> this library is meant for server-side usage only, as using it in client-side browser code will expose your secret API key. Visit the </em><a href="https://platform.openai.com/docs/api-reference/introduction"><em>API reference</em></a><em> for more details.</em></blockquote><p>In order to configure the library, we will need to generate an API key. Head over to the <a href="https://platform.openai.com/">Open AI platform</a>, sign up, and generate an API key if you don’t have it yet.</p><p>Once you’ve generated the API key, create a .env.local file and set the Open AI API key as follows:</p><pre># .env.local<br>OPENAI_API_KEY=&quot;sk-your-api-key&quot;</pre><p>You can now replace sk-your-api-key with the API key generated from the Open AI website.</p><h3>Create Next.js API route with GPT-3 configuration</h3><p>The next thing to do is we are going to create a Next.js API route inside pages/api directory.</p><p>In pages/api directory, create a new file and name it generate.ts, and paste in the following code:</p><pre>// pages/api/generate.ts<br>import { NextApiRequest, NextApiResponse } from &quot;next&quot;;<br>import { Configuration, OpenAIApi } from &quot;openai&quot;;<br><br>const configuration = new Configuration({<br>  apiKey: process.env.OPENAI_API_KEY,<br>});<br>const openai = new OpenAIApi(configuration);<br><br>export default async function handler(<br>  req: NextApiRequest,<br>  res: NextApiResponse<br>) {<br>  if (!configuration.apiKey) {<br>    res.status(500).json({<br>      error: {<br>        message:<br>          &quot;OpenAI API key not configured, please follow instructions in README.md&quot;,<br>      },<br>    });<br>    return;<br>  }<br><br>  const message = req.body.message;<br><br>  try {<br>    const completion = await openai.createCompletion({<br>      model: &quot;text-davinci-003&quot;,<br>      prompt: message,<br>      temperature: 0.6,<br>      max_tokens: 3500,<br>    });<br>    res.status(200).json({ result: completion.data.choices[0].text });<br>  } catch (error: any) {<br>    // Consider adjusting the error handling logic for your use case<br>    if (error.response) {<br>      console.error(error.response.status, error.response.data);<br>      res.status(error.response.status).json(error.response.data);<br>    } else {<br>      console.error(`Error with OpenAI API request: ${error.message}`);<br>      res.status(500).json({<br>        error: {<br>          message: &quot;An error occurred during your request.&quot;,<br>        },<br>      });<br>    }<br>  }<br>}</pre><p>The initial lines in the file contain the configuration for the openai node library. We are instantiating an OpenAIApi class to create an instance of the openai object.</p><p>Then, we have our exported async handler function. The function starts by checking if the configuration.apiKey is present. If not, it sets the response status to 500 (Internal Server Error) and returns an error message, indicating that the OpenAI API key has not been configured.</p><p>If the API key is present, the function extracts message from the request body, and uses the openai object to create a completion by calling the createCompletion method. The method takes in an object that specifies the parameters for the completion request, including the name of the model to use, the prompt text, the temperature, and the maximum number of tokens to generate.</p><p>If the completion request is successful, the response status is set to 200 (OK) and the JSON result is returned with the first choice’s text.</p><p>If there’s an error with the API request, the error handling logic checks if the error has a response property. If so, the error status and data are logged to the console and returned as the response. If not, a 500 error status with a generic error message is returned.</p><h3>Create a client that will consume the API route</h3><p>To kick off, let’s install react-markdown, a React component that can display Markdown content. We are utilizing it as the output from the OpenAI API is typically in Markdown format.</p><pre>yarn add react-markdown</pre><p>Subsequently, we will create a chat component in the components folder within the src directory, specifically at src/components/Chat.tsx.</p><pre>// src/components/Chat.tsx<br>import { Avatar, Flex } from &quot;@chakra-ui/react&quot;;<br>import { useEffect, useRef, useState } from &quot;react&quot;;<br>import { ReactMarkdown } from &quot;react-markdown/lib/react-markdown&quot;;<br>import { motion } from &quot;framer-motion&quot;;<br><br>const Chat = ({ message, user }: { message: string; user: &quot;me&quot; | &quot;gpt&quot; }) =&gt; {<br>  const chatStringIndex = useRef(0);<br>  const [chatMessage, setChatMessage] = useState(&quot;&quot;);<br><br>  function appendChar() {<br>    setChatMessage((prev) =&gt; prev + message[chatStringIndex.current]);<br>    chatStringIndex.current++;<br>  }<br><br>  useEffect(() =&gt; {<br>    if (chatStringIndex.current &lt; message.length - 1) {<br>      const appendCharInterval = setInterval(appendChar, 50);<br>      return () =&gt; clearInterval(appendCharInterval);<br>    }<br>  }, [chatMessage, chatStringIndex.current]);<br><br>  return (<br>    &lt;motion.div<br>      style={{<br>        alignSelf: user === &quot;gpt&quot; ? &quot;flex-start&quot; : &quot;flex-end&quot;,<br>        width: &quot;auto&quot;,<br>        maxWidth: &quot;90%&quot;,<br>      }}<br>      initial={{<br>        opacity: 0,<br>        translateY: &quot;100%&quot;,<br>      }}<br>      animate={{ opacity: 1, translateY: 0, transition: { duration: 0.3 } }}<br>      exit={{ opacity: 0, translateY: 0 }}<br>    &gt;<br>      &lt;Flex gap=&quot;5px&quot; w=&quot;full&quot; flexDir={user === &quot;gpt&quot; ? &quot;row&quot; : &quot;row-reverse&quot;}&gt;<br>        &lt;Avatar<br>          name={user === &quot;me&quot; ? &quot;Me&quot; : &quot;GPT&quot;}<br>          size=&quot;sm&quot;<br>          bg=&quot;border-color&quot;<br>          mt=&quot;-6px&quot;<br>        /&gt;<br>        &lt;Flex<br>          borderWidth={1}<br>          borderColor=&quot;blue.400&quot;<br>          bg=&quot;main-bg&quot;<br>          p=&quot;0.5rem 1rem&quot;<br>          w=&quot;auto&quot;<br>          rounded={user === &quot;gpt&quot; ? &quot;0 20px 20px 20px&quot; : &quot;20px 0 20px 20px&quot;}<br>          fontSize=&quot;18px&quot;<br>          flexDir=&quot;column&quot;<br>        &gt;<br>          {user === &quot;gpt&quot; &amp;&amp; (<br>            &lt;Flex<br>              alignSelf=&quot;flex-end&quot;<br>              fontStyle=&quot;italic&quot;<br>              opacity={0.4}<br>              fontSize=&quot;10px&quot;<br>              as=&quot;small&quot;<br>              fontWeight={500}<br>            &gt;<br>              GPT<br>            &lt;/Flex&gt;<br>          )}<br>          {user === &quot;me&quot; &amp;&amp; (<br>            &lt;Flex<br>              alignSelf=&quot;flex-start&quot;<br>              fontStyle=&quot;italic&quot;<br>              opacity={0.4}<br>              fontSize=&quot;10px&quot;<br>              as=&quot;small&quot;<br>              fontWeight={500}<br>            &gt;<br>              Me<br>            &lt;/Flex&gt;<br>          )}<br>          &lt;ReactMarkdown rehypePlugins={[]}&gt;<br>            {user === &quot;gpt&quot; ? chatMessage || &quot;&quot; : message || &quot;&quot;}<br>          &lt;/ReactMarkdown&gt;<br>        &lt;/Flex&gt;<br>      &lt;/Flex&gt;<br>    &lt;/motion.div&gt;<br>  );<br>};<br><br>export default Chat;</pre><p>In this component, we’re rendering a chat box that consists of a space for the message, and the entity (me or GPT) posting the chat.</p><p>Within the component, we have the code snippet below. What the snippet does is basically animates the display of the message string by gradually concatenating characters from the string to the chatMessage state. As a result, we will have something similar to the way ChatGPT renders responses.</p><pre>// src/components/Chat.tsx<br><br>...<br>  const chatStringIndex = useRef(0);<br>  const [chatMessage, setChatMessage] = useState(&quot;&quot;);<br><br>  function appendChar() {<br>    setChatMessage((prev) =&gt; prev + message[chatStringIndex.current]);<br>    chatStringIndex.current++;<br>  }<br><br>  useEffect(() =&gt; {<br>    if (chatStringIndex.current &lt; message.length - 1) {<br>      const appendCharInterval = setInterval(appendChar, 50);<br>      return () =&gt; clearInterval(appendCharInterval);<br>    }<br>  }, [chatMessage, chatStringIndex.current]);<br>...</pre><p>That is going to give us the following animation on the chat component.</p><p>Let’s also create an `InputField` component still in the `components` directory.</p><pre>import { Box, Flex, Input, InputProps } from &quot;@chakra-ui/react&quot;;<br>import React from &quot;react&quot;;<br>import PlaneIcon from &quot;../icons/PlaneIcon&quot;;<br>import { colors } from &quot;../theme&quot;;<br><br>type Props = {<br>  onSubmit: (e: React.MouseEvent&lt;HTMLElement&gt;) =&gt; Promise&lt;void&gt;;<br>  inputProps: InputProps;<br>};<br><br>const InputField = (props: Props) =&gt; {<br>  const { onSubmit, inputProps } = props;<br><br>  return (<br>    &lt;Flex<br>      maxW=&quot;800px&quot;<br>      as=&quot;form&quot;<br>      w=&quot;full&quot;<br>      mx=&quot;auto&quot;<br>      borderWidth={1}<br>      borderColor=&quot;transparent&quot;<br>      _focusWithin={{ borderColor: &quot;blue.500&quot; }}<br>      bg=&quot;border-color&quot;<br>      rounded=&quot;md&quot;<br>      align=&quot;center&quot;<br>      pr=&quot;8px&quot;<br>      boxShadow=&quot;md&quot;<br>    &gt;<br>      &lt;Input<br>        p=&quot;1rem&quot;<br>        h=&quot;60px&quot;<br>        borderColor=&quot;border-color&quot;<br>        _hover={{ outline: &quot;unset&quot; }}<br>        _focus={{ outline: &quot;unset&quot; }}<br>        _focusVisible={{ borderColor: &quot;transparent&quot; }}<br>        resize=&quot;none&quot;<br>        {...inputProps}<br>      /&gt;<br>      &lt;Box<br>        p=&quot;8px&quot;<br>        as=&quot;button&quot;<br>        rounded=&quot;md&quot;<br>        transition=&quot;all ease 0.2s&quot;<br>        _hover={{ bg: &quot;main-bg&quot; }}<br>        onClick={onSubmit}<br>      &gt;<br>        &lt;PlaneIcon fill={colors[&quot;main-color&quot;]} /&gt;<br>      &lt;/Box&gt;<br>    &lt;/Flex&gt;<br>  );<br>};<br><br>export default InputField;</pre><p>This component expects just two props — the `onSubmit` and `inputProps`. The `onSubmit` handler gets called when the `PlaneIcon` icon is clicked or the user hits the `enter` or `return` key.</p><p>And `inputProps` are just properties of the input element.</p><pre>// src/icons/PlaneIcon.tsx<br>import React from &quot;react&quot;;<br><br>const PlaneIcon = ({ fill = &quot;#2b303b&quot;, ...rest }: any) =&gt; {<br>  return (<br>    &lt;svg<br>      width=&quot;20&quot;<br>      height=&quot;20&quot;<br>      viewBox=&quot;0 0 20 20&quot;<br>      fill=&quot;none&quot;<br>      xmlns=&quot;http://www.w3.org/2000/svg&quot;<br>      {...rest}<br>    &gt;<br>      &lt;path<br>        fillRule=&quot;evenodd&quot;<br>        clipRule=&quot;evenodd&quot;<br>        d=&quot;M8.80494 11.8178L12.4619 17.7508C12.6219 18.0108 12.8719 18.0078 12.9729 17.9938C13.0739 17.9798 13.3169 17.9178 13.4049 17.6228L17.9779 2.17777C18.0579 1.90477 17.9109 1.71877 17.8449 1.65277C17.7809 1.58677 17.5979 1.44577 17.3329 1.52077L1.87695 6.04677C1.58394 6.13277 1.51994 6.37877 1.50594 6.47977C1.49194 6.58277 1.48794 6.83777 1.74695 7.00077L7.74794 10.7538L13.0499 5.39577C13.3409 5.10177 13.8159 5.09877 14.1109 5.38977C14.4059 5.68077 14.4079 6.15677 14.1169 6.45077L8.80494 11.8178ZM12.8949 19.4998C12.1989 19.4998 11.5609 19.1458 11.1849 18.5378L7.30794 12.2468L0.951945 8.27177C0.266945 7.84277 -0.091055 7.07877 0.019945 6.27577C0.129945 5.47277 0.680945 4.83477 1.45494 4.60777L16.9109 0.0817716C17.6219 -0.126228 18.3839 0.0707716 18.9079 0.592772C19.4319 1.11977 19.6269 1.88977 19.4149 2.60377L14.8419 18.0478C14.6129 18.8248 13.9729 19.3738 13.1719 19.4808C13.0779 19.4928 12.9869 19.4998 12.8949 19.4998Z&quot;<br>        fill={fill}<br>      /&gt;<br>    &lt;/svg&gt;<br>  );<br>};<br><br>export default PlaneIcon;</pre><p>At once, we’re going to also create the loader for the chats. This loader is rendered as API request to Open AI is in progress.</p><pre>// src/icons/ThreeDotsLoader.tsx<br>import React from &quot;react&quot;;<br><br>const ThreeDotsLoader = () =&gt; {<br>  return (<br>    &lt;svg<br>      xmlns=&quot;http://www.w3.org/2000/svg&quot;<br>      xmlnsXlink=&quot;http://www.w3.org/1999/xlink&quot;<br>      style={{ margin: &quot;auto&quot;, background: &quot;none&quot;, display: &quot;block&quot;, shapeRendering: &quot;auto&quot; }}<br>      width=&quot;30px&quot;<br>      height=&quot;30px&quot;<br>      viewBox=&quot;0 0 100 100&quot;<br>      preserveAspectRatio=&quot;xMidYMid&quot;<br>    &gt;<br>      &lt;circle cx=&quot;84&quot; cy=&quot;50&quot; r=&quot;10&quot; fill=&quot;rgba(255, 255, 255, 0.2)&quot;&gt;<br>        &lt;animate<br>          attributeName=&quot;r&quot;<br>          repeatCount=&quot;indefinite&quot;<br>          dur=&quot;0.7352941176470588s&quot;<br>          calcMode=&quot;spline&quot;<br>          keyTimes=&quot;0;1&quot;<br>          values=&quot;10;0&quot;<br>          keySplines=&quot;0 0.5 0.5 1&quot;<br>          begin=&quot;0s&quot;<br>        &gt;&lt;/animate&gt;<br>        &lt;animate<br>          attributeName=&quot;fill&quot;<br>          repeatCount=&quot;indefinite&quot;<br>          dur=&quot;2.941176470588235s&quot;<br>          calcMode=&quot;discrete&quot;<br>          keyTimes=&quot;0;0.25;0.5;0.75;1&quot;<br>          values=&quot;rgba(255, 255, 255, 0.4);rgba(255, 255, 255, 0.9999);rgba(255, 255, 255, 0.8);&quot;<br>          begin=&quot;0s&quot;<br>        &gt;&lt;/animate&gt;<br>      &lt;/circle&gt;<br>      &lt;circle cx=&quot;16&quot; cy=&quot;50&quot; r=&quot;10&quot; fill=&quot;rgba(255, 255, 255, 0.4)&quot;&gt;<br>        &lt;animate<br>          attributeName=&quot;r&quot;<br>          repeatCount=&quot;indefinite&quot;<br>          dur=&quot;2.941176470588235s&quot;<br>          calcMode=&quot;spline&quot;<br>          keyTimes=&quot;0;0.25;0.5;0.75;1&quot;<br>          values=&quot;0;0;10;10;10&quot;<br>          keySplines=&quot;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1&quot;<br>          begin=&quot;0s&quot;<br>        &gt;&lt;/animate&gt;<br>        &lt;animate<br>          attributeName=&quot;cx&quot;<br>          repeatCount=&quot;indefinite&quot;<br>          dur=&quot;2.941176470588235s&quot;<br>          calcMode=&quot;spline&quot;<br>          keyTimes=&quot;0;0.25;0.5;0.75;1&quot;<br>          values=&quot;16;16;16;50;84&quot;<br>          keySplines=&quot;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1&quot;<br>          begin=&quot;0s&quot;<br>        &gt;&lt;/animate&gt;<br>      &lt;/circle&gt;<br>      &lt;circle cx=&quot;50&quot; cy=&quot;50&quot; r=&quot;10&quot; fill=&quot;rgba(255, 255, 255, 0.6)&quot;&gt;<br>        &lt;animate<br>          attributeName=&quot;r&quot;<br>          repeatCount=&quot;indefinite&quot;<br>          dur=&quot;2.941176470588235s&quot;<br>          calcMode=&quot;spline&quot;<br>          keyTimes=&quot;0;0.25;0.5;0.75;1&quot;<br>          values=&quot;0;0;10;10;10&quot;<br>          keySplines=&quot;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1&quot;<br>          begin=&quot;-0.7352941176470588s&quot;<br>        &gt;&lt;/animate&gt;<br>        &lt;animate<br>          attributeName=&quot;cx&quot;<br>          repeatCount=&quot;indefinite&quot;<br>          dur=&quot;2.941176470588235s&quot;<br>          calcMode=&quot;spline&quot;<br>          keyTimes=&quot;0;0.25;0.5;0.75;1&quot;<br>          values=&quot;16;16;16;50;84&quot;<br>          keySplines=&quot;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1&quot;<br>          begin=&quot;-0.7352941176470588s&quot;<br>        &gt;&lt;/animate&gt;<br>      &lt;/circle&gt;<br>      &lt;circle cx=&quot;84&quot; cy=&quot;50&quot; r=&quot;10&quot; fill=&quot;rgba(255, 255, 255, 0.8)&quot;&gt;<br>        &lt;animate<br>          attributeName=&quot;r&quot;<br>          repeatCount=&quot;indefinite&quot;<br>          dur=&quot;2.941176470588235s&quot;<br>          calcMode=&quot;spline&quot;<br>          keyTimes=&quot;0;0.25;0.5;0.75;1&quot;<br>          values=&quot;0;0;10;10;10&quot;<br>          keySplines=&quot;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1&quot;<br>          begin=&quot;-1.4705882352941175s&quot;<br>        &gt;&lt;/animate&gt;<br>        &lt;animate<br>          attributeName=&quot;cx&quot;<br>          repeatCount=&quot;indefinite&quot;<br>          dur=&quot;2.941176470588235s&quot;<br>          calcMode=&quot;spline&quot;<br>          keyTimes=&quot;0;0.25;0.5;0.75;1&quot;<br>          values=&quot;16;16;16;50;84&quot;<br>          keySplines=&quot;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1&quot;<br>          begin=&quot;-1.4705882352941175s&quot;<br>        &gt;&lt;/animate&gt;<br>      &lt;/circle&gt;<br>      &lt;circle cx=&quot;16&quot; cy=&quot;50&quot; r=&quot;10&quot; fill=&quot;rgba(255, 255, 255, 0.9999)&quot;&gt;<br>        &lt;animate<br>          attributeName=&quot;r&quot;<br>          repeatCount=&quot;indefinite&quot;<br>          dur=&quot;2.941176470588235s&quot;<br>          calcMode=&quot;spline&quot;<br>          keyTimes=&quot;0;0.25;0.5;0.75;1&quot;<br>          values=&quot;0;0;10;10;10&quot;<br>          keySplines=&quot;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1&quot;<br>          begin=&quot;-2.205882352941176s&quot;<br>        &gt;&lt;/animate&gt;<br>        &lt;animate<br>          attributeName=&quot;cx&quot;<br>          repeatCount=&quot;indefinite&quot;<br>          dur=&quot;2.941176470588235s&quot;<br>          calcMode=&quot;spline&quot;<br>          keyTimes=&quot;0;0.25;0.5;0.75;1&quot;<br>          values=&quot;16;16;16;50;84&quot;<br>          keySplines=&quot;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1;0 0.5 0.5 1&quot;<br>          begin=&quot;-2.205882352941176s&quot;<br>        &gt;&lt;/animate&gt;<br>      &lt;/circle&gt;<br>    &lt;/svg&gt;<br>  );<br>};<br><br>export default ThreeDotsLoader;</pre><p>Lastly, we’re going to update `pages/index.ts` file with the code below. The component has three state variables — the `chats`, `value`, and `isSubmitting`.</p><p>The `chats` state stores the list of conversations within the chatroom in an array of `Chat` objects.<br>The `value` state holds the current value that the user’s text (query/prompt).<br>And the `isSubmitting` state is a boolean indicating that the query/prompt is being processed.</p><p>We’re going to use the `fetch` function to handle the API call to our `/api/generate` endpoint.</p><pre>/* eslint-disable react/no-unescaped-entities */<br>import { Flex } from &quot;@chakra-ui/react&quot;;<br>import type { NextPage } from &quot;next&quot;;<br>import React, { useState } from &quot;react&quot;;<br>import ThreeDotsLoader from &quot;../src/icons/ThreeDotsLoader&quot;;<br>import { colors } from &quot;../src/theme&quot;;<br>import { AnimatePresence } from &quot;framer-motion&quot;;<br>import Chat from &quot;../src/components/Chat&quot;;<br>import InputField from &quot;../src/components/InputField&quot;;<br><br>type Chat = {<br>  user: &quot;me&quot; | &quot;gpt&quot;;<br>  message: string;<br>  originalIndex: number;<br>};<br><br>const Home: NextPage = () =&gt; {<br>  const [chats, setChats] = useState&lt;Chat[]&gt;([]);<br>  const [value, setValue] = useState(&quot;&quot;);<br>  const [isSubmitting, setIsSubmitting] = useState(false);<br><br>  const handleSubmit = async (e: React.MouseEvent&lt;HTMLElement&gt;) =&gt; {<br>    e.preventDefault();<br><br>    try {<br>      setIsSubmitting(true);<br>      setValue(&quot;&quot;);<br>      setChats((prev) =&gt; [<br>        { user: &quot;me&quot;, message: value, originalIndex: prev.length },<br>        ...prev,<br>      ]);<br><br>      const response = await fetch(&quot;/api/generate&quot;, {<br>        method: &quot;POST&quot;,<br>        headers: {<br>          &quot;Content-Type&quot;: &quot;application/json&quot;,<br>        },<br>        body: JSON.stringify({<br>          message: [{ user: &quot;me&quot;, message: value }, ...chats]<br>            .reverse()<br>            .map((d) =&gt; d.message)<br>            .join(&quot;&quot;),<br>        }),<br>      });<br><br>      const data = await response.json();<br>      if (response.status !== 200) {<br>        throw (<br>          data.error ||<br>          new Error(`Request failed with status ${response.status}`)<br>        );<br>      }<br>      setChats((prev) =&gt; [<br>        { user: &quot;gpt&quot;, message: data.result, originalIndex: prev.length },<br>        ...prev,<br>      ]);<br>    } catch (error) {<br>      console.log(error);<br>    } finally {<br>      setIsSubmitting(false);<br>    }<br>  };<br><br>  return (<br>    &lt;Flex bg=&quot;main-bg&quot; h=&quot;100vh&quot; color=&quot;main-color&quot;&gt;<br>      &lt;Flex<br>        maxW=&quot;1000px&quot;<br>        flexDir=&quot;column&quot;<br>        justify=&quot;space-between&quot;<br>        bg={colors[&quot;button-color&quot;]}<br>        maxH=&quot;100vh&quot;<br>        rounded=&quot;xl&quot;<br>        w=&quot;full&quot;<br>        mx=&quot;auto&quot;<br>        pb=&quot;1rem&quot;<br>        pt=&quot;2rem&quot;<br>        px=&quot;1rem&quot;<br>      &gt;<br>        &lt;Flex<br>          flexDir=&quot;column-reverse&quot;<br>          justify=&quot;flex-start&quot;<br>          align=&quot;flex-start&quot;<br>          maxW=&quot;800px&quot;<br>          h=&quot;full&quot;<br>          w=&quot;full&quot;<br>          mx=&quot;auto&quot;<br>          gap=&quot;2rem&quot;<br>          overflowY=&quot;auto&quot;<br>          px={[0, 0, &quot;1rem&quot;]}<br>          py=&quot;2rem&quot;<br>        &gt;<br>          {isSubmitting &amp;&amp; (<br>            &lt;Flex alignSelf=&quot;flex-start&quot; justify=&quot;center&quot; px=&quot;2rem&quot; py=&quot;0.5rem&quot;&gt;<br>              &lt;ThreeDotsLoader /&gt;<br>            &lt;/Flex&gt;<br>          )}<br>          &lt;AnimatePresence&gt;<br>            {chats.map((chat, index) =&gt; {<br>              return (<br>                &lt;Chat<br>                  key={chat.originalIndex}<br>                  message={chat.message}<br>                  user={chat.user}<br>                /&gt;<br>              );<br>            })}<br>          &lt;/AnimatePresence&gt;<br>        &lt;/Flex&gt;<br>        &lt;InputField<br>          inputProps={{<br>            onChange: (e) =&gt; setValue(e.target.value),<br>            autoFocus: true,<br>            value,<br>          }}<br>          onSubmit={handleSubmit!}<br>        /&gt;<br>      &lt;/Flex&gt;<br>    &lt;/Flex&gt;<br>  );<br>};<br><br>export default Home;</pre><p>You can access the complete source code here: <a href="https://github.com/dieudonneAwa/mini-chatGPT">Mini-ChatGPT</a></p><h3>Conclusion</h3><p>In conclusion, building a chatbot using GPT-3’s API and Next.js can be a fun and challenging project. By following the steps outlined in this blog post, you should now have a good understanding of how to use GPT-3’s API to create a chatbot with Next.js. Whether you want to experiment with the API or build a chatbot for a production-ready application, the skills you have learned here should serve as a solid foundation.</p><p>Finally, if you found this article helpful, consider signing up for our newsletter to receive tips on web development. You can also check out my YouTube channel, <a href="https://www.youtube.com/channel/UC4Bh0roLmZn4RIYd4kcD7KQ">FullStack Mastery</a>, for more full-stack development content.</p><p>Now it’s your turn — what do you think of the article and the chatbot? Let me know in the comments section.</p><p>Thank you!</p><p><strong>Further reading</strong></p><ul><li><a href="https://openai.com/blog/chatgpt-plus/">Introducing ChatGPT Plus</a></li><li><a href="https://openai.com/blog/forecasting-misuse/">Forecasting Potential Misuses of Language Models for Disinformation Campaigns — and How to Reduce Risk</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78e0107a99fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to implement buffering on a custom video player in React.js]]></title>
            <link>https://dieudonneawa7.medium.com/complete-guide-on-how-to-implement-a-video-player-in-react-js-afd07576d50a?source=rss-62b1eded11ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/afd07576d50a</guid>
            <category><![CDATA[chakra-ui]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[dnd]]></category>
            <category><![CDATA[react-beautiful-dnd]]></category>
            <category><![CDATA[react-drag-and-drop]]></category>
            <dc:creator><![CDATA[Awa Dieudonne]]></dc:creator>
            <pubDate>Sat, 21 Jan 2023 19:14:20 GMT</pubDate>
            <atom:updated>2023-01-21T19:42:34.005Z</atom:updated>
            <content:encoded><![CDATA[<h4>An extensive guide to building a video player that has playback speed, seeking, pause/play, and buffer progress indicator using React.js and Chakra UI.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M-HXMDc_5q0ePex96J4erA.png" /></figure><p>In this article, I’m going to walk you through creating a video player, implementing buffering, playback speed, seeking (or timeline scrubbing), and pause/play. We will go from creating a simple video player with just pause/play functionality. Later on, we will add a timeline with play and buffer progress bars indicated.</p><p>Check out my blog website for the original post: <a href="https://awacreates.com/blog/implement-buffering-in-react--a-complete-guide">here</a></p><h4>Create a simple video player</h4><p>Start by setting up a React.js and Chakra UI application, if you don’t know how that is done, please follow the instructions in this guide: <a href="https://chakra-ui.com/getting-started">Getting started with Chakra UI and React.js</a>.</p><p>If you already have your React.js setup, create a file called `Player.tsx` in the root folder. Inside the file, render a simple video tag that expects src, muted, and autoplay props. The video component should have a basic Video styled component with styles that ensure it covers the full height of every parent element it is within.</p><pre>const Video = styled.video`<br>  flex-shrink: 1;<br>  height: 100%;<br>  object-fit: cover;<br>  border-radius: 10px;<br>`;</pre><p>In the `Player.tsx` component, return the video element with the three props: `src`, `muted`, and `autoplay`.</p><pre>interface Props {<br>  src: string;<br>  muted?: boolean;<br>  autoPlay?: boolean;<br>}<br><br>const Player = (props: Props) =&gt; {<br>  const { src, autoPlay, muted } = props;<br><br>  const videoRef = useRef&lt;HTMLVideoElement&gt;(null);<br><br>  const handlePlayPauseClick = () =&gt; {<br>    if (videoRef.current) {<br>      if (isPlaying) {<br>        videoRef.current.pause();<br>      } else {<br>        videoRef.current.play();<br>      }<br>    }<br>  };<br><br>  return (<br>    &lt;Flex<br>      cursor=&quot;pointer&quot;<br>      align=&quot;center&quot;<br>      justify=&quot;center&quot;<br>      rounded=&quot;10px&quot;<br>      overflow=&quot;hidden&quot;<br>    &gt;<br>      &lt;Video<br>        autoPlay={autoPlay}<br>        muted={muted}<br>        src={src}<br>        onClick={handlePlayPauseClick}<br>        ref={videoRef}<br>      /&gt;<br>    &lt;/Flex&gt;<br>  );<br>};<br><br>export default Player;</pre><p>This gives us a basic video player with a click to play or pause the video. It does not include a timeline or any other player controls, just play/pause. Import the component into `App.tsx` and render it there.</p><pre>// App.tsx<br>import &quot;./styles.css&quot;;<br>import Player from &quot;./Player&quot;;<br>import { Flex, Heading } from &quot;@chakra-ui/react&quot;;<br><br>export default function App() {<br>  return (<br>    &lt;Flex flexDir=&quot;column&quot; px=&quot;1rem&quot; className=&quot;App&quot;&gt;<br>      &lt;Heading&gt;Video player&lt;/Heading&gt;<br>      &lt;Player src=&quot;https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4&quot; /&gt;<br>    &lt;/Flex&gt;<br>  );<br>}</pre><h4>Add timeline, buffering, and play progress to the video player</h4><p>The timeline is where the playback and buffer progress bars are indicated in blue and white, respectively. We will use React’s `useRef` to create a reference to the Video element, allowing us to manipulate it with DOM methods. We will also create refs for the buffer and playback progress components. These components will be updated as the user interacts with the player or as the playback or buffer changes.</p><p>Inside the Player component, add a `useEffect` hook. This hook will listen for several events on the video element’s ref and update the UI accordingly. The events are: `waiting`, `play`, `playing`, `pause`, `progress`, and `timeupdate`.</p><p><strong>Quick Summary</strong></p><ul><li>`waiting`: Fired when playback stops because of a temporary lack of data. When this event gets fired, we will set our waiting flag to `true`, and set it back to false in other events.</li><li>`play`: Fired when the paused property is changed from true to false, as a result of the play method, or the autoplay attribute.</li><li>`pause`: Fired when playback is paused.</li><li>`playing`: Fired when the audio/video is playing after pausing or stopping for buffering.</li><li>`progress`: Fired when loading external resources for the video.</li><li>`timeupdate`: Fired when the time indicated by the `currentTime` attribute has been updated</li></ul><pre>// Player.tsx<br>import { Button, Flex, Spinner } from &quot;@chakra-ui/react&quot;;<br>import styled from &quot;@emotion/styled&quot;;<br>import React, { useEffect, useRef, useState } from &quot;react&quot;;<br><br>const Video = styled.video`<br>  flex-shrink: 1;<br>  height: 100%;<br>  object-fit: cover;<br>  border-radius: 10px;<br>`;<br><br>interface Props {<br>  src: string;<br>  muted?: boolean;<br>  autoPlay?: boolean;<br>}<br><br>const Player = (props: Props) =&gt; {<br>  const { src, autoPlay, muted } = props;<br>  const [isWaiting, setIsWaiting] = useState(false);<br>  const [isPlaying, setIsPlaying] = useState(autoPlay);<br>  const [durationSec, setDurationSec] = useState(1);<br>  const [elapsedSec, setElapsedSec] = useState(1);<br><br>  const videoRef = useRef&lt;HTMLVideoElement&gt;(null);<br>  const progressRef = useRef&lt;HTMLDivElement&gt;(null);<br>  const bufferRef = useRef&lt;HTMLDivElement&gt;(null);<br><br>  useEffect(() =&gt; {<br>    if (!videoRef.current) {<br>      return;<br>    }<br><br>    const onWaiting = () =&gt; {<br>      if (isPlaying) setIsPlaying(false);<br>      setIsWaiting(true);<br>    };<br><br>    const onPlay = () =&gt; {<br>      if (isWaiting) setIsWaiting(false);<br>      setIsPlaying(true);<br>    };<br><br>    const onPause = () =&gt; {<br>      setIsPlaying(false);<br>      setIsWaiting(false);<br>    };<br><br>    const element = videoRef.current;<br><br>    const onProgress = () =&gt; {<br>      if (!element.buffered) return;<br>      const bufferedEnd = element.buffered.end(element.buffered.length - 1);<br>      const duration = element.duration;<br>      if (bufferRef &amp;&amp; duration &gt; 0) {<br>        bufferRef.current!.style.width = (bufferedEnd / duration) * 100 + &quot;%&quot;;<br>      }<br>    };<br><br>    const onTimeUpdate = () =&gt; {<br>      setIsWaiting(false);<br>      const duration = element.duration;<br>      setDurationSec(duration);<br>      setElapsedSec(element.currentTime);<br>      if (progressRef &amp;&amp; duration &gt; 0) {<br>        progressRef.current!.style.width =<br>          (element.currentTime / duration) * 100 + &quot;%&quot;;<br>      }<br>    };<br><br>    element.addEventListener(&quot;progress&quot;, onProgress);<br>    element.addEventListener(&quot;timeupdate&quot;, onTimeUpdate);<br><br>    element.addEventListener(&quot;waiting&quot;, onWaiting);<br>    element.addEventListener(&quot;play&quot;, onPlay);<br>    element.addEventListener(&quot;playing&quot;, onPlay);<br>    element.addEventListener(&quot;pause&quot;, onPause);<br><br>    // clean up<br>    return () =&gt; {<br>      element.removeEventListener(&quot;waiting&quot;, onWaiting);<br>      element.removeEventListener(&quot;play&quot;, onPlay);<br>      element.removeEventListener(&quot;playing&quot;, onPlay);<br>      element.removeEventListener(&quot;pause&quot;, onPause);<br>      element.removeEventListener(&quot;progress&quot;, onProgress);<br>      element.removeEventListener(&quot;timeupdate&quot;, onTimeUpdate);<br>    };<br>  }, [videoRef.current]);<br><br>  const handlePlayPauseClick = () =&gt; {<br>    if (videoRef.current) {<br>      if (isPlaying) {<br>        videoRef.current.pause();<br>      } else {<br>        videoRef.current.play();<br>      }<br>    }<br>  };<br><br>  return (<br>    &lt;Flex<br>      flexDir=&quot;column&quot;<br>      cursor=&quot;pointer&quot;<br>      align=&quot;center&quot;<br>      justify=&quot;center&quot;<br>      pos=&quot;relative&quot;<br>      rounded=&quot;10px&quot;<br>      overflow=&quot;hidden&quot;<br>      _hover={{<br>        &quot;.timeline-container&quot;: {<br>          opacity: 1<br>        }<br>      }}<br>    &gt;<br>      {isWaiting &amp;&amp; &lt;Spinner pos=&quot;absolute&quot; color=&quot;white&quot; /&gt;}<br>      &lt;Video<br>        autoPlay={autoPlay}<br>        muted={muted}<br>        src={src}<br>        onClick={handlePlayPauseClick}<br>        ref={videoRef}<br>      /&gt;<br>      &lt;Flex<br>        w=&quot;full&quot;<br>        h=&quot;100px&quot;<br>        bg=&quot;linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.5))&quot;<br>        pos=&quot;absolute&quot;<br>        opacity={0}<br>        transition=&quot;opacity 0.5s linear&quot;<br>        className=&quot;timeline-container&quot;<br>        left={0}<br>        bottom={0}<br>        align=&quot;flex-end&quot;<br>        px=&quot;1rem&quot;<br>      &gt;<br>        &lt;Flex flexDir=&quot;column&quot; w=&quot;full&quot; align=&quot;center&quot;&gt;<br>          &lt;Flex<br>            w=&quot;full&quot;<br>            transition=&quot;height 0.1s linear&quot;<br>            className=&quot;timeline&quot;<br>            h=&quot;4px&quot;<br>            mb=&quot;0.5rem&quot;<br>            rounded=&quot;10px&quot;<br>            bg=&quot;rgba(193, 193, 193, 0.5)&quot;<br>            _hover={{ height: &quot;5px&quot; }}<br>            overflow=&quot;hidden&quot;<br>          &gt;<br>            &lt;Flex pos=&quot;relative&quot; w=&quot;full&quot; h=&quot;full&quot;&gt;<br>              &lt;Flex<br>                h=&quot;full&quot;<br>                className=&quot;play-progress&quot;<br>                bg=&quot;#0CAADC&quot;<br>                zIndex={1}<br>                ref={progressRef}<br>              /&gt;<br>              &lt;Flex<br>                pos=&quot;absolute&quot;<br>                h=&quot;full&quot;<br>                className=&quot;buffer-progress&quot;<br>                bg=&quot;#FDFFFC&quot;<br>                ref={bufferRef}<br>              /&gt;<br>            &lt;/Flex&gt;<br>          &lt;/Flex&gt;<br>        &lt;/Flex&gt;<br>      &lt;/Flex&gt;<br>    &lt;/Flex&gt;<br>  );<br>};<br><br>export default Player;</pre><p><strong>Video buffering</strong></p><p>The following code snippet gets the buffer progress and updates the timeline.</p><pre>...<br>    const onProgress = () =&gt; {<br>      if (!element.buffered) return;<br>      const bufferedEnd = element.buffered.end(element.buffered.length - 1);<br>      const duration = element.duration;<br>      if (bufferRef &amp;&amp; duration &gt; 0) {<br>        bufferRef.current!.style.width = (bufferedEnd / duration) * 100 + &quot;%&quot;;<br>      }<br>    };<br><br>    element.addEventListener(&quot;progress&quot;, onProgress);<br>...</pre><ul><li>`element.buffered` represents a collection of buffered time ranges.</li><li>`element.buffered.end(element.buffered.length — 1)` gets the time at the end of the buffer range.</li></ul><p>With this value, we can now compute the current buffer range and update the buffer progress accordingly.</p><pre>...<br>    const onTimeUpdate = () =&gt; {<br>      setIsWaiting(false);<br>      const duration = element.duration;<br>      setDurationSec(duration);<br>      setElapsedSec(element.currentTime);<br>      if (progressRef &amp;&amp; duration &gt; 0) {<br>        progressRef.current!.style.width =<br>          (element.currentTime / duration) * 100 + &quot;%&quot;;<br>      }<br>    };<br><br>    element.addEventListener(&quot;timeupdate&quot;, onTimeUpdate);<br>...</pre><p>Make sure to call `setIsWaiting(false)` to set the waiting flag to false, so the loader does not continue to run when the player is not buffering.</p><p>Track the `elapsedTimeSec` and `duration`, as they will be needed to add a time tracker to the player.</p><p>At this point, the playback and buffer progress bars should be displayed on the player, as shown below:</p><p><a href="https://firebasestorage.googleapis.com/v0/b/oauth-303809.appspot.com/o/article%2F2c86cece-244c-40e7-9adc-faa74436440d-p.png?alt=media&amp;token=9c54e168-1443-429d-bee5-c206942e605e">https://firebasestorage.googleapis.com/v0/b/oauth-303809.appspot.com/o/article%2F2c86cece-244c-40e7-9adc-faa74436440d-p.png?alt=media&amp;token=9c54e168-1443-429d-bee5-c206942e605e</a></p><h4>How to implement timeline seeking</h4><p>To allow the user to seek or jump to a specific point in the video, listen for a click event on the timeline and use the following handler:</p><pre>...<br>  // This is when clicking on the timeline<br>  const seekToPosition = (event: React.MouseEvent&lt;HTMLDivElement, MouseEvent&gt;) =&gt; {<br>    const { left, width } = event.currentTarget.getBoundingClientRect();<br>    const clickedPos = (event.clientX - left) / width;<br>    if (clickedPos &lt; 0 || clickedPos &gt; 1) return;<br><br>    const durationMs = videoRef.current!.duration * 1000 || 0;<br><br>    const newElapsedMs = durationMs * clickedPos;<br>    const newTimeSec = newElapsedMs / 1000;<br>    videoRef.current.currentTime = newTimeSec;<br>  };<br>...</pre><p>From the click event, obtain the dimension from zero to where the timeline was clicked (represented as left) and the width of the timeline. Use these values to calculate the position. Make sure that the click position is within the range `0=&lt;pos&lt;=1`, and if not, return void.</p><p>Use the value for `clickedPos` to calculate the new time in seconds and update the video’s `currentTime` attribute with it.</p><h4>Add controls to the video player</h4><p>The play controls include play/pause, playback speed, and time tracker. Create components for `PlayIcon.tsx`, `PauseIcon.tsx`, and `ElapsedTimeTracker.tsx`.<br>- `PlayIcon.tsx` and `PauseIcon.tsx` are going to be SVG icon components<br>- `ElapsedTimeTracker.tsx` will be a normal react component that returns JSX for the time tracker.</p><p>Here are the `PlayIcon.tsx` and `PauseIcon.tsx` icon components:</p><pre>// PlayIcon.tsx<br>import React from &quot;react&quot;;<br><br>export default function Play({<br>  fill = &quot;#FFF&quot;,<br>  ...rest<br>}: React.SVGProps&lt;SVGSVGElement&gt;) {<br>  return (<br>    &lt;svg<br>      width=&quot;24&quot;<br>      height=&quot;24&quot;<br>      viewBox=&quot;0 0 24 24&quot;<br>      fill=&quot;none&quot;<br>      xmlns=&quot;http://www.w3.org/2000/svg&quot;<br>      {...rest}<br>    &gt;<br>      &lt;path<br>        fillRule=&quot;evenodd&quot;<br>        clipRule=&quot;evenodd&quot;<br>        d=&quot;M16.578 12.946C15.2954 14.1729 11.805 16.249 10.0193 16.9156C9.73432 17.0217 9.00774 17.2465 8.85116 17.2496C8.51865 17.259 8.19846 17.0935 8.04365 16.8282C7.98383 16.7251 7.8079 16.0523 7.7516 15.7526C7.58447 14.841 7.49827 13.4252 7.50003 12.0016C7.49827 10.5077 7.59151 9.02478 7.77799 8.12253C7.82725 7.87902 7.97152 7.31862 8.01374 7.22809C8.09291 7.0595 8.23717 6.92682 8.41134 6.84408C8.54504 6.78008 8.6981 6.74574 8.85116 6.75042C9.00774 6.75355 9.6446 6.95179 9.86275 7.02828C11.5833 7.62145 15.2233 9.77249 16.5604 11.0369C16.68 11.1508 17.009 11.4568 17.0635 11.5192C17.1884 11.6597 17.25 11.8299 17.25 12.0016C17.25 12.1608 17.1955 12.3231 17.0829 12.459C17.0248 12.5292 16.6888 12.8414 16.578 12.946Z&quot;<br>        fill={fill}<br>      /&gt;<br>    &lt;/svg&gt;<br>  );<br>}</pre><pre>// PauseIcon.tsx<br>import React from &quot;react&quot;;<br><br>export default function Pause({<br>  fill = &quot;#fff&quot;,<br>  ...rest<br>}: React.SVGProps&lt;SVGSVGElement&gt;) {<br>  return (<br>    &lt;svg<br>      width=&quot;24&quot;<br>      height=&quot;24&quot;<br>      viewBox=&quot;0 0 24 24&quot;<br>      fill=&quot;none&quot;<br>      xmlns=&quot;http://www.w3.org/2000/svg&quot;<br>      {...rest}<br>    &gt;<br>      &lt;rect x=&quot;7&quot; y=&quot;6&quot; width=&quot;3&quot; height=&quot;12&quot; rx=&quot;1.5&quot; fill={fill} /&gt;<br>      &lt;rect<br>        opacity=&quot;0.5&quot;<br>        x=&quot;14&quot;<br>        y=&quot;6&quot;<br>        width=&quot;3&quot;<br>        height=&quot;12&quot;<br>        rx=&quot;1.5&quot;<br>        fill={fill}<br>      /&gt;<br>    &lt;/svg&gt;<br>  );<br>}</pre><p>The icon components accept an optional fill prop and spread the rest of the incoming props on the `&lt;svg&gt;` tag.</p><p>Now, create another component for the elapsed time tracker.</p><pre>// ElapsedTimeTracker<br>import { Flex, Text } from &quot;@chakra-ui/react&quot;;<br>import React from &quot;react&quot;;<br><br>type Props = {<br>  elapsedSec: number;<br>  totalSec: number | null;<br>};<br><br>export default function ElapsedTimeTracker({ ...props }: Props) {<br>  const elapsedMin = Math.floor(props.elapsedSec / 60);<br>  const elapsedSec = Math.floor(props.elapsedSec % 60);<br><br>  return (<br>    &lt;Flex<br>      align=&quot;center&quot;<br>      className=&quot;elapsed-time-tracker&quot;<br>      fontWeight=&quot;600&quot;<br>      gap=&quot;4px&quot;<br>      transition=&quot;500ms opacity&quot;<br>      mt=&quot;-8px&quot;<br>      p={0}<br>    &gt;<br>      &lt;Flex justify=&quot;end&quot;&gt;<br>        &lt;Text fontWeight={600} color=&quot;white&quot;&gt;<br>          {elapsedMin}:<br>        &lt;/Text&gt;<br>        &lt;Text fontWeight={600} color=&quot;white&quot;&gt;<br>          {elapsedSec.toString().padStart(2, &quot;0&quot;)}<br>        &lt;/Text&gt;<br>      &lt;/Flex&gt;<br>    &lt;/Flex&gt;<br>  );<br>}</pre><p>The time tracker expects two props: `elapsedSec`, for elapsed time in seconds, and `totalSec` for the video’s total duration in seconds.</p><p><strong>Playback rate (or playback speed):</strong></p><p>The playback rate is the speed at which a video plays. In this player, the user will be able to increase the speed, but not decrease it. This is the final feature of the player.</p><pre>// PlaybackRate.tsx<br>import { CheckIcon, ChevronDownIcon } from &quot;@chakra-ui/icons&quot;;<br>import {<br>  Flex,<br>  Menu,<br>  MenuButton,<br>  MenuGroup,<br>  MenuItem,<br>  MenuList,<br>  Text<br>} from &quot;@chakra-ui/react&quot;;<br>import React from &quot;react&quot;;<br><br>type PlaybackRateControlButtonProps = {<br>  onClick?: React.MouseEventHandler;<br>  playbackRate: number;<br>};<br><br>const PlaybackRateControlButton = React.forwardRef&lt;<br>  HTMLDivElement,<br>  PlaybackRateControlButtonProps<br>&gt;(({ onClick, playbackRate }, ref) =&gt; (<br>  &lt;div ref={ref}&gt;<br>    &lt;Flex<br>      className=&quot;playback-rate-control&quot;<br>      alignItems=&quot;center&quot;<br>      cursor=&quot;pointer&quot;<br>      h=&quot;40px&quot;<br>      justifyContent=&quot;center&quot;<br>      rounded=&quot;12px&quot;<br>      w=&quot;40px&quot;<br>      _hover={{<br>        bg: &quot;rgba(255, 255, 255, 0.08)&quot;<br>      }}<br>      onClick={onClick}<br>      mt=&quot;-8px&quot;<br>      transition=&quot;500ms opacity&quot;<br>    &gt;<br>      &lt;Text<br>        color=&quot;white&quot;<br>        fontWeight={700}<br>        letterSpacing=&quot;0.5px&quot;<br>        pos=&quot;relative&quot;<br>        top=&quot;-1px&quot;<br>      &gt;<br>        &lt;span style={{ fontSize: &quot;14px&quot; }}&gt;{playbackRate}&lt;/span&gt;<br>        &lt;span style={{ fontSize: &quot;11px&quot; }}&gt;x&lt;/span&gt;<br>        &lt;ChevronDownIcon<br>          bottom=&quot;-1px&quot;<br>          color=&quot;white&quot;<br>          marginLeft=&quot;-1px&quot;<br>          marginRight=&quot;-4px&quot;<br>          opacity=&quot;0.5&quot;<br>          pos=&quot;relative&quot;<br>          width=&quot;12px&quot;<br>          stroke=&quot;white&quot;<br>        /&gt;<br>      &lt;/Text&gt;<br>    &lt;/Flex&gt;<br>  &lt;/div&gt;<br>));<br><br>type Props = {<br>  playbackRate: number;<br>  setPlaybackRate: (playbackRate: number) =&gt; void;<br>};<br><br>export default React.memo(function PlaybackRateControl({<br>  playbackRate,<br>  setPlaybackRate<br>}: Props) {<br>  return (<br>    &lt;Menu autoSelect={false} placement=&quot;top-start&quot;&gt;<br>      &lt;MenuButton as={PlaybackRateControlButton} playbackRate={playbackRate} /&gt;<br>      &lt;MenuList<br>        bg=&quot;#1D253F&quot;<br>        border=&quot;none&quot;<br>        pl=&quot;8px&quot;<br>        pr=&quot;8px&quot;<br>        minW=&quot;50px&quot;<br>        zIndex=&quot;2&quot;<br>      &gt;<br>        &lt;MenuGroup<br>          color=&quot;white&quot;<br>          fontSize=&quot;12px&quot;<br>          fontWeight=&quot;400&quot;<br>          ml=&quot;12px&quot;<br>          title=&quot;Playback Speed&quot;<br>        &gt;<br>          {[1, 1.5, 2].map((rate) =&gt; (<br>            &lt;MenuItem<br>              height=&quot;40px&quot;<br>              justifyContent=&quot;space-between&quot;<br>              key={`playbackRate_${rate}`}<br>              onClick={() =&gt; {<br>                if (playbackRate === rate) return;<br>                setPlaybackRate(rate);<br>              }}<br>              rounded=&quot;8px&quot;<br>              _hover={{<br>                bg: &quot;rgba(0, 0, 0, 0.4)&quot;<br>              }}<br>              _focus={{<br>                bg: &quot;rgba(0, 0, 0, 0.4)&quot;<br>              }}<br>            &gt;<br>              &lt;Text fontWeight={600} size=&quot;sm&quot; color=&quot;white&quot;&gt;<br>                {rate.toFixed(1)}x<br>              &lt;/Text&gt;<br>              {playbackRate === rate &amp;&amp; (<br>                &lt;CheckIcon width=&quot;15px&quot; height=&quot;11px&quot; fill=&quot;white&quot; /&gt;<br>              )}<br>            &lt;/MenuItem&gt;<br>          ))}<br>        &lt;/MenuGroup&gt;<br>      &lt;/MenuList&gt;<br>    &lt;/Menu&gt;<br>  );<br>});</pre><p>The component expects two props: `playbackRate` and `setPlaybackRate`. `playbackRate` is the state variable for the playback speed, and `setPlaybackRate` is used to set the value of `playbackRate`.</p><p>Finalize Video player<br>To complete the video player, import the components you just created into the `Player.tsx` file and render them there.</p><p>The final Player component should have the following code:</p><pre>// Player.tsx<br>import { Button, Flex, Spinner } from &quot;@chakra-ui/react&quot;;<br>import styled from &quot;@emotion/styled&quot;;<br>import React, { useEffect, useRef, useState } from &quot;react&quot;;<br>import PlayIcon from &quot;./PlayIcon&quot;;<br>import PauseIcon from &quot;./PauseIcon&quot;;<br>import ElapsedTimeTracker from &quot;./ElapsedTimeTracker&quot;;<br>import PlaybackRate from &quot;./PlaybackRate&quot;;<br><br>const Video = styled.video`<br>  flex-shrink: 1;<br>  height: 100%;<br>  object-fit: cover;<br>  border-radius: 10px;<br>`;<br><br>interface Props {<br>  src: string;<br>  muted?: boolean;<br>  autoPlay?: boolean;<br>}<br><br>const Player = (props: Props) =&gt; {<br>  const { src, autoPlay, muted } = props;<br>  const [isWaiting, setIsWaiting] = useState(false);<br>  const [isPlaying, setIsPlaying] = useState(autoPlay);<br>  const [playbackRate, setPlaybackRate] = useState(1);<br>  const [durationSec, setDurationSec] = useState(1);<br>  const [elapsedSec, setElapsedSec] = useState(1);<br><br>  const videoRef = useRef&lt;HTMLVideoElement&gt;(null);<br>  const progressRef = useRef&lt;HTMLDivElement&gt;(null);<br>  const bufferRef = useRef&lt;HTMLDivElement&gt;(null);<br><br>  useEffect(() =&gt; {<br>    if (!videoRef.current) {<br>      return;<br>    }<br><br>    const onWaiting = () =&gt; {<br>      if (isPlaying) setIsPlaying(false);<br>      setIsWaiting(true);<br>    };<br><br>    const onPlay = () =&gt; {<br>      if (isWaiting) setIsWaiting(false);<br>      setIsPlaying(true);<br>    };<br><br>    const onPause = () =&gt; {<br>      setIsPlaying(false);<br>      setIsWaiting(false);<br>    };<br><br>    const element = videoRef.current;<br><br>    element.addEventListener(&quot;progress&quot;, function () {<br>      if (!element.buffered) return;<br>      const bufferedEnd = element.buffered.end(element.buffered.length - 1);<br>      const duration = element.duration;<br>      if (bufferRef &amp;&amp; duration &gt; 0) {<br>        bufferRef.current!.style.width = (bufferedEnd / duration) * 100 + &quot;%&quot;;<br>      }<br>    });<br><br>    element.addEventListener(&quot;timeupdate&quot;, function () {<br>      setIsWaiting(false);<br>      const duration = element.duration;<br>      setDurationSec(duration);<br>      setElapsedSec(element.currentTime);<br>      if (progressRef &amp;&amp; duration &gt; 0) {<br>        progressRef.current!.style.width =<br>          (element.currentTime / duration) * 100 + &quot;%&quot;;<br>      }<br>    });<br><br>    element.addEventListener(&quot;waiting&quot;, onWaiting);<br>    element.addEventListener(&quot;play&quot;, onPlay);<br>    element.addEventListener(&quot;playing&quot;, onPlay);<br>    element.addEventListener(&quot;pause&quot;, onPause);<br><br>    // clean up<br>    return () =&gt; {<br>      element.removeEventListener(&quot;waiting&quot;, onWaiting);<br>      element.removeEventListener(&quot;play&quot;, onPlay);<br>      element.removeEventListener(&quot;playing&quot;, onPlay);<br>      element.removeEventListener(&quot;pause&quot;, onPause);<br>    };<br>  }, [videoRef.current]);<br><br>  // This is where the playback rate is set on the video element.<br>  useEffect(() =&gt; {<br>    if (!videoRef.current) return;<br>    if (videoRef.current.playbackRate === playbackRate) return;<br>    videoRef.current.playbackRate = playbackRate;<br>  }, [playbackRate]);<br><br>  const handlePlayPauseClick = () =&gt; {<br>    if (videoRef.current) {<br>      if (isPlaying) {<br>        videoRef.current.pause();<br>      } else {<br>        videoRef.current.play();<br>      }<br>    }<br>  };<br><br>  const seekToPosition = (pos: number) =&gt; {<br>    if (pos &lt; 0 || pos &gt; 1) return;<br><br>    const durationMs = videoRef.current!.duration * 1000 || 0;<br><br>    const newElapsedMs = durationMs * pos;<br>    const newTimeSec = newElapsedMs / 1000;<br>    console.log(durationMs, newElapsedMs, pos, newTimeSec);<br>    videoRef.current.currentTime = newTimeSec;<br>  };<br><br>  return (<br>    &lt;Flex<br>      flexDir=&quot;column&quot;<br>      cursor=&quot;pointer&quot;<br>      align=&quot;center&quot;<br>      justify=&quot;center&quot;<br>      pos=&quot;relative&quot;<br>      rounded=&quot;10px&quot;<br>      overflow=&quot;hidden&quot;<br>      _hover={{<br>        &quot;.timeline-container&quot;: {<br>          opacity: 1<br>        }<br>      }}<br>    &gt;<br>      {isWaiting &amp;&amp; &lt;Spinner pos=&quot;absolute&quot; color=&quot;white&quot; /&gt;}<br>      &lt;Video<br>        autoPlay={autoPlay}<br>        muted={muted}<br>        src={src}<br>        onClick={handlePlayPauseClick}<br>        ref={videoRef}<br>      /&gt;<br>      &lt;Flex<br>        w=&quot;full&quot;<br>        h=&quot;100px&quot;<br>        bg=&quot;linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.5))&quot;<br>        pos=&quot;absolute&quot;<br>        opacity={0}<br>        transition=&quot;opacity 0.5s linear&quot;<br>        className=&quot;timeline-container&quot;<br>        left={0}<br>        bottom={0}<br>        align=&quot;flex-end&quot;<br>        px=&quot;1rem&quot;<br>      &gt;<br>        &lt;Flex flexDir=&quot;column&quot; w=&quot;full&quot; align=&quot;center&quot;&gt;<br>          &lt;Flex<br>            w=&quot;full&quot;<br>            transition=&quot;height 0.1s linear&quot;<br>            className=&quot;timeline&quot;<br>            h=&quot;4px&quot;<br>            mb=&quot;0.5rem&quot;<br>            rounded=&quot;10px&quot;<br>            bg=&quot;rgba(193, 193, 193, 0.5)&quot; // Buffer color: #FDFFFC<br>            _hover={{ height: &quot;5px&quot; }}<br>            overflow=&quot;hidden&quot;<br>            onClick={(e: React.MouseEvent&lt;HTMLDivElement, MouseEvent&gt;) =&gt; {<br>              const { left, width } = e.currentTarget.getBoundingClientRect();<br>              const clickedPos = (e.clientX - left) / width;<br>              seekToPosition(clickedPos);<br>            }}<br>          &gt;<br>            &lt;Flex pos=&quot;relative&quot; w=&quot;full&quot; h=&quot;full&quot;&gt;<br>              &lt;Flex<br>                h=&quot;full&quot;<br>                className=&quot;play-progress&quot;<br>                bg=&quot;#0CAADC&quot;<br>                zIndex={1}<br>                ref={progressRef}<br>              /&gt;<br>              &lt;Flex<br>                pos=&quot;absolute&quot;<br>                h=&quot;full&quot;<br>                className=&quot;buffer-progress&quot;<br>                bg=&quot;#FDFFFC&quot;<br>                ref={bufferRef}<br>              /&gt;<br>            &lt;/Flex&gt;<br>          &lt;/Flex&gt;<br>          &lt;Flex w=&quot;full&quot; justify=&quot;space-between&quot; align=&quot;center&quot;&gt;<br>            &lt;Flex align=&quot;center&quot;&gt;<br>              &lt;Button<br>                maxW=&quot;25px&quot;<br>                minW=&quot;25px&quot;<br>                w=&quot;25px&quot;<br>                p=&quot;0&quot;<br>                mr=&quot;0.4rem&quot;<br>                maxH=&quot;25px&quot;<br>                h=&quot;25px&quot;<br>                rounded=&quot;4px&quot;<br>                colorScheme=&quot;transparent&quot;<br>                bg=&quot;transparent&quot;<br>                mb=&quot;0.5rem&quot;<br>                _hover={{<br>                  bg: &quot;rgba(0, 0, 0, 0.4)&quot;<br>                }}<br>                onClick={handlePlayPauseClick}<br>              &gt;<br>                {!isPlaying ? &lt;PlayIcon /&gt; : &lt;PauseIcon /&gt;}<br>              &lt;/Button&gt;<br><br>              &lt;ElapsedTimeTracker<br>                totalSec={durationSec}<br>                elapsedSec={elapsedSec}<br>              /&gt;<br>            &lt;/Flex&gt;<br><br>            &lt;PlaybackRate<br>              playbackRate={playbackRate}<br>              setPlaybackRate={setPlaybackRate}<br>            /&gt;<br>          &lt;/Flex&gt;<br>        &lt;/Flex&gt;<br>      &lt;/Flex&gt;<br>    &lt;/Flex&gt;<br>  );<br>};<br><br>export default Player;</pre><p>The final version of the video player should include play/pause, buffering, a timeline, seeking, and player controls, as shown in the screenshot below:</p><p>![Video player with buffering](<a href="https://firebasestorage.googleapis.com/v0/b/oauth-303809.appspot.com/o/article%2F1295518b-759f-48d0-a799-9060d5cb2a45-final%20video%20player.png?alt=media&amp;token=4aedc5d1-cd79-4b02-9e89-70435739b226">https://firebasestorage.googleapis.com/v0/b/oauth-303809.appspot.com/o/article%2F1295518b-759f-48d0-a799-9060d5cb2a45-final%20video%20player.png?alt=media&amp;token=4aedc5d1-cd79-4b02-9e89-70435739b226</a>)</p><p>..<br>![Video player with buffering and playback rate](<a href="https://firebasestorage.googleapis.com/v0/b/oauth-303809.appspot.com/o/article%2F9f68f394-955f-4e9d-92fb-76010e653c80-final%20video%20player%202.png?alt=media&amp;token=a60c4162-401c-48b1-ae3e-dc098bb0ed1e">https://firebasestorage.googleapis.com/v0/b/oauth-303809.appspot.com/o/article%2F9f68f394-955f-4e9d-92fb-76010e653c80-final%20video%20player%202.png?alt=media&amp;token=a60c4162-401c-48b1-ae3e-dc098bb0ed1e</a>)</p><h4>Conclusion</h4><p>With that, we have completed our custom video player with buffering functionality.</p><p>If you found this article helpful, consider signing up for our newsletter to receive tips on web development. You can also check out my YouTube channel, <a href="https://www.youtube.com/channel/UC4Bh0roLmZn4RIYd4kcD7KQ">FullStack Mastery</a>, for more full-stack development content.</p><p>Now it’s your turn — what do you think of the article and our player? Let me know in the comments below.</p><p>Thank you!</p><p><strong>Helpful links</strong><br>- <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Video_and_audio_APIs">Video and Audio APIs</a><br>- <a href="https://muffinman.io/blog/react-simple-video-buffering-loader/">Simple video buffering loader in React</a><br>- YouTube: <a href="https://www.youtube.com/watch?v=Y9TL_43X3Lc">How to create a React.js video player with buffering | playback speed | scrubbing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afd07576d50a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google OAuth in Nodejs, Express, and Reactjs]]></title>
            <link>https://medium.com/swlh/google-oauth-in-nodejs-express-and-reactjs-25d72e6d7165?source=rss-62b1eded11ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/25d72e6d7165</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[google-authentication]]></category>
            <category><![CDATA[google-login]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[google-oauth]]></category>
            <dc:creator><![CDATA[Awa Dieudonne]]></dc:creator>
            <pubDate>Sun, 07 Mar 2021 07:20:33 GMT</pubDate>
            <atom:updated>2024-02-25T18:49:26.541Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hV-LUx79-IF-cwrxbGWIuQ.jpeg" /></figure><p>In this article, I will walk you through implementing google OAuth with passportjs and JWT in a <strong>React, Node</strong>, <strong>Express</strong>, <strong>Sequelize,</strong> and <strong>PostgreSQL</strong> application. The same flow can be used on a Next.js application as well.</p><p><em>Originally published at </em><a href="https://awacreates.com/"><em>https://awacreates.com</em></a><em>.</em></p><h3>What is Google Oauth?</h3><p>Oauth stands for<strong> Open Authorization. </strong>It allows third-party services like Google and Facebook to exchange your information without you having to give away your passwords. This helps prevent your password from being compromised. Learn more about Google Oauth <a href="https://developers.google.com/identity/protocols/oauth2">here</a>.</p><h3>How does Google Oauth work?</h3><p>Once a user clicks on the Oauth login button, our frontend sends a request to the Google authorization server through a browser redirect and obtains an access token that will grant access to the Google API. During the access-token request, our application sends one or more values in the <strong>scope</strong> parameter which controls the set of resources and operations that an access token permits.</p><p>After obtaining the access token, what happens next?</p><p>Our application makes a call to the Google API, setting the token in the <a href="https://developer.mozilla.org/docs/Web/HTTP/Headers/Authorization">HTTP Authorization request header</a>. The access token will be valid only for the set of operations and resources described in the <strong>scope</strong> of the token request.</p><p>Our request is authenticated using <a href="http://www.passportjs.org/docs/downloads/html/">passport.js authentication</a> and sends the user’s profile info. We will receive the user’s profile info inside a <a href="http://www.passportjs.org/docs/configure/"><strong>passport verify callback </strong></a>whose purpose is to find the user that possesses the set of credentials.</p><p>Once authentication is successful, a session is established and maintained via a cookie set in the user’s browser. Each subsequent request will not contain credentials, but rather the unique cookie that identifies the session. Passport uses the serialize and deserialize functions to save the user’s ID to and from the session.</p><h3>Google Oauth Flow diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*VN7bbDJBE0khDkKPJKg_uA.png" /></figure><h3>Understanding passport Serialize and Deserialize functions</h3><ul><li><strong>serializeUser: </strong>Determines which data of the user object should be stored in the session. The result of the serializeUser method is attached to the session as req.session.passport.user</li><li>In our case only the user ID will be serialized to the session, keeping the amount of data stored within the session small.</li><li><strong>deserializeUser: </strong>Used to retrieve the id stored in the session by the serializeUser function. This is where we make a backend call to get the user instance by that ID and attach it to the request object as <strong>req.user</strong>.</li></ul><p>Visit <a href="http://www.passportjs.org/docs/configure/">http://www.passportjs.org/docs/configure/</a> for more info about serializeUser and deserializeUser functions.</p><p>After deserializing, our next handler receives control, generates a JWT token from the credentials in <strong>req.user</strong>, and sends a response containing the user’s object and the JWT.</p><p>Feel free to comment if there’s anything you do not understand about the above explanations.</p><h3>Implementing Google Oauth in Nodejs, express, sequelize, and Postgres</h3><h3>1. Create a Google client ID and client secret</h3><p>Visit <a href="https://console.developers.google.com/">Google API Console</a> and obtain OAuth 2.0 credentials such as a client ID and client secret that will be known to both Google and our application.</p><p>Below are the steps to follow:</p><ul><li>From the projects drop-down, create a new one by clicking on <strong>New project.</strong></li><li>In the sidebar under “APIs &amp; Services”, select Credentials</li><li>In the Credentials tab, click the <strong>Create credentials</strong> drop-down list, and choose<strong> OAuth client ID</strong>.</li><li>Configure the consent screen and set the scopes. When you’re done, go back to the dashboard.</li><li>Click again on <strong>Create credentials</strong> drop-down list, and select<strong> OAuth client ID, </strong>but this time it will take you to a page where you will select the application type. Choose <strong>Web application.</strong></li><li>Under <strong>Authorised JavaScript origins, </strong>enter the backend API’s URL, which in our case is going to be <a href="http://localhost:3000/">http://localhost:3000</a></li><li>Under <strong>Authorised redirect URIs, </strong>enter the frontend URL which is going to be<strong>: </strong><a href="http://localhost:4000/">http://localhost:4000</a>, and click save.</li></ul><h3>2. Initialize Nodejs and install all dependencies</h3><p>Create an empty folder and open it in your favorite editor. Run the following to initialize a Nodejs project.</p><pre>npm init</pre><p>After that is complete, run the following to install all necessary dependencies</p><pre>npm i body-parser cors dotenv express jsonwebtoken passport passport-google-token pg sequelize</pre><p>Install Dev dependencies</p><pre>npm i --save-dev @babel/cli @babel/core @babel/node @babel/plugin-proposal-optional-chaining @babel/plugin-transform-runtime @babel/preset-env @babel/register @babel/runtime babel-node nodemon sequelize-cli</pre><h3>3. Configure Express server</h3><pre>// api/server.js<br>import cors from &#39;cors&#39;;<br>import logger from &#39;morgan&#39;;<br>import express from &#39;express&#39;;<br>import bodyParser from &#39;body-parser&#39;;</pre><pre>const app = express();</pre><pre>app.use(cors({ origin: true }));<br>app.use(bodyParser.json());<br>app.use(bodyParser.urlencoded({ extended: false }));<br>app.use(logger(&#39;dev&#39;));</pre><pre>const port = process.env.PORT || 5000;</pre><pre>app.listen(port, () =&gt; console.log(`Server running on http://localhost:${port}`));</pre><h3>4. Setup Postgres database connection with Sequelize</h3><p>Step 1: Create a .sequelizerc file with the following code</p><p>Step 2: Initialize sequelize</p><pre>sequelize init</pre><p>This will create the following folders</p><ul><li>config.js, which tells the Sequelize CLI how to connect to the database</li><li>models contain all models for your project</li><li>migrations contain all migration files</li><li>seeders contain all seed files</li></ul><p>Step 3: Configure Postgres database connection</p><p>Let’s start by creating our .env file to store our environment variables such as our google client key, JWT secret, Database connection URL, …etc</p><p>Copy the Google Client Id and Secret Id from your <a href="https://console.developers.google.com/apis/credentials?highlightClient=1098763850660-6k9o5vetme9r6b3l8ghnlukb9mo3qr2f.apps.googleusercontent.com&amp;project=avid-lacing-302609">Google API Console dashboard</a> and save them inside the .env file.</p><pre>DATABASE_DEV=postgres: <br>GOOGLE_CLIENT_ID= GOOGLE_CLIENT_SECRET= JWT_SECRET=</pre><p>Copy and paste the following connection setup code inside config.js file.</p><p>This file is supposed to set up a connection to our database, but we do not have one yet. So run the following sequelize command to create the database for our API</p><pre>sequelize db:create</pre><p>Step 4: Create a migration file for the users’ table</p><p>Now that we are done with the configurations, let’s create the users’ migration file with all its columns by running the following command:</p><pre>sequelize model:generate --name User --attributes name:string,email:string,password:string,goodleId:string,provider:string</pre><p>As soon as this is done running, let us create the database table by executing the migration as follows:</p><pre>sequelize db:migrate</pre><h3>5. Create Google Oauth endpoint</h3><p>Step 1: Configure passport.js and google strategy:</p><p>Create a controller folder in the /api directory and create another new folder for authController with index.js and passport.js in it.</p><p>Copy and paste the following code into the passport.js file you just created.</p><p>So we imported our google strategy and created an instance of it inside the use() function. Inside the verify callback we are getting the user’s profile coming from google to check if that user already signed up through Google Oauth, else we sign him up and call done(null, user).</p><p>Step 2: Create a controller function for completing the OAuth flow:</p><p>Inside our controller/index.js file, copy and paste the following code</p><p>What this google OAuth does is to receive the authenticated user from the req object generate a JWT token and return a response of the user and his login token.</p><p>Step 3: Connect passport.js configurations to the server and add a route:</p><p>Import the configurations from controllers/passport.js inside our express server and create the endpoint for Google OAuth. The server should now look like this:</p><p>And then we are done with Implementing Google Oauth in Nodejs, express, sequelize, and Postgres. Let’s go ahead and consume the OAuth endpoint on the frontend.</p><h3>Implementing Google Oauth in ReactJs</h3><h3>1. Initialize create-react-app:</h3><p>Initialize a new react project by running the following in your term</p><pre>npx create-react-app google-oauth-client</pre><h3>2. Install all necessary dependencies:</h3><pre>npm i --save axios react-google-login js-cookie</pre><h3>3. Use GoogleLogin button component from react-google-login:</h3><p>Let’s first of all setup our environment variables.</p><p>Create a .env file in the root directory of the application and add the following variables to it.</p><pre>REACT_APP_API_BASE_URL=http: REACT_APP_GOOGLE_CLIENT_ID=</pre><p>Inside our App.jsx component, copy and paste the following code</p><p>You should have something like this as the end result</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*YOMiKYGZJH0an4dKUWzJ5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*ddWPAb7KAjAtES4citgWPQ.png" /></figure><p>Test it out, if you face any issues, let me know in the comment section, I am available 24/7 to answer your questions.</p><h3>Conclusion</h3><p>So that is it for setting up google OAuth. Now I’d like to hear what you have to say.</p><p>Have you learned something new? Drop it in the comment section, we never can tell how many people will learn from us. Was it helpful? Spread the word, share with friends even on social media.</p><p>Thanks</p><p><em>Originally published at </em><a href="https://awacreates.com/"><em>https://awacreates.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25d72e6d7165" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/google-oauth-in-nodejs-express-and-reactjs-25d72e6d7165">Google OAuth in Nodejs, Express, and Reactjs</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Summarised Next.js Version 10 features]]></title>
            <link>https://dieudonneawa7.medium.com/summarised-next-js-version-10-features-3d5bbc182995?source=rss-62b1eded11ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d5bbc182995</guid>
            <category><![CDATA[image-optimization]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[website-optimization]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react-framework]]></category>
            <dc:creator><![CDATA[Awa Dieudonne]]></dc:creator>
            <pubDate>Wed, 28 Oct 2020 20:13:25 GMT</pubDate>
            <atom:updated>2020-10-28T20:15:31.130Z</atom:updated>
            <content:encoded><![CDATA[<h3>Summary of Next.js Version 10 features</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fb7X4s1RkJ1ckuKkZkS1gg.jpeg" /></figure><p>Nextjs has had over 20 new features that improve performance and developer experience. At the same time, the JavaScript size of the Next.js core has been reduced by 16%.</p><h3>Automatic image optimization</h3><blockquote>Because the web is not only made of JS, they’ve also introduced automatic image optimisation through introducing a component that will replace the HTML <strong>&lt;img&gt;</strong> element.</blockquote><ul><li>When using the Image component from next/image, images are automatically lazy-loaded.</li><li>Whenever a large image is used on phone screens, the next/image component will automatically generate smaller sizes through built-in Image Optimization.</li><li>Built-in Image Optimization automatically serves the images in modern image formats like WebP, which is about 30% smaller than JPEG</li></ul><h3>Internationalize Routing</h3><blockquote>Built-in support for internationalized routing and language detection.</blockquote><ul><li>This supports Next.js’s hybrid strategy, meaning you can choose between Static Generation or Server-Rendering on a per-page basis.</li><li>Next.js 10 supports the two most common routing strategies: subpath routing and domain routing.</li><li>Subpath routing puts the locale in the url. This allows all languages to live on a single domain.</li><li>Domain routing enables you to map a locale to a top level domain.</li><li>Next.js 10 has built-in language detection on the / route based on the `Accept-Language` header, which all modern browsers support.</li></ul><h3>Next.js Analytics</h3><blockquote>The solution for tracking real-world performance metrics and feeding those insights back into your development workflow.</blockquote><p><strong>With Next.js Analytics:</strong></p><ul><li>Instead of measuring once, you will now measure continuously.</li><li>Instead of measuring on your development device, measurements will come from the actual devices that your visitors are using.</li></ul><h3>Core Web Vitals</h3><blockquote>Google, in conjunction with the Web Performance Working Group, have established the set of metrics to accurately measure how users experience the performance of your website: aptly named, Web Vitals.</blockquote><p>Web Vitals are metrics that track the perceived loading speed, responsiveness, and visual stability of your website — all three essential for website’s overall health!</p><h3>getStaticProps / getServerSideProps Fast Refresh</h3><blockquote>When making edits to your <em>getStaticProps</em> and <em>getServerSideProps</em> functions Next.js will now automatically re-run the function and apply the new data. This allows you to iterate quicker without having to refresh the page.</blockquote><h3>Automatic Resolving of `href`</h3><blockquote>As part of Next.js 10 you no longer have to use the as property for the majority of use-cases on Link component from next/link</blockquote><p>e.g</p><p>&lt;Link href=”/categories/[slug]” as=”/categories/books”&gt; becomes &lt;Link as=”/categories/books”&gt;</p><h3>Conclusion</h3><p>In conclusion, I am always excited about good things.</p><p>So after going through the <a href="https://nextjs.org/blog/next-10">Next.js 10 release blog post</a>, I thought summarising the features will help the future me retain the version 10 features.</p><p>After summarising for myself, I thought it will also make sense to share it for those who might not have the time to go through the post like I did.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d5bbc182995" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a responsive hamburger navigation menu — ReactJS and Styled Components]]></title>
            <link>https://levelup.gitconnected.com/how-to-create-a-responsive-hamburger-navigation-menu-reactjs-and-styled-components-59ce167ed543?source=rss-62b1eded11ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/59ce167ed543</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[styled-components]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[create-react-app]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Awa Dieudonne]]></dc:creator>
            <pubDate>Mon, 20 Apr 2020 14:23:52 GMT</pubDate>
            <atom:updated>2023-01-21T19:50:17.961Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to create a responsive hamburger navigation menu — ReactJS and Styled Components</h3><figure><img alt="Responsive hamburger navigation menu using React and styled-components." src="https://cdn-images-1.medium.com/max/1024/1*n2gFbNdctIeI8_8z5KBpWQ.png" /></figure><p>In order to build a website with a good user experience, there are a lot of things to consider and one of them is how responsive your site is going to be. Your site can be responsive and still have a bad user experience. But how do you solve this?</p><p><em>Originally published my blog here </em><a href="https://awacreates.com/blog/responsive-hamburger-navigation-menu--reactjs-and-styled-components"><strong><em>here</em></strong></a></p><p>In this article, I am going to walk you through building a hamburger responsive navigation menu from scratch using <a href="https://reactjs.org/"><strong><em>Reactjs</em></strong></a><strong><em> and </em></strong><a href="https://styled-components.com/"><strong><em>Styled-Components</em></strong>.</a> To do this, there are a few things to handle.</p><h4>Setup React app</h4><p>In your terminal, run the following scripts. Then open <a href="http://localhost:3000/">http://localhost:3000</a> to see your app.</p><pre>npx create-react-app responsive-nabar<br>cd responsive-nabar<br>npm start</pre><p>While your app is running, install styled components using the following scripts.</p><pre>npm install styled-components</pre><p>Go to your root directory and clear out the create react app files we won&#39;t be needing. Your directory structure should look exactly like this</p><figure><img alt="File structure for responsive navbar react app" src="https://cdn-images-1.medium.com/max/591/1*L071xaRUSkjvxZ-oY-_7LA.png" /><figcaption>File structure for responsive-navbar</figcaption></figure><p>Open your index.html and add the following code directly below the &lt;title&gt; tag.</p><pre>&lt;style&gt;<br>  * {<br>    padding: 0;<br>    margin: 0;<br>    box-sizing: border-box;<br>  }<br>&lt;/style&gt;</pre><p>Update your App.js file with the following code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a29555640641f1756205ed9f15a2b3c/href">https://medium.com/media/2a29555640641f1756205ed9f15a2b3c/href</a></iframe><p>Your RightNav.jsx, Burger.jsx, and Navbar.jsx files should have the respective codes below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5c2205e4e2d0b9049899b37b8a4f4da/href">https://medium.com/media/e5c2205e4e2d0b9049899b37b8a4f4da/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cada5e71b52cbc888539fba2f42ebfda/href">https://medium.com/media/cada5e71b52cbc888539fba2f42ebfda/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/620cff0b3bc60aeaa205ef336dacc083/href">https://medium.com/media/620cff0b3bc60aeaa205ef336dacc083/href</a></iframe><p>After this, your app should look as shown below with no styling yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FiqXysHMd62afRsIRpdJxQ.png" /></figure><h4>Apply styles to components</h4><p>Given that we already install styled-components, our RightNav.jsx, Burger.jsx, and Navbar.jsx components will finally look as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ebbb8400aa20daaadaade071bf32435/href">https://medium.com/media/9ebbb8400aa20daaadaade071bf32435/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cb16236fa1791031f6c9e079ce71cdf/href">https://medium.com/media/3cb16236fa1791031f6c9e079ce71cdf/href</a></iframe><p>You can now check your app on the browser and it should look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4YI2Og1kHcd_kYLVEpkXDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aj4AC7q4Qyduz490Yc8l0A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fcAW2sLTfS-31WragIDvJw.png" /></figure><h3>Conclusion</h3><p>Finally, you should have a responsive navigation menu with some nice hamburger animations when clicked. In case you face any problems, you can reference the repository on <a href="https://github.com/dieudonneAwa/responsive-navbar">GitHub</a></p><p>Thanks</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59ce167ed543" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-create-a-responsive-hamburger-navigation-menu-reactjs-and-styled-components-59ce167ed543">How to create a responsive hamburger navigation menu — ReactJS and Styled Components</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>