<?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 Harish  on Medium]]></title>
        <description><![CDATA[Stories by Harish  on Medium]]></description>
        <link>https://medium.com/@harishbalaji369?source=rss-4b31c58bcd29------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*eCaHRlNGrgVBjrmuFwZrRQ.jpeg</url>
            <title>Stories by Harish  on Medium</title>
            <link>https://medium.com/@harishbalaji369?source=rss-4b31c58bcd29------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 06:16:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harishbalaji369/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[Deploying NextJS app on EC2 using PM2, Nginx and SSH]]></title>
            <link>https://blog.coffeeinc.in/deploying-nextjs-app-on-ec2-using-pm2-nginx-and-ssh-2b35ae38ea78?source=rss-4b31c58bcd29------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b35ae38ea78</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Harish ]]></dc:creator>
            <pubDate>Mon, 24 Feb 2025 08:51:53 GMT</pubDate>
            <atom:updated>2025-02-24T08:51:53.465Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQze-yzSucf_GtCb6hhSEw.png" /><figcaption>NextJS app deployed on Amazon EC2</figcaption></figure><p><strong>Hola readers!!! Vanakkam Makkale!!!</strong></p><p>In this blog, we’ll explore the process of deploying Next.js on EC2, giving us full control over our hosting environment.</p><p>While platforms like Vercel and Netlify offer convenience and simplicity, they do have their limitations. By hosting on EC2, we will gain the power to customize our server environment, optimize performance, and even reduce costs in the long run. So grab a cup of coffee, sit back, and get ready to unleash the power of Next.js on EC2. Let’s dive in! 😁</p><h3>Prerequisites</h3><p>We will need the following things:</p><ol><li>AWS Account, use <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/get-set-up-for-amazon-ec2.html#sign-up-for-aws">this documentation</a> to create one.</li><li>Administrative user (optional but a good practice), use <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/get-set-up-for-amazon-ec2.html#create-an-admin">this documentation</a> to setup one.</li></ol><p><strong>Note: </strong>As long as you have created your AWS account less than 12 months ago, and have not already exceeded the free tier benefits for Amazon EC2, it won’t cost us anything to complete this tutorial because we will be selecting options that are within the free tier benefits. Otherwise, you’ll <strong>incur the standard Amazon EC2 usage fees</strong> from the time that you launch the instance until you terminate the instance (which is the final task of this tutorial), even if it remains idle.</p><h3>Setting up EC2 instance</h3><p>Let’s open AWS Console in the browser and search for “EC2”, this will take us to EC2 Dashboard.</p><p>Click on “Instances” in the sidebar. We will be served a page similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-mUutbhqwfMqByC0i8a39g.png" /></figure><p><strong>Note: </strong>AWS keeps on updating their UI (Console) so there might be differences on how we get to the EC2 Dashboard or Instances page 🙂.</p><h4>Step 1</h4><p>Click on “Launch Instances” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dY9k_uoZd9W79j1ib1fzog.png" /></figure><h4>Step 2</h4><p>Let’s give a name for our server like as simple as “NextJS App Server”. Tags will help us to identify the specific server, especially when we have more than one instance running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*7mlTrEQSCPkiaywOc6RwnA.png" /></figure><h4>Step 3</h4><p>Select an AMI (Amazon Machine Image) . We will be using Ubuntu Server 22.04 LTS AMI for this blog and it is eligible for free tier usage 😉.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*j1fXUeXudrUcI8k40bOGWQ.png" /></figure><p>Basically, an AMI (Amazon Machine Image) is a pre-configured template that contains the necessary software, operating system, and configurations required to launch an instance (virtual server) on AWS. Think of an AMI as a snapshot of a specific server setup, including the operating system, applications, and any additional software that is needed. AMIs are the foundation for creating EC2 instances and provide a quick and efficient way to replicate and deploy server environments.</p><p>The Ubuntu image gives us the vanilla version of the OS, allowing us to install the dependencies we require.</p><h4>Step 4</h4><p>Select “t2.micro” as our Instance Type, which also comes under free tier 😉.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*c8SoWSumN2xFSHChPAMZ6Q.png" /></figure><p>We can choose difference Instance type depending on our hardware requirements. In a nutshell, we have to choose bigger or advanced Instance type for more compute power.</p><h4>Step 5</h4><p>EC2 instance requires a key-pair to connect to it through SSH. If you already have a key-pair then choose it and move to step 7 or click on the “Create new key pair” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*BxjcrBffmEi6ar6kEzjCwQ.png" /></figure><h4>Step 6</h4><p>Give a name to the key-pair and we can use default options for other fields. Click on “Create key pair” and it will automatically download the .pem file. Then, choose the newly created key-pair for our EC2 instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*GzY_hAMLKmPTwrT1C9XHfw.png" /></figure><h4>Step 7</h4><p>Let us use the default Network settings, that is Default VPC and other options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*il5Y7LhQHMoRh2M8g-Xm9g.png" /></figure><p>Please use <a href="https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html">this</a> documentation, to learn more about VPC.</p><h4>Step 8</h4><p>We can create a new Security Group for our instance or if you have one, feel free to use it. So, select the “Create security group” option and then check the “Allow SSH traffic from anywhere” and “Allow HTTP traffic from the internet”. Most probably we will use this instance as a web server so it does make sense to have HTTP requested allowed to our instance. If you have SSL certificate then you check the “Allow HTTPS traffic from the internet”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*Tf9ARDbGOO5NwNfI_kBnvQ.png" /></figure><p>Security Groups are like firewall for our instances in AWS. It is important to note that if you allow a specific protocol, then by default all other protocol or requests from any other IP address which is not specified in the rule will be denied.</p><h4>Step 9</h4><p>Again, let’s use the default options for our storage, that is 8GB GP2 root volume.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*VVSHeRkbuerCnFYaVD1QGA.png" /></figure><p>EC2 instances will, by default, have root volumes which cannot be changed once created but can be replaced by a new volume (technically, we can detach a root volume but the instance will not run without a root volume attached to it).</p><h4>Step 10</h4><p>Check the summary and click on “Launch instance”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*qPcD0u53YaTB5rswVK_NtA.png" /></figure><p>Take a sip of your coffee ☕ while AWS is launching our instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vheeUeiXAGNJJAAss5Fqwg.png" /></figure><p>Successs!!! Our instance was initiated successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3V2NLENmM_bxAqTprQEy-A.png" /></figure><p>Initially, our newly created instance will be in “Pending” state for few seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*_1MsdCJFTUuipP5xx3cNfg.png" /></figure><p>And if the instance state changes to “Running”, then we can start to use the instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*5Z4Yd_Dj_Vky5PWZwLp_PA.png" /></figure><p>After launching an instance, it will be listed in our “Instances” page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x8CNoclI-AuC48uEPI2jmw.png" /></figure><p>Our instance will be assigned a Public IPv4 address by AWS, which we will be using to access/connect to the EC2 instance.</p><p><strong>Note: </strong>Please note that the Public IP address (allocated by AWS) will be changed when we restart the instance unless we implement any technique to maintain/use the same IP address like elastic IP.</p><h3>Connect to the instance</h3><p>Let’s connect to the instance from our local machine.</p><p>I am using Ubuntu OS in my local machine, so if you are using Linux or MacOS these steps will be the same, but if you are using window or facing any difficulty in connecting, please feel free to drop a comment or refer <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstances.html">this</a> documentation.</p><p>let’s open a terminal in the same directory, where we have downloaded or saved the key-pair (.pem) file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*23rllISJ83lVCO2e3nZjjg.png" /></figure><p>For SSH connections, we must set the permissions of the key-pair (.pem) file so that only we can read the file. To see the permissions of the file, use:</p><pre>ls -l</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*yEQR5KC8VXHEWaf-extfWg.png" /></figure><p>Change the permission of the file to 400 (read permission only to the user), by using: chmod 400 &lt;KEY_PAIR_NAME&gt;.pem</p><pre>chmod 400 ./nextjs-app-server-key-pair.pem</pre><p>Now, we have changed the permissions of the key-pair (.pem) file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*9eoKqDDGzMoegjmElqecVw.png" /></figure><p>We can connect to our instance using instance’s Public DNS name or IPv6 address or IPv4 address. (AWS documentation mentioned to use either Public DNS or IPv6 address, but now I will be using IPv4 address. It is absolutely your choice of using any of these things).</p><p>Use the following command to connect to the instance using</p><p>Public IPv6 address:</p><pre>ssh -i /path/key-pair-name.pem instance-user-name@instance-IPv6-address</pre><p>or</p><p>Public DNS name:</p><pre>ssh -i /path/key-pair-name.pem instance-user-name@instance-public-dns-name</pre><p>or</p><p>Public IPv4 address:</p><pre>ssh -i /path/key-pair-name.pem instance-user-name@instance-public-IPv4-address</pre><p>The default username for Ubuntu AMIs is “ubuntu”, so let’s use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*klQhUh6JngS8L65ks4yp7g.png" /></figure><p>Check out the default usernames for other AMIs <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connection-prereqs.html">here</a>. While connecting to the server using the username and IP is the norm, you can setup a custom host name to quickly connect by following this article:</p><p><a href="https://blog.coffeeinc.in/how-to-ssh-to-a-remote-server-with-a-custom-host-name-ssh-coffeed-f6415da29e51">How to SSH to a remote server with a custom Host name (ssh coffeed)?</a></p><p>Once you ssh into the server, you will be greeted by the following message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*4LlfOK0Ri9B8hP95OIo6Fg.png" /></figure><p>Now, we can see that we have connected to the instance as our terminal shows the username and private IP address of the instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*SP3nMZ71mFGfIXpuwlYCNA.png" /></figure><p>Always it is a good practice to update our system or server, so let’s do it right away.</p><pre>sudo apt update &amp;&amp; sudo apt upgrade</pre><h3>Deploying NextJS App on EC2</h3><p>Ufffff!!!!😮‍💨 It was a long procedure to create an EC2 instance.</p><p>Let’s move on to creating a Next.js project and deploying it.</p><p>Connect to the instance and change to root user, by</p><pre>sudo su</pre><h3>Setting up the requirements</h3><p>Next.js requires a node server. For our case, let’s install nvm, for managing node versions, by using</p><pre>curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash</pre><p>Close and reopen your ssh connection to start using nvm</p><p>or</p><p>activate nvm, by</p><pre>. ~/.nvm/nvm.sh</pre><p>Then, let’s install node using nvm</p><pre>nvm install node</pre><p>check if it is installed properly, by</p><pre>node -v</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*cR8Hf2rng1UUvQgOs_sFcA.png" /></figure><p>I am gonna use v20, but if you want to use a specific version (for example version 16) then you can use</p><pre>nvm install v16<br><br>nvm use v16</pre><p>By default, node comes with npm, so there is no need to install it separately. To check the version of npm, use</p><pre>npm -v</pre><p>Let’s install PM2, using</p><pre>npm i -g pm2</pre><p>PM2 is a process manager for the JavaScript runtime Node.js, we will discuss why we are using this tool in the later half of this section.</p><p>Then we can install our web server, Nginx.</p><pre>sudo apt install nginx</pre><p>After installing nginx on ubuntu, by default, the service will be running in the background.</p><p>To check if it is working,</p><p>— Take note of the public IPv4 address of our instance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n1-4TZfBmp2folhMIAPvkA.png" /></figure><p>— Open a browser and type “https://&lt;Public_IP_address&gt;”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*7v2KrmS-bRml9ILtZBx-Fw.png" /></figure><p><strong>Note: </strong>We cannot use https request as the security group of our instance was configured not to allow this request.</p><p>If we get the Nginx home page, then the web server is ready to be configured.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IlekoPfAsOig-febqvKN-A.png" /></figure><h4>Setting up a new project</h4><p>Change the directory to “/var/www”</p><pre>cd /var/www</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*yTVPE4MAJQ7QrMFcmh4gkQ.png" /></figure><p>After using “ls” command in the directory we can see a html file, which is the default home page for Nginx.</p><p>Now, let’s create a next project, using</p><blockquote>sudo npx create-next-app@latest &lt;Project_name&gt;</blockquote><p>(no need to use sudo keyword if we are using the root user)</p><pre>sudo npx create-next-app@latest next-project</pre><p>Configure the project by choosing the options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*2MkJq5pR4IqW5Ew--XzbVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*Y0vTxKmP1MSd4J36xFyZCw.png" /></figure><p>Instead of creating a new project, we can also clone it from a repository after installing git.</p><p>Using “ls”, we can see that the new project was created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*rlzWHANBM449v7kj7I1VbQ.png" /></figure><p>Change the directory to our project, by using cd ./&lt;Project-name&gt;</p><pre>cd next-project</pre><p>and let’s install all the dependencies (this is not necessary for newly created project but this is required if you are cloning your poject from GitHub or other platforms)</p><pre>npm install</pre><p>Let’s build our project</p><pre>npm run build</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*mr7VKJCXvVvEnqOdXDSIxg.png" /></figure><p>We will use a tool called PM2 to make sure that our Next.js application is always running. PM2 will even restart the Next.js application if it goes down. Start the Next.js application using PM2:</p><pre>pm2 start npm --name &quot;next-project&quot; -- run dev</pre><p>or</p><pre>pm2 start npm --name &quot;next-project&quot; -- start</pre><p>This command will start the Next.js application with the name “nextjs” using the npm run dev or npm start command. PM2 will automatically restart the application if it crashes or if the server reboots.</p><p>To ensure PM2 starts on boot, run:</p><pre>pm2 startup</pre><p>This command will generate a script that you can copy and paste into your terminal to enable PM2 to start on boot, like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*FQwpqw5qCqVnEi-F4Gbdng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*m8FQur6VMI1siIKhw_MfMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*ANATw0S0lifKrDqdnNNLKQ.png" /></figure><p>Save the current PM2 processes:</p><pre>pm2 save</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*AZEmSmDmiDjeTJlrd3XPNw.png" /></figure><h3>Configure Nginx Server</h3><p>Now, our NextJS app is running and now we have to point the Nginx server to our NextJS app (Node server).</p><p>Lets change our directory, by using</p><pre>cd /etc/nginx/sites-available</pre><p>We can see there is a default site in the directory which is the default home page for Nginx server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*xIljq7q_w4lT0cILKSauVA.png" /></figure><p>Let’s create a file “next-project” and edit the file using nano editor, by using</p><pre>sudo nano ./next-project</pre><p>Copy and paste the below code into the newly created file and change the values server_name, proxy_pass (NextJS app port — like <a href="http://localhost:3000)">http://localhost:3000)</a> and the location path.</p><pre>server {<br>    listen 80;<br>    server_name &lt;IP_ADDRESS&gt;; # Change to your IP adress or domain name <br>    gzip on;<br>    gzip_proxied any;<br>    gzip_types application/javascript application/x-javascript text/css text/javascript;<br>    gzip_comp_level 5;<br>    gzip_buffers 16 8k;<br>    gzip_min_length 256;<br><br>    location /_next/static/ {<br>        alias /var/www/&lt;FOLDER_NAME&gt;/.next/static/; # Change to your app name<br>        expires 365d;<br>        access_log off;<br>    }<br><br>    location / {<br>        proxy_pass http://127.0.0.1:3000; # Change to your app port<br>        proxy_http_version 1.1;<br>        proxy_set_header Upgrade $http_upgrade;<br>        proxy_set_header Connection &#39;upgrade&#39;;<br>        proxy_set_header Host $host;<br>        proxy_cache_bypass $http_upgrade;<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*yqcJYCYBOtnCL884Jq2tzQ.png" /></figure><p>Now, we can see that we have created a new site or file in the directory</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*os8yVPJ9wOgd5Tz8MV6-Cg.png" /></figure><p>Let’s create a link for this file in “/etc/nginx/sites-enabled” directory, to make this site active or enabled, by using</p><pre>sudo ln -s /etc/nginx/sites-available/next-project /etc/nginx/sites-enabled/</pre><p>Test the Nginx configuration for any syntax errors, by</p><pre>sudo nginx -t</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*IIfNnnMHu0oQf6bKAkSw9g.png" /></figure><p>If the configuration test is successful, restart Nginx:</p><pre>sudo service nginx restart</pre><h3>Wrapping up</h3><p>Finally!!! we have completed the deployment and now if we go to the public IP address (http request) in our browser, we will be able to see the default home page of NextJS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XgOBa6zf4nn6LKTDw58nsA.png" /><figcaption>NextJS app deployed on EC2</figcaption></figure><p><strong>Alert!!! Keep In Mind</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8mmcR98gdBln0fut" /><figcaption>meme from iFunny.co (<a href="https://ifunny.co/picture/how-did-you-end-up-in-poverty-gamble-drugs-i-4OHsBlDQ9?s=cl">link</a>)</figcaption></figure><p>(Just Kidding)</p><p>But do not forget to terminate the instance if you do not need it anymore. We can easily terminate an instance by selecting the instance and select Actions &gt; Terminate Instance in the Instances page.</p><p>Hope you have liked and enjoyed this blog. Share your thoughts, suggestions or questions if you have any.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*BJa8lsgr3m0UBanU.gif" /></figure><p>Until next time, Tataaa!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b35ae38ea78" width="1" height="1" alt=""><hr><p><a href="https://blog.coffeeinc.in/deploying-nextjs-app-on-ec2-using-pm2-nginx-and-ssh-2b35ae38ea78">Deploying NextJS app on EC2 using PM2, Nginx and SSH</a> was originally published in <a href="https://blog.coffeeinc.in/">Coffee Byte</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with Vercel Postgres and Next.js 13]]></title>
            <link>https://blog.coffeeinc.in/getting-started-with-vercel-postgres-and-next-js-13-bcb4715f3899?source=rss-4b31c58bcd29------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcb4715f3899</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[vercel]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Harish ]]></dc:creator>
            <pubDate>Wed, 28 Jun 2023 16:47:30 GMT</pubDate>
            <atom:updated>2023-06-28T16:47:30.951Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bSRy7sXE0ZaNoDtFWrfyKQ.png" /></figure><p><strong>Hola readers!!! Vanakkam Makkale!!! </strong>👋</p><p>Recently, Vercel announced a few new storage offerings on their platform: a key-value storage solution using Redis, a full Postgres database, and blob storage for your static files. In this article, I wanted to take the opportunity to explore the Vercel Postgres, a serverless SQL database built for the frontend, powered by Neon.</p><p>Vercel Postgres is designed to work seamlessly with the Next.js App Router (introduced in version 13), components and other frameworks like Next and SvelteKit, making it easy to fetch data from your Postgres database to render dynamic content on the server at the speed of static.</p><p>We can use Vercel Postgres to query, insert, update, or delete data directly inside your components, providing us with powerful server-first data mutations and less client-side JavaScript.</p><h4><strong>Getting Started with Vercel</strong></h4><p>Log in to Vercel or create an account on Vercel, if you do not have one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pbtMpKk85JH_1imnpYmkWw.png" /></figure><p>After creating an account on Vercel, we have to create a new project from a template or by importing a Git Repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5w6PlrR8P0zeU3gr0w_sZA.png" /></figure><p><strong>Setting up a GitHub repository: </strong>Let’s go to GitHub (or your favourite platform) and create a repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LoBiSju4RyD4Pr1fCglD0Q.png" /></figure><ul><li><strong>Name:</strong> Let’s give a name to our project, “vercel-postgresql-demo”</li><li><strong>Public or Private:</strong> It’s upto you whether you want this repo to be public or not.</li><li>Check the “Add a README file” (optional).</li><li>Let’s choose “Node” for the “Add .gitignore” (optional)</li><li>Choose MIT License (or any other license) for license (optional).</li><li>Click on “Create repository” button</li></ul><p>Let’s go back to vercel.com and now we can import the project that we have created now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iyq6IBmJNRBsDvcssFcEFw.png" /></figure><p>Give a name to the project and select “Next.js” for the framework. We will be using Next.js 13 and its new app router feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e4c55ys0kU955QCwZC325g.png" /></figure><p>Click on the “Deploy” button. At this stage, the deployment will fail as we didn’t start to work on the project. Don’t worry, we will fix it.</p><h4>Creating the Database</h4><p>Let’s create our postgresql database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qvP5psrr2X4DGK3ippt-ug.png" /></figure><p>First, go to the project page and then select the <strong>Storage</strong> tab and click on the “Create Database” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j8toP8Uu_72rneEgZTmrDQ.png" /></figure><p>Here, we can see all the available storage services from vercel. Let’s create Postgres Database by selecting the Postgres option and click on the “Continue” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*Mt9Gwivo5g0fjCBj0nuYaw.png" /></figure><p>Click on the “Accept” button after thoroughly reading the terms and conditions 🙂.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*442B-GNYA1HBHXfGZltCFA.png" /></figure><p>Let’s give a name to our database, let it be “postgres-vercel” and select the region of your choice. Finally click on the “Create” button.</p><p><strong>Success!!! </strong>We have successfully created a Postgres Database on vercel.</p><h4>Connecting the Database to our Vercel project</h4><p>Let’s connect the database to our Vercel project. Go to the project dashboard and select the <strong>Storage </strong>tab</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LP11vuE-3aWXpzaK2-j1Yg.png" /></figure><p>Here we can see our database, so let’s connect it by clicking on the “Connect” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3bMwvR4WcsJ2iq_tv6Za3A.png" /></figure><p>Let’s use the default options and click on the “Connect” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*_qYz6Rs2HCcjqNcfNrHw8g.png" /></figure><p>If we get this success message, then we have connected the database to our project successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pouGUFLNIvaarteA8t6_Aw.png" /></figure><p>There we go, we can see our database.🎉🎉 Select the <strong>Query</strong> tab and we can see an input box where we can run our SQL queries</p><h4><strong>Creating a table &amp; Adding to It</strong></h4><p>Let’s create a table without wasting any time.In the input box, run:</p><pre>CREATE TABLE Pets ( Name varchar(255), Owner varchar(255) );</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BrvEZx1vvAsVcDjfA-rNCQ.png" /></figure><p>And here, we can see our table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pbuw-NGDLQo5jQsiwVjCOw.png" /></figure><p>Let’s add values to the table</p><pre>INSERT INTO Pets (Name, Owner) VALUES (&#39;Bruno&#39;, &#39;Harish&#39;);</pre><p>Let’s check our table now</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ed0dPNoutRXcrAogqGqnKA.png" /></figure><p>Let’s add more values to our table</p><pre>INSERT INTO <br>  Pets (Name, Owner) <br>VALUES <br>  (&#39;Charlie&#39;, &#39;Kannu&#39;),<br>  (&#39;Nandu&#39;, &#39;Ammu&#39;),<br>  (&#39;Meenu&#39;, &#39;Ammu&#39;),<br>  (&#39;Sembha&#39;, &#39;Harish&#39;),<br>;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GtAxggg3mjObSTMEWy1vMQ.png" /></figure><p>Okayyyy!!! This data is enough for now. We have successfully created our table for Pets and added entries. Let’s move on to set up our project to get data from our database.</p><h4>Setting up the Next.js Project</h4><p>Let’s get the URL of our repo from GitHub</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H5mAZMmBrWW3ZC3-Oe_G4Q.png" /></figure><p>Let’s create a directory in our local machine and clone the git repo.</p><pre>git clone &lt;REPO_URL&gt;</pre><p>Change the directory, by</p><pre>cd ./&lt;PROJECT_NAME&gt;</pre><p>Let’s create a NextJS app using</p><pre>npx create-next-app@latest .</pre><p>Configure the project by choosing the options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i7eFCJ9zErg5YbXOc2VNog.png" /></figure><p>It is absolutely up to you how you want to configure or setup your project.</p><p><strong>Note:</strong> I am gonna use the latest App Router feature of NextJS 13. If you want to use Page Router feature then select “No” for “Use App Router” while creating the project.</p><p>Let’s make our initial commit. Select the “Source Control” in your VSCode and let’s commit our changes with a commit message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zki2TnOxLXQwjWKrrnuPmw.png" /></figure><p>or by</p><pre>git commit -m &quot;Commit message&quot;</pre><h4>Connecting to Vercel</h4><p>Let’s install the latest version of Vercel CLI</p><pre>npm i -g vercel@latest</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MrL2y9M0fz7LX_htifki8w.png" /></figure><p>and then install the Vercel Postgres package</p><pre>npm i @vercel/postgres</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*coFSuUCunSfzONajPwCmWQ.png" /></figure><p>We are ready to link the project with vercel, run</p><pre>vercel link</pre><p>select the login method, and get authenticated</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*mapVZzmyOZ4eqGWnM1zl_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*zHi28gIAQ9lbcfw51RP0Xw.png" /></figure><ul><li>Choose <strong>Y </strong>for “Set up &lt;PROJECT_NAME&gt; ?“</li><li>Select the scope for our project</li><li>Choose <strong>Y</strong> for “Link the existing project?”, as we have already created our database and project.</li><li>Enter the name of our Vercel project</li></ul><p>Now, we have successfully linked our project to Vercel. When we created our Postgres database, our API URL and credentials were created as environment variables. We’ll need to <strong>pull the latest environment variables from Vercel </strong>to get our local project working with the Postgres database.</p><pre>vercel env pull .env.development.local</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BF5QUHkosJzlZ5BTQYV5Uw.png" /></figure><p>This should create a .env.development.local file with all environment variables required for our project.</p><h4><strong>Creating an API endpoint</strong></h4><p>Let’s create a folder named <strong><em>api</em></strong> inside the <strong><em>app </em></strong>folder. Then, create a folder name <strong><em>get-pets</em> </strong>inside <strong><em>api</em></strong> folder and create a file named <strong><em>route.ts </em></strong>inside the <strong><em>get-pets</em></strong> folder.</p><p>Let’s write a function (handler) to get data from the Vercel Postgres database.</p><pre>// app/api/get-pets/route.ts<br><br>import { db } from &#39;@vercel/postgres&#39;;<br>import { NextResponse } from &#39;next/server&#39;;<br> <br>export async function GET() {<br>  const client = await db.connect();<br>  let pets;<br>  <br>  try {<br>    pets = await client.sql`SELECT * FROM Pets;`;<br>  } catch (error) {<br>    return NextResponse.json({ error });<br>  }<br> <br>  return NextResponse.json({ data: pets });<br>}</pre><p><strong>Good To Know: </strong><strong>sql</strong> is a function that translates your query into a native Postgres parametrized query to help prevent SQL injection.</p><p><strong>Note: </strong>As we have already pulled the env variables from vercel earlier, it will be used here to connect to the database and retrieve data from it.</p><p>Soooooo…. our API endpoint is now ready and we create a simple home page and calls this internal NextJS API to get our data.</p><h4><strong>Calling the Internal API</strong></h4><p>Let’s create an async function to call our internal API and call this function from an useEffect hook. To check, we can console log the data returned to us.</p><pre>  const getData = async () =&gt; {<br>    await fetch(&#39;/api/get-pets&#39;)<br>    .then( res =&gt; res.json() )<br>    .then( data =&gt; {<br>      console.log(data.data.rows);<br>    })<br>    .catch( err =&gt; console.log(err) )<br>    .finally( () =&gt; {<br>      setLoading(false);<br>    })<br>  }</pre><p>Let’s add an useEffect block to call this function whenever this component is rendered.</p><pre>  useEffect(() =&gt; {<br>    getData();<br>  }, [])</pre><p>And, we can remove all the content inside the return block expect &lt;main&gt;&lt;/main&gt; . So, now our home page will be like:</p><pre>&quot;use client&quot;<br><br>// app/page.tsx<br><br>import { useEffect, useState } from &quot;react&quot;<br><br>export default function Home() {<br><br>  const getData = async () =&gt; {<br>    await fetch(&#39;/api/get-pets&#39;)<br>    .then( res =&gt; res.json() )<br>    .then( data =&gt; {<br>      console.log(data.data.rows);<br>    })<br>    .catch( err =&gt; console.log(err) )<br>    .finally( () =&gt; {<br>      // set loading to false<br>    })<br>  }<br><br>  useEffect(() =&gt; {<br>    getData();<br>  }, [])<br><br>  return (<br>    &lt;main&gt;<br>    &lt;/main&gt;<br>  )<br>}</pre><p><strong>Note: </strong>We have to use &quot;use client&quot; in the component, as we have used useEffect hook and we will be using useState hook later. By default, all parent components (am referring to the components that are at the top-level or not inside any client component) are <strong>server components </strong>where we cannot use hooks.</p><p>Then, run</p><pre>npm run dev</pre><p>Open up a browser and type localhost:3000, we can see our app is running (blank screen without any error messages, as we have not completed our home page).</p><p>Let’s open the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e1EaXCeGUQA099i-YFOayg.png" /></figure><p>It’s working perfectly, as the data is being displayed in the console. So, let’s save the data in a state variable.</p><pre>  // Modified getData function<br><br>  const [pets, setPets] = useState([]);<br>  const [loading, setLoading] = useState(true);<br><br>  const getData = async () =&gt; {<br>    await fetch(&#39;/api/get-pets&#39;)<br>    .then( res =&gt; res.json() )<br>    .then( data =&gt; {<br>      setPets(data.data.rows);<br>    })<br>    .catch( err =&gt; console.log(err) )<br>    .finally( () =&gt; {<br>      setLoading(false);<br>    })<br>  }<br><br>  useEffect(() =&gt; {<br>    getData();<br>  }, [])</pre><p>Let’s render our data.</p><pre>&lt;main className=&quot;h-screen flex justify-center items-center&quot;&gt;<br>  {<br>    loading?<br>      &lt;div&gt;<br>        Getting data from Vercel Postgres database...<br>      &lt;/div&gt;<br>    :<br>      &lt;div className=&quot;w-fit flex flex-col justify-center items-center&quot;&gt;<br>        &lt;table className=&quot; border border-white&quot;&gt;<br>          &lt;thead className=&quot;font-semibold text-xl&quot;&gt;<br>            &lt;tr className=&quot;&quot;&gt;<br>              &lt;td&gt;<br>                Name<br>              &lt;/td&gt;<br>              &lt;td&gt;<br>                Owner<br>              &lt;/td&gt;<br>            &lt;/tr&gt;<br>          &lt;/thead&gt;<br>          {<br>            (pets.length &gt; 0)?<br>            &lt;tbody&gt;<br>              {<br>                pets.map((pet:any, index) =&gt; (<br>                  &lt;tr&gt;<br>                    &lt;td&gt;<br>                      {pet.name}<br>                    &lt;/td&gt;<br>                    &lt;td&gt;<br>                      {pet.owner}<br>                    &lt;/td&gt;<br>                  &lt;/tr&gt;<br>                ))<br>              }<br>            &lt;/tbody&gt;<br>            :<br>            &lt;tbody&gt;<br>              No data available<br>            &lt;/tbody&gt;<br>          }<br>        &lt;/table&gt;<br>        &lt;div className=&quot;mt-10 text-xs &quot;&gt;<br>          data received from Vercel Postgres<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>  }<br>&lt;/main&gt;</pre><p>Here is how it looks when loading:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VcXbL0P83uxh7lyhDW2Jag.png" /></figure><p>Here is how it looks when it is loaded:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6DCyNPpyjXoq6FSJud3oA.png" /></figure><p>Here is the final page.tsx</p><pre>&quot;use client&quot;<br>import { useEffect, useState } from &quot;react&quot;<br><br>export default function Home() {<br>  const [pets, setPets] = useState([]);<br>  const [loading, setLoading] = useState(true);<br><br>  const getData = async () =&gt; {<br>    await fetch(&#39;/api/get-pets&#39;)<br>    .then( res =&gt; res.json() )<br>    .then( data =&gt; {<br>      setPets(data.data.rows);<br>      console.log(data.data.rows);<br>    })<br>    .catch( err =&gt; console.log(err) )<br>    .finally( () =&gt; {<br>      setLoading(false);<br>    })<br>  }<br><br>  useEffect(() =&gt; {<br>    getData();<br>  }, [])<br><br>  return (<br>    &lt;main className=&quot;h-screen flex justify-center items-center&quot;&gt;<br>      {<br>        loading?<br>          &lt;div&gt;<br>            Getting data from Vercel Postgres database...<br>          &lt;/div&gt;<br>        :<br>          &lt;div className=&quot;w-fit flex flex-col justify-center items-center&quot;&gt;<br>            &lt;table className=&quot; border border-white&quot;&gt;<br>              &lt;thead className=&quot;font-semibold text-xl&quot;&gt;<br>                &lt;tr className=&quot;&quot;&gt;<br>                  &lt;td&gt;<br>                    Name<br>                  &lt;/td&gt;<br>                  &lt;td&gt;<br>                    Owner<br>                  &lt;/td&gt;<br>                &lt;/tr&gt;<br>              &lt;/thead&gt;<br>              {<br>                (pets.length &gt; 0)?<br>                &lt;tbody&gt;<br>                  {<br>                    pets.map((pet:any, index) =&gt; (<br>                      &lt;tr&gt;<br>                        &lt;td&gt;<br>                          {pet.name}<br>                        &lt;/td&gt;<br>                        &lt;td&gt;<br>                          {pet.owner}<br>                        &lt;/td&gt;<br>                      &lt;/tr&gt;<br>                    ))<br>                  }<br>                &lt;/tbody&gt;<br>                :<br>                &lt;tbody&gt;<br>                  No data available<br>                &lt;/tbody&gt;<br>              }<br>            &lt;/table&gt;<br>            &lt;div className=&quot;mt-10 text-xs &quot;&gt;<br>              data received from Vercel Postgres<br>            &lt;/div&gt;<br>          &lt;/div&gt;<br>      }<br>    &lt;/main&gt;<br>  )<br>}</pre><h3>Wrapping up</h3><p>Yay!!! We have completed our objective of exploring Vercel Postgres database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/0*q9J7-rKgHkQz6DPW" /></figure><p>Here is our final home page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6DCyNPpyjXoq6FSJud3oA.png" /></figure><p>Feel free to check the whole project on <a href="https://github.com/Harish-b-03/vercel-postgresql-demo">GitHub</a>.</p><p>I hope you have enjoyed working on this project as much as I did. Please let me know your comments and suggestions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*kUpDpMlC5bhXVmPF.gif" /></figure><p>Byeeee….. Tata!!!!!</p><p><em>Edited and Curated by </em><a href="https://medium.com/u/16989b968303?source=post_page-----cf53715e0b95--------------------------------"><em>Gaurav G</em></a><em> for </em><a href="https://www.coffeeinc.in/"><em>Coffee</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcb4715f3899" width="1" height="1" alt=""><hr><p><a href="https://blog.coffeeinc.in/getting-started-with-vercel-postgres-and-next-js-13-bcb4715f3899">Getting started with Vercel Postgres and Next.js 13</a> was originally published in <a href="https://blog.coffeeinc.in/">Coffee Byte</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Component in React to filter Product Categories in the Frontend]]></title>
            <link>https://blog.coffeeinc.in/building-a-component-in-react-to-filter-product-categories-in-the-frontend-cb9daa591a5f?source=rss-4b31c58bcd29------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb9daa591a5f</guid>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Harish ]]></dc:creator>
            <pubDate>Tue, 23 May 2023 13:25:18 GMT</pubDate>
            <atom:updated>2023-05-23T13:25:18.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HAJ3KLL2H03ckMPOw971Cw.png" /></figure><p><strong>Hola readers!!! Vanakkam Makkale!!!</strong></p><p>In this blog, we will explore how to create a filter component in React that’s both powerful and user-friendly. We will start by discussing the benefit of using a filter component and how it can enhance the user experience. Then, we will dive into the technical details of building a filter component in React, including the use of state and props, handling events, and rendering the results.</p><p>Whether you’re building an e-commerce platform, a search engine, or a data-heavy application, a filter component can help your users find exactly what they’re looking for in a flash, thus improving the user experience. So let’s roll up our sleeves, fire up our favorite code editor, grab a cup of coffee (or your beverage of choice) and get ready to build a filter component that will make your users’ lives easier and your codebase cleaner.</p><p>We will be creating a component for front-end filtering and we will NOT send the filters back to the server (through query) to get the filtered response.</p><p>Let’s do this!</p><h3>Getting Started</h3><p>We will be using create-react-app to set up the base project for this tutorial. Run the following command in the terminal:</p><pre>npx create-react-app filter</pre><p>after the setup,</p><ol><li>Delete all the files in src folder except index.js and index.css .</li><li>Remove all the contents in the index.js file and paste the following code</li></ol><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom/client&#39;;<br>import &#39;./index.css&#39;;<br>import App from &#39;./App&#39;;<br><br>const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));<br>root.render(<br>  &lt;React.StrictMode&gt;<br>    &lt;App /&gt;<br>  &lt;/React.StrictMode&gt;<br>);</pre><p>3. Remove all the files in public folder except index.html</p><p>4. Create app.jsx under the src folder and use rafce (react es7 snippet) to create a template component.</p><p>5. Install Tailwind CSS by using</p><pre>npm install -D tailwindcss<br>npx tailwindcss init -p</pre><p>5.1. Configure your template paths and add all of your template files in your tailwind.config.js file.</p><pre>/** tailwind.config.js */<br>/** @type {import(&#39;tailwindcss&#39;).Config} */<br>module.exports = {<br>  content: [<br>    &quot;./src/**/*.{html,js,jsx,ts,tsx}&quot;, <br>    &quot;./src/**/**/*.{html,js,jsx,ts,tsx}&quot;,<br>    &quot;./src/pages/**/*.{html,js,jsx,ts,tsx}&quot;,<br>  ],<br>  theme: {<br>    extend: {},<br>  },<br>  plugins: [],<br>}</pre><p>5.2. Add the @tailwind directives for each Tailwind’s layers to your index.css file. Remove all the CSS code in the file.</p><pre>/** global.css */<br>@tailwind base;<br>@tailwind components;<br>@tailwind utilities;</pre><p>6. Run npm start in the terminal to start the localhost:3000 where our React app will be hosted. We can also see all our changes there.</p><h3>Data</h3><p><a href="https://dummyjson.com/">DummyJSON</a> is a free online REST API that you can use whenever you need some placeholder data for your front-end website or single-page application without running any server-side code. It’s awesome for teaching purposes, sample codes, testing, prototyping.</p><p>We are going to use the products endpoint of the dummyjson API, instead of using a dummy local data, to simulate real-world scenario. Here is an example of the response:</p><pre>{<br>  &quot;products&quot;: [<br>    {<br>      &quot;id&quot;: 1,<br>      &quot;title&quot;: &quot;iPhone 9&quot;,<br>      &quot;description&quot;: &quot;An apple mobile which is nothing like apple&quot;,<br>      &quot;price&quot;: 549,<br>      &quot;discountPercentage&quot;: 12.96,<br>      &quot;rating&quot;: 4.69,<br>      &quot;stock&quot;: 94,<br>      &quot;brand&quot;: &quot;Apple&quot;,<br>      &quot;category&quot;: &quot;smartphones&quot;,<br>      &quot;thumbnail&quot;: &quot;...&quot;,<br>      &quot;images&quot;: [&quot;...&quot;, &quot;...&quot;, &quot;...&quot;]<br>    },<br>    {...},<br>    {...},<br>    {...}<br>    // 30 items<br>  ],<br><br>  &quot;total&quot;: 100,<br>  &quot;skip&quot;: 0,<br>  &quot;limit&quot;: 30<br>}</pre><p>We will also be using /products/categories endpoint to get the list of categories and here is an example of the response:</p><pre>[<br>  &quot;smartphones&quot;,<br>  &quot;laptops&quot;,<br>  &quot;fragrances&quot;,<br>  &quot;skincare&quot;,<br>  &quot;groceries&quot;,<br>  &quot;home-decoration&quot;,<br>  &quot;furniture&quot;,<br>  &quot;tops&quot;,<br>  &quot;womens-dresses&quot;,<br>  &quot;womens-shoes&quot;,<br>  &quot;mens-shirts&quot;,<br>  &quot;mens-shoes&quot;,<br>  &quot;mens-watches&quot;,<br>  &quot;womens-watches&quot;,<br>  &quot;womens-bags&quot;,<br>  &quot;womens-jewellery&quot;,<br>  &quot;sunglasses&quot;,<br>  &quot;automotive&quot;,<br>  &quot;motorcycle&quot;,<br>  &quot;lighting&quot;<br>]</pre><p>And we will also implement this component without this products/categories API (by manually collecting all the categories from the products list) in later part of this blog.</p><h3>Getting data from API</h3><p>Lets create a async function getCategories to call the API to get all the categories and then we can store it in categories state variable.</p><pre>// App.jsx<br>const [loading, setLoading] = useState(false);<br><br>const getCategories = async () =&gt; {<br>  setLoading(true);<br>  <br>  await fetch(&#39;https://dummyjson.com/products/categories&#39;)<br>    .then(res =&gt; res.json())<br>    .then(data =&gt; <br>        setCategories(data);<br>    })<br>    .catch(err =&gt; alert(err))<br>    .finally(()=&gt;{<br>        setLoading(false);<br>    })<br>}</pre><p>Also, we will create a logic to get all the categories from the product list, without using this API, in the later part of this blog.</p><p>Now, we can go ahead and get all the products from the API,</p><pre>// App.jsx<br>const [productList, setProductList] = useState([]);<br><br>const getProducts = async () =&gt; {<br>  setLoading(true);<br>  <br>  await fetch(&#39;https://dummyjson.com/products&#39;)<br>  .then(res =&gt; res.json())<br>  .then(data =&gt; .then(data =&gt; {<br>      setProductList(data.products);<br>      getCategories(); // get the categories list<br>  })<br>  .catch(err =&gt; alert(err))<br>  .finally(()=&gt;{<br>      setLoading(false);<br>  })<br>}<br><br>useEffect(() =&gt; {<br>  getProducts();<br>}, [])</pre><p>Here we have defined a <strong>async</strong> function getProducts to call the API and then we have stored the products-list in our productList state variable. Then, we used useEffect , which will trigger when the component mounts, to call the getProducts function.</p><h3>Building the Filter Component &amp; Logic</h3><p>With all the data in place, we can proceed with developing the core logic for selecting categories and filtering the data.</p><p>Lets create a state selectedCategories to store the list of all the selected categories. Please take note that we will be designing this component to enable simultaneous selection of multiple categories.</p><pre>  const [selectedCategories, setSelectedCategories] = useState([]);</pre><p>And we can create functions to add, remove and reset this list of selected categories.</p><pre>  const addCategory = (category) =&gt; {<br>    if(!selectedCategories.includes(category)){<br>        setSelectedCategories(prev =&gt; ([...prev, category]))<br>    }     <br>  }<br><br>  const removeCategory = (category) =&gt; {<br>    if(selectedCategories.includes(category)){<br>        const removedList = selectedCategories.filter((item) =&gt; (item !== category));<br>        setSelectedCategories(removedList);<br>    }<br>  }<br><br>  const resetCategory = () =&gt; { // this function will be used to clear the filter<br>    setSelectedCategories([]); <br>  }</pre><p>Okaayyy!!! Lets ….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*OgtKHnGz5iIWWBOZ" /><figcaption>Gif from giphy.com</figcaption></figure><p>…develop the logic for filtering data.</p><pre>  const [fileredProductList, setFilteredProductList] = useState([]);<br>  <br>  useEffect(() =&gt; {<br>    if(selectedCategories.length === 0){<br>        setFilteredProductList(productList);<br>    } else{<br>        setFilteredProductList(productList.filter((item)=&gt;(selectedCategories.includes(item.category))));<br>    }<br>  }, [selectedCategories, productList])</pre><p>Here, we have created a state variable filteredProductList to store the filtered list of products and defined an useEffect that will be triggered whenever selectedCategories and productList variables changes.</p><p>In the event that the user modifies the filters, such as adding or removing a category, the following block of code will be executed. Within this block of code, we initially verify whether the selectedCategories list is empty. If it is empty, the filteredProductList will be set to the original productList. However, if it is not empty, we will extract the product items from the productList that have the selected category.</p><h4>The Main Components</h4><p>Using the categories and filteredProducts state variables, let’s create filter tags and product card.</p><pre><br>&lt;div className=&#39;relative w-full h-[15%] flex items-center overflow-x-auto&#39;&gt;<br>  &lt;span className=&#39;mx-3 ml-5 font-medium&#39;&gt; Categories: &lt;/span&gt;<br>    {<br>        categories.map((category) =&gt; (<br>            &lt;div<br>                onClick={() =&gt; {<br>                    if(selectedCategories.includes(category)){<br>                        removeCategory(category);<br>                    } else{<br>                        addCategory(category);<br>                    }<br>                }} <br>                className={`w-fit min-w-fit h-8 mx-2 px-5 py-2 flex flex-row justify-center items-center text-sm border break-keep rounded-3xl cursor-pointer transition-all duration-300 ${(selectedCategories.includes(category))?&#39;border-blue-500 bg-blue-500 text-white&#39;:&#39; border-gray-500 bg-white text-gray-900&#39;} `}&gt;<br>                {category.split(&quot;-&quot;).join(&quot; &quot;)}<br>            &lt;/div&gt;<br>        ))<br>    }<br>    &lt;div<br>        onClick={() =&gt; resetCategory()} <br>        className={`${(selectedCategories.length&gt;0)?&#39;opacity-100&#39;:&#39;opacity-0 pointer-events-none&#39;} sticky right-0 w-fit h-full px-5 flex justify-center items-center text-blue-500 bg-white backdrop-blur-lg cursor-pointer hover:text-blue-700 transition-all duration-300`}<br>    &gt;<br>        clear<br>    &lt;/div&gt;<br>&lt;/div&gt; </pre><p>In this section, we have implemented filter tags that allow for the addition and removal of categories depending on whether they have been selected or not. This is how it looks</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x3UyWQbQGw0gfMs_qsjZSQ.png" /><figcaption>Default view of the section</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5gR6Hz0MphuAmJmxSlbnwg.png" /><figcaption>When a category is selected</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQ9z6pyjBEiqDVOIeNg4Iw.png" /><figcaption>When multiple categories are selected</figcaption></figure><p>Now, lets create simple ProductList component to display the product items. Create a new file named ProductList.jsx under src folder</p><p>We will filteredProducts state, that contains the filtered list of product items, and not the productList state variable.</p><pre>// ProductList.jsx<br>const ProductList = ({filteredProductList, loading}) =&gt; {<br>  <br>  if(loading)<br>    return &lt;&gt;Loading&lt;/&gt; // use your loading state or component<br><br>  return (<br>    &lt;div className=&quot;w-full h-[85%] px-5&quot;&gt;<br>        &lt;div className=&quot;w-full&quot;&gt;Products: &lt;/div&gt;<br>        &lt;div className=&quot;w-full h-full flex flex-wrap gap-1 justify-between items-start overflow-y-auto&quot;&gt;<br>            {<br>                filteredProductList.map((product) =&gt; (<br>                    &lt;div key={product.id} className=&#39;w-[19%] h-fit my-3 rounded-xl overflow-hidden border border-gray-200&#39;&gt;<br>                        &lt;img<br>                            src={product.thumbnail}<br>                            alt=&#39;product&#39;<br>                            className=&#39;w-full h-28 object-cover&#39;<br>                        /&gt;<br>                        &lt;div className=&quot;mt-2 mb-2 px-3&quot;&gt;<br>                            &lt;div className=&quot;font-semibold&quot;&gt;<br>                                {(product.title.length &gt; 25)? product.title.substring(0,22) + &#39;...&#39;: product.title}<br>                            &lt;/div&gt;<br>                            &lt;div className=&quot;text-sm text-gray-600&quot;&gt;<br>                                {product.category}<br>                            &lt;/div&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                ))<br>            }<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>export default ProductList</pre><p>Here is how it looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IKmqECUUeXRJOIQl-9OZLQ.png" /></figure><p><strong>Getting the categories list from products API (without categories API) — </strong>To get list of all categories manually, instead of using the API, we can modify the getCategories function like this:</p><pre>const getCategories = (products) =&gt; {<br>  setLoading(true);<br><br>  if(products.length &gt; 0){<br>      const unique_categories = [];<br><br>      products.map((item) =&gt; {<br>          if(!unique_categories.includes(item.category)){<br>              unique_categories.push(item.category);<br>          }<br>      })<br><br>      setCategories(unique_categories);<br><br>  } else {<br>      setCategories([]);<br>  }<br><br>  setLoading(false);<br>}</pre><p><strong>Note: </strong>We have passed the list of product items to this function, so if you are using this function then change the function calling in getProducts from getCategories() to getCategories(data.products).</p><h4>Wrapping up</h4><p>Yay!!! We have completed the component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/0*JQUrCpzMHb83qzXz" /></figure><p>Lets have a look at App.jsx.</p><pre>import React, { useEffect, useState } from &#39;react&#39;<br>import ProductList from &#39;./ProductList&#39;;<br><br>const App = () =&gt; {<br>  <br>  const [loading, setLoading] = useState(false);<br>  const [productList, setProductList] = useState([]);<br>  const [categories, setCategories] = useState([]);<br>  const [selectedCategories, setSelectedCategories] = useState([]);<br>  const [fileredProductList, setFilteredProductList] = useState([]);<br><br>  const addCategory = (category) =&gt; {<br>    if(!selectedCategories.includes(category)){<br>        setSelectedCategories(prev =&gt; ([...prev, category]))<br>    }     <br>  }<br><br>  const removeCategory = (category) =&gt; {<br>    if(selectedCategories.includes(category)){<br>        console.log(selectedCategories)<br>        const removedList = selectedCategories.filter((item) =&gt; (item !== category));<br>        setSelectedCategories(removedList);<br>    }<br>  }<br><br>  const resetCategory = () =&gt; {<br>    setSelectedCategories([]);<br>  }<br><br>  useEffect(() =&gt; {<br>    if(selectedCategories.length === 0){<br>        setFilteredProductList(productList);<br>    } else{<br>        setFilteredProductList(productList.filter((item)=&gt;(selectedCategories.includes(item.category))));<br>    }<br>  }, [selectedCategories, productList])<br><br>  const getCategories = async () =&gt; {<br>    setLoading(true);<br><br>    await fetch(&#39;https://dummyjson.com/products/categories&#39;)<br>    .then(res =&gt; res.json())<br>    .then(data =&gt; {<br>        setCategories(data);<br>    })<br>    .catch(err =&gt; alert(err))<br>    .finally(()=&gt;{<br>        setLoading(false);<br>    })<br>  }<br><br>  const getProducts = async () =&gt; {<br>    setLoading(true);<br>    <br>    await fetch(&#39;https://dummyjson.com/products&#39;)<br>    .then(res =&gt; res.json())<br>    .then(data =&gt; {<br>        setProductList(data.products);<br>        setFilteredProductList(data.products);<br>        getCategories(); // get the categories list<br>    })<br>    .catch(err =&gt; alert(err))<br>    .finally(()=&gt;{<br>        setLoading(false);<br>    })<br>  }<br><br>  useEffect(() =&gt; {<br>    getProducts();<br>  }, [])<br>  <br>  return (<br>    &lt;div className=&#39;w-screen h-screen px-5 bg-gray-100 flex justify-center items-center&#39;&gt;<br>        &lt;div className=&#39;w-full h-[90%] rounded-md bg-white&#39;&gt; <br>            &lt;div className=&#39;relative w-full h-[15%] flex items-center overflow-x-auto&#39;&gt;<br>                &lt;span className=&#39;mx-3 ml-5 font-medium&#39;&gt; Categories: &lt;/span&gt;<br>                {<br>                    categories.map((category) =&gt; (<br>                        &lt;div<br>                            onClick={() =&gt; {<br>                                if(selectedCategories.includes(category)){<br>                                    removeCategory(category);<br>                                } else{<br>                                    addCategory(category);<br>                                }<br>                            }} <br>                            className={`w-fit min-w-fit h-8 mx-2 px-5 py-2 flex flex-row justify-center items-center text-sm border break-keep rounded-3xl cursor-pointer transition-all duration-300 ${(selectedCategories.includes(category))?&#39;border-blue-500 bg-blue-500 text-white&#39;:&#39; border-gray-500 bg-white text-gray-900&#39;} `}&gt;<br>                            {category.split(&quot;-&quot;).join(&quot; &quot;)}<br>                        &lt;/div&gt;<br>                    ))<br>                }<br>                &lt;div<br>                    onClick={() =&gt; resetCategory()} <br>                    className={`${(selectedCategories.length&gt;0)?&#39;opacity-100&#39;:&#39;opacity-0 pointer-events-none&#39;} sticky right-0 w-fit h-full px-5 flex justify-center items-center text-blue-500 bg-white backdrop-blur-lg cursor-pointer hover:text-blue-700 transition-all duration-300`}<br>                &gt;<br>                    clear<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;ProductList filteredProductList={fileredProductList} loading={loading} /&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>export default App</pre><p>Here is the final output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*Ty0BjoBdu-ItHTXzwjjX0A.gif" /></figure><p>Feel free to check the whole project on <a href="https://github.com/Harish-b-03/filter">GitHub</a>.</p><p>I hope you have enjoyed working on this project as much as I did. Please let me know your comments and suggestions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*lkXGhcBwqNiymulQ.gif" /></figure><p>Byeeee….. Tata!!!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb9daa591a5f" width="1" height="1" alt=""><hr><p><a href="https://blog.coffeeinc.in/building-a-component-in-react-to-filter-product-categories-in-the-frontend-cb9daa591a5f">Building a Component in React to filter Product Categories in the Frontend</a> was originally published in <a href="https://blog.coffeeinc.in/">Coffee Byte</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recipe GPT : Building a NextJS Web App to get a Recipe with Ingredients using GPT API — Part 2]]></title>
            <link>https://blog.coffeeinc.in/recipe-gpt-building-a-nextjs-web-app-to-get-a-recipe-with-ingredients-using-gpt-api-part-2-2813598733dd?source=rss-4b31c58bcd29------2</link>
            <guid isPermaLink="false">https://medium.com/p/2813598733dd</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[recipe]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Harish ]]></dc:creator>
            <pubDate>Thu, 04 May 2023 14:30:33 GMT</pubDate>
            <atom:updated>2023-05-04T14:30:33.968Z</atom:updated>
            <content:encoded><![CDATA[<h3>Recipe GPT : Building a NextJS Web App to get a Recipe with Ingredients using GPT API — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4B7uh1C6L85KjGyvE92P-g.png" /><figcaption>Avocado Grilled Cheese Sandwich by RecipeGPT</figcaption></figure><p><strong>Hola readers!!! Vanakkam Makkale!!!</strong></p><p>Welcome back!!! 👋 This is the second part of building RecipeGPT, a web-app using GPT API. Incase you have missed the first part, feel free to check it out <a href="https://blog.coffeeinc.in/recipe-gpt-building-a-nextjs-web-app-to-get-a-recipe-with-ingredients-using-gpt-api-part-1-89a2a16e137d">Part 1</a>.</p><p>Lets remind ourselves what we did in the first part:</p><ul><li>Project Flow Outline</li><li>Set up a NextJS project</li><li>Dataset for the ingredients added</li><li>Developed the Main Components</li></ul><p>So, without further ado, let us hop back into building our project. This article mainly deals with bring all our components together and tying in the functionality to it.</p><h3>The Main Page</h3><p>Create a new page in the pages directory and call it index.jsx. This is the page where we are going to assemble our components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2UE270vlJn-KaAVcwuuG_g.gif" /><figcaption>React Components… Assemble!</figcaption></figure><p>Below is the code for the main part of the Home component. As you can see we have brought in the components we build together here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nh40OJ-BYjS2f5N61ZVH4A.png" /><figcaption>The index page of RecipeGPT</figcaption></figure><ol><li>TopBar</li><li>SelectedIngredient</li><li>SearchBox</li><li>Flyout — The Results Flyout</li><li>OpenAIKeyPopup</li></ol><pre>&lt;&gt;<br>  &lt;Head&gt;<br>      &lt;title&gt;recipe - GPT&lt;/title&gt;<br>      &lt;meta<br>          name=&quot;description&quot;<br>          content=&quot;RecipeGPT is a recipe recommendation app built on OpenAI GPT-3 API&quot;<br>      /&gt;<br>      &lt;meta<br>          name=&quot;viewport&quot;<br>          content=&quot;width=device-width, initial-scale=1&quot;<br>      /&gt;<br>      &lt;link rel=&quot;icon&quot; href=&quot;/favicon.ico&quot; /&gt;<br>  &lt;/Head&gt;<br>  &lt;main className=&quot;w-full h-screen p-0 m-0 flex flex-col justify-between items-center bg-black&quot;&gt;<br>      &lt;TopBar /&gt;<br><br>      &lt;div className=&quot;pt-[70px] w-full h-full&quot;&gt;<br>          &lt;SelectedIngredient<br>              ingredients={selectedIngredients}<br>              setSelectedIngredients={setSelectedIngredients}<br>          /&gt;<br><br>          &lt;div className=&quot;w-full h-[60%] md:h-[70%] md:overflow-y-scroll flex justify-center items-center&quot;&gt;<br>              &lt;div className=&quot;relative&quot;&gt;<br>                  &lt;SearchBox<br>                      clearSearch={clearSearch}<br>                      onChangeInput={onChangeInput}<br>                      loading={loading}<br>                      search={search}<br>                      filteredIngredients={filteredIngredients}<br>                      addIngredient={addIngredient}<br>                      handleSubmit={handleSubmit}<br>                  /&gt;<br>              &lt;/div&gt;<br>          &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;Toaster position=&quot;bottom-center&quot; gutter={8} /&gt;<br><br>      &lt;Footer handleSubmit={handleSubmit} /&gt;<br><br>      &lt;Flyout<br>          showFlyout={showFlyout}<br>          closeFlyout={closeFlyout}<br>          response={response}<br>      /&gt;<br><br>      {showKeyInput &amp;&amp; (<br>          &lt;OpenAIKeyPopup<br>              hideKeyInput={hideKeyInput}<br>              callGetResponse={callGetResponse}<br>              onChange={(e: any) =&gt; {<br>                  setApiKey(e.target.value);<br>              }}<br>          /&gt;<br>      )}<br><br>      {loading &amp;&amp; &lt;Loading /&gt;}<br>  &lt;/main&gt;<br>&lt;/&gt;</pre><h4>Variables</h4><p>We have a number of variables that we use to save the state of data on the page.</p><pre>const [selectedIngredients, setSelectedIngredients] = useState([]);<br>const [search, setSearch] = useState(&quot;&quot;);<br>const [filteredIngredients, setFilteredIngredients] = useState(ingredients);<br>const [showFlyout, setShowFlyout] = useState(false);<br>const [response, setResponse] = useState(&quot;&quot;);<br>const [loading, setLoading] = useState(false);<br>const [apiKey, setApiKey] = useState(&quot;&quot;);<br>const [showKeyInput, setShowKeyInput] = useState(false);</pre><ul><li>selectedIngredients— Array of selected ingredients.</li><li>search — Stores the user input in the search box.</li><li>filteredIngredients— Array of Ingredients after filtering our original ingredients dataset (5000 ingredients) with the search. Thus only contains the ingredients relevant to the search and it will empty array if ‘search’ is an empty string.</li><li>showFlyout — boolean that stores the state to show or hide our flyout section which shows the result (recipe).</li><li>response — Stores the response (recipe) from chatGPT.</li><li>loading — Stores the loading state when a request is submitted.</li><li>apiKey — Stores the OpenAI key from the prompt popup in state.</li><li>showKeyInput — boolean to show or hide the OpenAI key prompt popup.</li></ul><h3>Jumping into the functionality</h3><p>We have a number of core functions on the index.jsx page. Below I have detailed the different functionality used on the page.</p><h4>Handling Search Suggestions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WE8oMVfbs9Jgtr59lc4yAw.png" /><figcaption>Suggestions on entering search variable</figcaption></figure><p>Let’s setup the search handling functionality in the useEffect. There is one dependency I added, which is the search variable. If the search variable changes, the useEffect is triggered.</p><pre>useEffect(() =&gt; {<br>    if (search === &quot;&quot;) setFilteredIngredients([]);<br>    else {<br>        const exactResults = ingredients.filter((item) =&gt; {<br>            var temp = item.ingredient.toLowerCase();<br>            return temp.startsWith(search.toLowerCase());<br>        });<br><br>        const relevantResults = ingredients.filter((item) =&gt; {<br>            var temp = item.ingredient.toLowerCase();<br>            return temp.includes(search.toLowerCase());<br>        });<br>        // To get the exact results first and followed by relevant results<br>        setFilteredIngredients([...exactResults, ...relevantResults]);<br>    }<br>}, [search]);</pre><p>Here, we are filtering the ingredients list with the search variable. The exactResults and relevantResults are filtered from the ingredients and saved to filteredIngredients using the setState function.</p><h4>Adding Selected Ingredient</h4><p>We have to store the ingredient in the selectedIngredients variable. So, this addIngredient function will be called when the user selects the ingredient.</p><pre>const addIngredient = (ingredient) =&gt; {<br>    if (selectedIngredients.length &lt;= 3) {<br>        if (selectedIngredients.indexOf(ingredient.ingredient) &lt; 0)<br>            setSelectedIngredients((prev) =&gt; [<br>                ...prev,<br>                ingredient[&quot;ingredient&quot;],<br>            ]);<br>    } else<br>        toast.error(&quot;Select not more than 4 ingredients&quot;, {<br>            icon: &quot;😊&quot;,<br>            style: {<br>                borderRadius: &quot;10px&quot;,<br>                background: &quot;#333&quot;,<br>                color: &quot;#fff&quot;,<br>            },<br>        });<br>};</pre><p>Here, we have implemented our restriction that users can enter at least 1 or maximum of 4 ingredients. I used react-hot-toast to show the toast message.</p><h3>API Integration</h3><p>Okayyy cool !!</p><p>We can now move to the next part where we will integrate OpenAI API with our frontend.</p><h4>Engineering the Prompt</h4><p>So, with the GPT API, its all about the prompt. Here’s the prompt that I used:</p><blockquote>Get me some recipes only with the ingredients: &lt;ingredients list&gt;, with its cooking procedure and a story with it.</blockquote><p>This prompt will make the GPT API to give us a recipe with the given ingredients. Feel free to change this prompt and have fun with GPT.</p><h4>Creating the API function</h4><p>I created an component called getResponse.jsx in the api folder.</p><pre>import type { NextApiRequest, NextApiResponse } from &quot;next&quot;;<br><br>type data = {<br>    ingredients: string;<br>};<br><br>const { Configuration, OpenAIApi } = require(&quot;openai&quot;);<br><br>export default async function handler(<br>    // ingredients<br>    req: NextApiRequest,<br>    res: NextApiResponse&lt;data&gt;<br>) {<br>    const request = req.body;<br><br>    const configuration = new Configuration({<br>        apiKey: request.key,<br>    });<br><br>    const openai = new OpenAIApi(configuration);<br>    const prompt = `Get me some recipes only with ingredients: ${request.data}, with its cooking procedure and a Story with it.`;<br>    <br>    const response = await openai.createCompletion({<br>        model: &quot;text-davinci-003&quot;,<br>        prompt: prompt,<br>        temperature: 0,<br>        max_tokens: 3000,<br>        top_p: 1,<br>        frequency_penalty: 0.4,<br>        presence_penalty: 0,<br>    });<br>    var choices = response.data;<br>    return res.status(200).json(choices);<br>}</pre><p>The main part of the above component is the call to createCompletion function of openai library. We get the key from the request and use that along with the prompt in the function.</p><pre>const configuration = new Configuration({<br>    apiKey: request.key,<br>});<br><br>const openai = new OpenAIApi(configuration);<br>const prompt = `Get me some recipes only with ingredients: ${request.data}, with its cooking procedure and a Story with it.`;<br>const response = await openai.createCompletion({<br>    model: &quot;text-davinci-003&quot;,<br>    prompt: prompt,<br>    temperature: 0,<br>    max_tokens: 3000,<br>    top_p: 1,<br>    frequency_penalty: 0.4,<br>    presence_penalty: 0,<br>});</pre><p>Read up on the parameters of the createCompletion function here: <a href="https://platform.openai.com/docs/api-reference/completions/create">https://platform.openai.com/docs/api-reference/completions/create</a>.</p><h4>Calling the API</h4><p>First, let’s add the handleSubmit function, which will be executed when we click the <strong>Get Recipe</strong> button. This function sets the state of showKeyInput to true, which triggers the visibility of the OpenAI key prompt popup.</p><pre>const handleSubmit = (e: any) =&gt; {<br>    e.preventDefault();<br>    setShowKeyInput(true);<br>};</pre><p>The users will be a shown a popup like follows (the OpenAIKeyPopup component).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*zMI5RSBCGeVYF8AymprSow.png" /></figure><p>Once we get the OpenAI API Key from the user, we can call the callGetResponse function to call our own NextJS API (api/getResponse), which we created above.</p><pre>const callGetResponse = async () =&gt; {<br>    setLoading(true);<br><br>    if (selectedIngredients.length &gt; 0) {<br>        await fetch(&quot;api/getResponse&quot;, {<br>            method: &quot;POST&quot;,<br>            headers: { &quot;Content-type&quot;: &quot;application/json;charset=UTF-8&quot; },<br>            body: JSON.stringify({<br>                key: apiKey,<br>                data: selectedIngredients,<br>            }),<br>        })<br>            .then((res) =&gt; res.json())<br>            .then((data) =&gt; {<br>                setResponse(data.choices[0].text);<br>                setShowFlyout(true);<br>                setLoading(false);<br>            })<br>            .catch((err) =&gt; {<br>                toast.error(&quot;An error occured. Please look at the console&quot;);<br>                toast.error(&quot;Please give a valid API Key&quot;);<br>                setLoading(false);<br>            });<br>    } else {<br>        toast.error(&quot;Please select atleast 1 ingredient&quot;, {<br>            icon: &quot;😊&quot;,<br>            style: {<br>                borderRadius: &quot;10px&quot;,<br>                background: &quot;#333&quot;,<br>                color: &quot;#fff&quot;,<br>            },<br>        });<br>    }<br>    setLoading(false);<br>    setShowKeyInput(false);<br>};</pre><p>On calling the API (api/getResponse), we receive the response and handle any errors here.</p><h3>Bringing it all together</h3><p>Finally, we have completed all the components and functionality. Lets have a look at our index page:</p><pre>import Head from &quot;next/head&quot;;<br>import { useEffect, useState } from &quot;react&quot;;<br>import { toast, Toaster } from &quot;react-hot-toast&quot;;<br>import Loading from &quot;../components/Atomic/Loading&quot;;<br>import Flyout from &quot;../components/Flyout&quot;;<br>import Footer from &quot;../components/Footer&quot;;<br>import SelectedIngredient from &quot;../components/SelectedIngredient&quot;;<br>import TopBar from &quot;../components/TopBar&quot;;<br>import { ingredients } from &quot;../ingredients&quot;;<br>import SearchBox from &quot;../components/SearchBox&quot;;<br>import OpenAIKeyPopup from &quot;../components/InputPopup&quot;;<br><br>const Home = () =&gt; {<br>    const [selectedIngredients, setSelectedIngredients] = useState([]);<br>    const [search, setSearch] = useState(&quot;&quot;);<br>    const [filteredIngredients, setFilteredIngredients] = useState(ingredients);<br>    const [showFlyout, setShowFlyout] = useState(false);<br>    const [response, setResponse] = useState(&quot;&quot;);<br>    const [loading, setLoading] = useState(false);<br>    const [apiKey, setApiKey] = useState(&quot;&quot;);<br>    const [showKeyInput, setShowKeyInput] = useState(false);<br><br>    const callGetResponse = async () =&gt; {<br>        setLoading(true);<br>        if (selectedIngredients.length &gt; 0) {<br>            await fetch(&quot;api/getResponse&quot;, {<br>                method: &quot;POST&quot;,<br>                headers: { &quot;Content-type&quot;: &quot;application/json;charset=UTF-8&quot; },<br>                body: JSON.stringify({<br>                    key: apiKey,<br>                    data: selectedIngredients,<br>                }),<br>            })<br>                .then((res) =&gt; res.json())<br>                .then((data) =&gt; {<br>                    setResponse(data.choices[0].text);<br>                    setShowFlyout(true);<br>                    setLoading(false);<br>                })<br>                .catch((err) =&gt; {<br>                    toast.error(&quot;An error occured. Please look at the console&quot;);<br>                    toast.error(&quot;Please give a valid API Key&quot;);<br>                    setLoading(false);<br>                });<br>        } else {<br>            toast.error(&quot;Please select atleast 1 ingredient&quot;, {<br>                icon: &quot;😊&quot;,<br>                style: {<br>                    borderRadius: &quot;10px&quot;,<br>                    background: &quot;#333&quot;,<br>                    color: &quot;#fff&quot;,<br>                },<br>            });<br>        }<br>        setLoading(false);<br>        setShowKeyInput(false);<br>    };<br><br>    const handleSubmit = (e) =&gt; {<br>        e.preventDefault();<br>        setShowKeyInput(true);<br>    };<br><br>    const addIngredient = (ingredient) =&gt; {<br>        if (selectedIngredients.length &lt;= 3) {<br>            if (selectedIngredients.indexOf(ingredient.ingredient) &lt; 0)<br>                setSelectedIngredients((prev) =&gt; [<br>                    ...prev,<br>                    ingredient[&quot;ingredient&quot;],<br>                ]);<br>        } else<br>            toast.error(&quot;Select not more than 4 ingredients&quot;, {<br>                icon: &quot;😊&quot;,<br>                style: {<br>                    borderRadius: &quot;10px&quot;,<br>                    background: &quot;#333&quot;,<br>                    color: &quot;#fff&quot;,<br>                },<br>            });<br>    };<br><br>    useEffect(() =&gt; {<br>        if (search === &quot;&quot;) setFilteredIngredients([]);<br>        else {<br>            const exactResults = ingredients.filter((item) =&gt; {<br>                var temp = item.ingredient.toLowerCase();<br>                return temp.startsWith(search.toLowerCase());<br>            });<br><br>            const relevantResults = ingredients.filter((item) =&gt; {<br>                var temp = item.ingredient.toLowerCase();<br>                return temp.includes(search.toLowerCase());<br>            });<br>            // To get the exact results first and followed by relevant results<br>            setFilteredIngredients([...exactResults, ...relevantResults]);<br>        }<br>    }, [search]);<br><br>    const onChangeInput = (e) =&gt; {<br>        setSearch(e.target.value);<br>    };<br><br>    const clearSearch = () =&gt; {<br>        setSearch(&quot;&quot;);<br>    };<br><br>    const closeFlyout = () =&gt; {<br>        setShowFlyout(false);<br>    };<br><br>    const hideKeyInput = () =&gt; {<br>        setShowKeyInput(false);<br>    };<br><br>    return (<br>        &lt;&gt;<br>            &lt;Head&gt;<br>                &lt;title&gt;recipe - GPT&lt;/title&gt;<br>                &lt;meta<br>                    name=&quot;description&quot;<br>                    content=&quot;RecipeGPT is a recipe recommendation app built on OpenAI GPT-3 API&quot;<br>                /&gt;<br>                &lt;meta<br>                    name=&quot;viewport&quot;<br>                    content=&quot;width=device-width, initial-scale=1&quot;<br>                /&gt;<br>                &lt;link rel=&quot;icon&quot; href=&quot;/favicon.ico&quot; /&gt;<br>            &lt;/Head&gt;<br>            &lt;main className=&quot;w-full h-screen p-0 m-0 flex flex-col justify-between items-center bg-black&quot;&gt;<br>                &lt;TopBar /&gt;<br><br>                &lt;div className=&quot;pt-[70px] w-full h-full&quot;&gt;<br>                    &lt;SelectedIngredient<br>                        ingredients={selectedIngredients}<br>                        setSelectedIngredients={setSelectedIngredients}<br>                    /&gt;<br><br>                    &lt;div className=&quot;w-full h-[60%] md:h-[70%] md:overflow-y-scroll flex justify-center items-center&quot;&gt;<br>                        &lt;div className=&quot;relative&quot;&gt;<br>                            &lt;SearchBox<br>                                clearSearch={clearSearch}<br>                                onChangeInput={onChangeInput}<br>                                loading={loading}<br>                                search={search}<br>                                filteredIngredients={filteredIngredients}<br>                                addIngredient={addIngredient}<br>                                handleSubmit={handleSubmit}<br>                            /&gt;<br>                        &lt;/div&gt;<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>                &lt;Toaster position=&quot;bottom-center&quot; gutter={8} /&gt;<br><br>                &lt;Footer handleSubmit={handleSubmit} /&gt;<br><br>                &lt;Flyout<br>                    showFlyout={showFlyout}<br>                    closeFlyout={closeFlyout}<br>                    response={response}<br>                /&gt;<br><br>                {showKeyInput &amp;&amp; (<br>                    &lt;OpenAIKeyPopup<br>                        hideKeyInput={hideKeyInput}<br>                        callGetResponse={callGetResponse}<br>                        onChange={(e) =&gt; {<br>                            setApiKey(e.target.value);<br>                        }}<br>                    /&gt;<br>                )}<br><br>                {loading &amp;&amp; &lt;Loading /&gt;}<br>            &lt;/main&gt;<br>        &lt;/&gt;<br>    );<br>};<br><br>export default Home;</pre><h3>Wrapping up</h3><p>At last, we have assembled our project, and got Chef GPT at our service. Here is the final outcome:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*wICnelrAgPz82vHgUNHmTw.gif" /></figure><p>I hope you have enjoyed working on this project as much as I did. Please let me know your comments and suggestions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*xEI8jgHD09F5YMEh.gif" /></figure><p>Byeeee….. Tata!!!!!</p><p><em>Edited and Curated by </em><a href="https://medium.com/u/16989b968303"><em>Gaurav G</em></a><em> for </em><a href="https://www.coffeeinc.in/"><em>Coffee</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2813598733dd" width="1" height="1" alt=""><hr><p><a href="https://blog.coffeeinc.in/recipe-gpt-building-a-nextjs-web-app-to-get-a-recipe-with-ingredients-using-gpt-api-part-2-2813598733dd">Recipe GPT : Building a NextJS Web App to get a Recipe with Ingredients using GPT API — Part 2</a> was originally published in <a href="https://blog.coffeeinc.in/">Coffee Byte</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recipe GPT : Building a NextJS Web App to get a Recipe with Ingredients using GPT API — Part 1]]></title>
            <link>https://blog.coffeeinc.in/recipe-gpt-building-a-nextjs-web-app-to-get-a-recipe-with-ingredients-using-gpt-api-part-1-89a2a16e137d?source=rss-4b31c58bcd29------2</link>
            <guid isPermaLink="false">https://medium.com/p/89a2a16e137d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[recipe]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Harish ]]></dc:creator>
            <pubDate>Mon, 01 May 2023 09:12:51 GMT</pubDate>
            <atom:updated>2023-05-04T10:24:39.203Z</atom:updated>
            <content:encoded><![CDATA[<h3>Recipe GPT : Building a NextJS Web App to get a Recipe with Ingredients using GPT API — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QIvy9v-4t6HNhVr1" /><figcaption>Photo by <a href="https://unsplash.com/@siva_photography?utm_source=medium&amp;utm_medium=referral">Levart_Photographer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Hola readers!!! Vanakkam Makkale!!!</strong></p><p>So let’s begin with this… ahem ahem (clearing throat)…</p><p>Who loves cooking?? Or wanna impress your loved ones with your cooking skills?? 👀… This one’s for you…</p><p>This blog is all about my development journey with the GPT-3 API and Next JS. Of course, we have to think of a fancy name for the project that would suggest recipes, based on ingredients selected. Hence: “RecipeGPT”.</p><p><strong>Fun note: </strong>My mum doesn’t have any idea of what she is gonna prepare for the next meal (happens always) and a lot of the time, she makes the decision based on ingredients available at home. So, I hope this might help her with some extra ideas to cook.</p><p>First, let me take you on a tour of what we are going to build now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*wICnelrAgPz82vHgUNHmTw.gif" /></figure><p>Since we are making use of the GPT API from OpenAI and access to free credits for the API is limited, I opted to have user enter their own OpenAI key to request a response.</p><p>If you noticed, I also added a slight twist in the end with an entertaining story around the recipe. You have not only a recipe to work with but a story to go with it (food for the belly and thought 😁).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6rErhibShweVrbqmNeYXbw.png" /><figcaption>Alice’s adventures with Orange Egg Custard</figcaption></figure><h3><strong>Project Flow:</strong></h3><ol><li>Users can enter ingredients and select from the list of ingredients shown.</li><li>A limit of minimum one and a maximum of 4 ingredients can be selected. (I added an upper limit considering there will be at most 2–3 main ingredients in a dish🙂. It is easier to start with something simple and then, if required, we can modify this constraint).</li><li>We get the OpenAI API Key from the user and then initiate the request to GPT API.</li><li>The ingredient list will be used to create a prompt, which will be sent to OpenAI’s GPT API.</li><li>The GPT API (our master chef 👨‍🍳) will give us a delicious recipe with the selected ingredients as a response.</li></ol><p><strong>On a future note</strong>🤔<strong>:</strong> we can save this response so that it will be helpful for the user and also reduce the number of requests to the GPT API. For this feature, we can use local storage or alternatively, set up authentication and backend. We will implement this feature in the next phase.</p><p><strong>Tech Stack:</strong></p><ul><li>NextJS</li><li>TailwindCSS</li></ul><p><strong>Other dependencies:</strong></p><ul><li>Openai</li><li>Eslint (optional)</li><li>React-hot-toast (optional)</li></ul><h3><strong>Setting up a NextJS project</strong></h3><p>Following method is my go-to way of setting up projects. I prefer to use npm as the package manager. If you want to DIY: you can follow <a href="https://nextjs.org/docs#automatic-setup">NextJS setup</a>, <a href="https://tailwindcss.com/docs/guides/nextjs">TailwindCSS setup</a> and <a href="https://www.atlassian.com/git/tutorials/setting-up-a-repository">GitHub repo setup</a>, and feel free to skip this section.</p><ol><li>Create a new repository in GitHub (or any other platform) and copy the project repo link, which we will use for git clone. Repo link will be similar to:</li></ol><pre>https://github.com/&lt;your_username&gt;/&lt;repo_name&gt;.git</pre><p><strong>Creating a git repo allows us to add our project to version control from the start. </strong>Thus, you can maintain versions of the project and revert changes if required.</p><p>2. Open the folder where you maintain projects in your local machine and clone the repository.</p><pre>git clone &lt;repo_link&gt;</pre><p>3. Go to project folder (with your repo_name, that was created in the previous step).</p><pre>cd &lt;repo_name&gt;</pre><p>4. Create a NextJS project with typescript, by using</p><pre>npx create-next-app@latest .</pre><p>5. Install Tailwind CSS by using</p><pre>npm install -D tailwindcss postcss autoprefixer<br>npx tailwindcss init -p</pre><p>5.1.Configure your template paths and add all of your template files in your tailwind.config.js file.</p><pre>/** tailwind.config.js */<br>/** @type {import(&#39;tailwindcss&#39;).Config} */<br>module.exports = {<br>  content: [<br>    &quot;./src/**/*.{html,js,jsx,ts,tsx}&quot;, <br>    &quot;./src/**/**/*.{html,js,jsx,ts,tsx}&quot;,<br>    &quot;./src/pages/**/*.{html,js,jsx,ts,tsx}&quot;,<br>  ],<br>  theme: {<br>    extend: {},<br>  },<br>  plugins: [],<br>}</pre><p>5.2. Add the @tailwind directives for each Tailwind’s layers to your globals.css file. Remove all the CSS code in the file.</p><pre>/** global.css */<br>@tailwind base;<br>@tailwind components;<br>@tailwind utilities;</pre><p>6. Clean the project</p><p>a. Delete all the icons in the `/public` folder.</p><p>b. Delete the `/src/styles/Home.module.css` file.</p><p>c. Delete the `index.tsx` file and create a new `index.tsx`. Then, we can use rafce (react es7 snippet) to create a template component.</p><p>d. Delete hello.ts in the /src/pages/api folder. We will be creating our own API route.</p><p>7. One of the main libraries we will be working with apart from the ones that come bundles with the NextJS app is openai. Install openai by using:</p><pre>npm install openai</pre><p>8. Add all your files to the git repo. Commit and push to the git remote repository.</p><pre>git add .<br>git commit -m &quot;Next project created&quot;<br>git push</pre><h3>Data</h3><p>We need a list of ingredients so that we can use this dataset to give users suggestions when they are searching in the search box and we will only allow users to select from the list.</p><p>The main reason why we are going with this technique is that if this restriction is not in place then users may mistakenly give wrong input and also we may get weird inputs for the ingredients, for example, we may get “Human” as an input for the ingredient. 🥲</p><p>To avoid these extreme cases, we can use a preset list as suggestions, from which users can select ingredients.</p><p>I used a dataset of 5000 ingredients in JSON format and here is the <a href="https://drive.google.com/file/d/1yEh_4MtdQqCyJoMUjeVSGVURx8TXjI1O/view?usp=sharing">link</a> to download the js file (I set it up as a constant).</p><h3><strong>Components</strong></h3><p>To get started, let’s first build the main components of our UI. We are going for something like the screen below with the following components:</p><ol><li>Navbar</li><li>Selected Ingredients section</li><li>Ingredients search bar (with autocomplete support)</li><li>Results Flyout section</li><li>OpenAI key prompt popup</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YbXUKU04lKbuG0XwvZ8fZg.png" /></figure><h4>1. Navbar</h4><p>First we can start with the navbar. We can keep it as simple as possible for now, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*Q06OBuiO6s-Yu8Ux57VBZQ.png" /></figure><p>Just a simple navbar with our logo on its left. Maybe in the future, we can have a profile picture or user’s name on the right (for when we bring in authentication).</p><pre><br>const TopBar = () =&gt; {<br>  return (<br>    &lt;div className=&quot;fixed top-0 left-0 w-full h-[10%] max-h-[70px] <br>    px-2 sm:px-10 flex justify-between items-center border-b-slate-900 <br>    border-solid border-b-[1px] bg-black&quot;&gt;<br>        &lt;div className=&quot;mx-2 text-xl font-bold text-white&quot;&gt;<br>            &lt;span&gt;Recipe&lt;/span&gt;<br>            &lt;span className=&quot;text-violet-500&quot;&gt;GPT&lt;/span&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>export default TopBar</pre><h4>2. Selected Ingredients Section</h4><p>Do we need to show the selected ingredients 🤔?</p><p>Yes of course, it improves our website’s user experience and basically it is a common sense too 😅. I added this section on the top of the page so that it doesn’t get covered by the dropdown showing suggestions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*nD3XHrBZHK_VQxzkyWmBUA.png" /></figure><p>Once users select ingredients, we can show the selected list as shown in the below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*EA5igun_eOuivX6OEaeG7g.png" /></figure><p>We have 2 main atomic components that make up the selected ingredients section:</p><p><strong>a. Selected Ingredient Card</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*fbSalWZCeKzDjlmGc0XSbw.png" /><figcaption>On hover, the remove button is shown</figcaption></figure><p>A card to show each selected ingredient with the option to remove the ingredient.</p><pre>const SelectedIngredientCard = ({ item, setSelectedIngredients }) =&gt; {<br>    const [showRemoveButton, setShowRemoveButton] = useState(false);<br><br>    return (<br>        &lt;div<br>            key={item}<br>            onMouseEnter={() =&gt; {<br>                setShowRemoveButton(true);<br>            }}<br>            onMouseLeave={() =&gt; {<br>                setShowRemoveButton(false);<br>            }}<br>            className=&quot;w-5/6 md:w-fit relative text-gray-200 mx-1 sm:mx-2 mb-2 bg-gray-900 py-1 px-3 rounded-md cursor-pointer transition-all duration-200 hover:bg-gray-800 hover:text-white&quot;<br>        &gt;<br>            {`${item.length &gt; 30 ? item.substring(0, 27) + &quot;...&quot; : item}`}<br>            {showRemoveButton &amp;&amp; (<br>                &lt;div<br>                    onClick={() =&gt;<br>                        setSelectedIngredients((prev) =&gt;<br>                            prev.filter((i) =&gt; i !== item)<br>                        )<br>                    }<br>                    className=&quot;absolute top-0 right-0 h-[12px] w-[12px] -translate-y-1/2 translate-x-1/2 hidden md:flex justify-center items-center text-xs bg-gray-900 rounded-full transition-all duration-200 hover:bg-red-500&quot;<br>                &gt;<br>                    &lt;span className=&quot;pb-1&quot;&gt;-&lt;/span&gt;<br>                &lt;/div&gt;<br>            )}<br>            {<br>                &lt;div<br>                    onClick={() =&gt;<br>                        setSelectedIngredients((prev) =&gt;<br>                            prev.filter((i) =&gt; i !== item)<br>                        )<br>                    }<br>                    className=&quot;absolute top-0 right-0 h-full w-6 flex md:hidden justify-center items-center text-xs&quot;<br>                &gt;<br>                    x<br>                &lt;/div&gt;<br>            }<br>        &lt;/div&gt;<br>    );<br>};</pre><p><strong>b. Selected Ingredient Section</strong></p><p>This is the main Selected Ingredient component that brings together the Label and SelectedIngredientCard component and displays the list of selected ingredients.</p><pre>const SelectedIngredient = ({ ingredients, setSelectedIngredients }) =&gt; {<br>    return (<br>        &lt;div className=&quot;w-full md:h-[15%] px-2 sm:px-10 flex justify-between items-center overflow-y-auto&quot;&gt;<br>            &lt;div className=&quot;w-full flex flex-col sm:flex-row justify-start items-center&quot;&gt;<br>                &lt;div className=&quot;w-full sm:w-max text-center sm:mr-4 sm:ml-2 mt-5 mb-3 sm:my-0 font-bold text-white sm:underline underline-offset-4&quot;&gt;<br>                    Ingredients Selected:<br>                &lt;/div&gt;<br>                {ingredients.length === 0 ? (<br>                    &lt;div className=&quot;w-5/6 text-center md:text-start text-sm sm:mr-4 ml-2 my-1 sm:my-0 font-bold text-gray-500 py-1 px-3&quot;&gt;<br>                        No Ingredients Selected<br>                    &lt;/div&gt;<br>                ) : (<br>                    &lt;div className=&quot;w-full md:w-fit flex flex-col md:flex-row justify-center items-center&quot;&gt;<br>                        {ingredients.map((item, index) =&gt; {<br>                            return (<br>                                &lt;SelectedIngredientCard<br>                                    key={index}<br>                                    item={item}<br>                                    setSelectedIngredients={<br>                                        setSelectedIngredients<br>                                    }<br>                                /&gt;<br>                            );<br>                        })}<br>                    &lt;/div&gt;<br>                )}<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default SelectedIngredient;</pre><p><strong>Note: </strong>I had passed the setSelectedIngredients state function down to the child components for ease of implementation. For a more standardized implementation, it is better to create a global state that maintains and accesses the selectedIngredients in all its child components.</p><h4>3. Search Box</h4><p>Let’s move on to build our Search box, from which we will get input (list of ingredients) from the user. And this is also going to be as simple as possible, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*iiCLR8p-7zhdzrSS4JJLoQ.png" /><figcaption>Search Box</figcaption></figure><p>Users can enter ingredients and select from the dropdown. The main SearchBox component has</p><ul><li>an input field,</li><li>a list of suggestions and</li><li>the submit button.</li></ul><pre>const SearchBox = ({<br>    loading,<br>    clearSearch,<br>    onChangeInput,<br>    search,<br>    filteredIngredients,<br>    addIngredient,<br>    handleSubmit,<br>}) =&gt; {<br>    return (<br>        &lt;div&gt;<br>            &lt;form className=&quot;w-fit flex justify-center items-center&quot;&gt;<br>                &lt;div className=&quot;flex items-center h-14 md:h-10 w-[300px] md:w-[600px]&quot;&gt;<br>                    &lt;div className=&quot;relative w-full h-full&quot;&gt;<br>                        &lt;input<br>                            type=&quot;text&quot;<br>                            placeholder=&quot;search ingredients...&quot;<br>                            value={search}<br>                            onChange={(e) =&gt; onChangeInput(e)}<br>                            className=&quot;h-full w-full py-1 px-6 bg-transparent border border-solid border-gray-700 -outline-offset-2 text-gray-200 placeholder:text-gray-700 rounded-md md:rounded-tl-md md:rounded-bl-md leading-tight&quot;<br>                        /&gt;<br>                        &lt;Suggestions<br>                            search={search}<br>                            filteredIngredients={filteredIngredients}<br>                            addIngredient={addIngredient}<br>                            clearSearch={clearSearch}<br>                        /&gt;<br>                    &lt;/div&gt;<br>                    &lt;button<br>                        type=&quot;submit&quot;<br>                        className={`hidden md:block -mx-1 w-[100px] md:w-[200px] h-full bg-blue-500 hover:bg-blue-700 text-white text-sm font-medium md:text-base md:font-bold rounded-tr-md rounded-br-md z-10 ${<br>                            loading<br>                                ? &quot;cursor-wait bg-blue-300 hover:bg-blue-300&quot;<br>                                : &quot;&quot;<br>                        }`}<br>                        disabled={loading}<br>                        onClick={handleSubmit}<br>                    &gt;<br>                        {loading ? &quot;Loading...&quot; : &quot;Get Recipes&quot;}<br>                    &lt;/button&gt;<br>                &lt;/div&gt;<br>            &lt;/form&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default SearchBox;</pre><p>You will notice a Suggestions component is used, which will help us handle the dropdown list of ingredients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*C3kWglMa9mhp8Rou2hk-Bw.png" /><figcaption>Search with suggestions</figcaption></figure><p>The dropdown is shown from the list of ingredients from the dataset that we had discussed about before.</p><pre>const Suggestions = ({<br>    search,<br>    filteredIngredients,<br>    addIngredient,<br>    clearSearch,<br>}) =&gt; {<br>    return (<br>        &lt;div<br>            className={`${<br>                search !== &quot;&quot;<br>                    ? &quot;h-[150px] block opacity-100&quot;<br>                    : &quot; h-0 opacity-0 pointer-events-none&quot;<br>            } absolute top-full left-[6px] w-[calc(100%-10px)] bg-[rgba(255,255,255,0.05)] rounded-bl-xl rounded-br-xl border border-solid border-[rgba(255,255,255,0.01)] overflow-y-auto transition-all duration-300`}<br>        &gt;<br>            {filteredIngredients.map((item, index) =&gt; {<br>                return (<br>                    &lt;div<br>                        key={index}<br>                        onClick={() =&gt; {<br>                            addIngredient(item);<br>                            clearSearch();<br>                        }}<br>                        className=&quot;min-h-[32px] max-h-fit px-5 py-1 text-gray-400 cursor-pointer hover:bg-[rgba(255,255,255,0.08)] hover:text-white&quot;<br>                    &gt;<br>                        {item.ingredient}<br>                    &lt;/div&gt;<br>                );<br>            })}<br>        &lt;/div&gt;<br>    );<br>};</pre><h4>4. Result Flyout</h4><p>Finallyyyy!!! To complete our UI let’s add a flyout section to display our result (Recipe) like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*84MHPQ9Vbl6MnnUQt6U74g.png" /></figure><p>Our Result Flyout needs to display the recipe received from GPT’s API. I created a simple header for the flyout.</p><pre>const FlyoutHeader = ({ closeFlyout }) =&gt; {<br>    return (<br>        &lt;div className=&quot;w-full h-[10%] relative flex border-b-[1px] border-solid border-b-[rgba(255,255,255,0.3)]&quot;&gt;<br>            &lt;div<br>                onClick={() =&gt; closeFlyout()}<br>                className=&quot;w-fit h-full px-4 sm:px-10 absolute left-0 flex justify-center items-center cursor-pointer hover:font-medium&quot;<br>            &gt;<br>                &lt;span className=&quot;text-2xl mr-1&quot;&gt;&amp;lt;&lt;/span&gt;<br>            &lt;/div&gt;<br>            &lt;span className=&quot;w-full h-full flex justify-center items-center text-center font-medium text-md tracking-wider text-white&quot;&gt;<br>                Your Recipe and Story<br>            &lt;/span&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default FlyoutHeader;</pre><p>We parse the response from GPT and display it in the flyout that overlays the main page.</p><pre>import FlyoutHeader from &quot;./FlyoutHeader&quot;;<br><br>const Flyout = ({ showFlyout, closeFlyout, response }) =&gt; {<br>    var text = response.split(&quot;\n&quot;);<br><br>    return (<br>        &lt;div<br>            onClick={() =&gt; closeFlyout()}<br>            className={` ${<br>                showFlyout ? &quot;opacity-1&quot; : &quot;opacity-0 pointer-events-none&quot;<br>            } transition-all duration-300 delay-200 ease-in-out w-screen h-full fixed top-0 bg-[rgba(255,255,255,0.3)] z-50`}<br>        &gt;<br>            &lt;div<br>                className={`${<br>                    showFlyout ? &quot;translate-x-0&quot; : &quot;translate-x-full&quot;<br>                } w-full sm:w-2/3 h-full absolute right-0 bg-black text-white transition-all duration-500 ease-in-out border-l-[1px] border-solid border-l-[rgba(255,255,255,0.3)]`}<br>            &gt;<br>                &lt;div className=&quot;w-full h-full relative&quot;&gt;<br>                    &lt;FlyoutHeader closeFlyout={closeFlyout} /&gt;<br>                    &lt;div className=&quot;w-full h-[90%] p-4 sm:pl-10 overflow-y-scroll&quot;&gt;<br>                        {text.map((line, index) =&gt; {<br>                            return (<br>                                &lt;div<br>                                    key={index}<br>                                    className={`${<br>                                        line.trim().split(&quot; &quot;).length === 1<br>                                            ? &quot;my-3 text-lg font-bold underline underline-offset-4&quot;<br>                                            : &quot;&quot;<br>                                    }`}<br>                                &gt;<br>                                    {line}<br>                                &lt;/div&gt;<br>                            );<br>                        })}<br>                    &lt;/div&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default Flyout;</pre><h4>5. OpenAI Key Prompt Popup</h4><p>On an extended note, as I mentioned before, I wanted to give users the ability to enter their own OpenAI key. This key would be directly used for the request and not saved anywhere as you will see in the next part.</p><p>This is a simple popup component that allows user to input their key.</p><pre><br>const OpenAIKeyPopup = ({hideKeyInput, callGetResponse, onChange}) =&gt; {<br>  return (<br>    &lt;div className=&quot;w-screen h-full fixed top-0 bg-[rgba(0,0,0,0.9)] z-50&quot;&gt;<br>        &lt;div className=&quot;fixed top-[100px] left-1/2 w-full max-w-sm h-fit px-8 -translate-x-1/2 bg-gray-900 rounded-xl&quot;&gt;<br>            &lt;div className=&quot;w-full h-11 flex justify-center items-center text-gray-300&quot;&gt;<br>                Enter your OpenAI API Key<br>            &lt;/div&gt;<br>            &lt;div className=&quot;my-3 w-full h-12 flex justify-center items-center&quot;&gt;<br>                &lt;input onChange={onChange} type=&quot;text&quot; placeholder=&quot;API Key&quot; className=&quot;px-3 w-full h-8 text-gray-300 rounded-lg bg-gray-700&quot;/&gt;<br>            &lt;/div&gt;<br>            &lt;div className=&quot;my-3 w-full h-12 flex justify-between items-center&quot;&gt;<br>                &lt;button className=&quot;text-gray-300&quot; onClick={()=&gt;hideKeyInput()}&gt;<br>                    Cancel<br>                &lt;/button&gt; <br>                &lt;button onClick={()=&gt;{callGetResponse()}} className=&quot;px-3 py-1 bg-gray-400 rounded-md&quot;&gt;<br>                    Done<br>                &lt;/button&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>export default OpenAIKeyPopup</pre><h3>Wrapping Up Part 1</h3><p>Now that we have our main components ready, we can go ahead and assemble them all together and call the GPT API to get our recipe and story.</p><p>I will continue the integration and functionality development in the next part of this article. Stay tuned and share your thoughts if you have any questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*xEI8jgHD09F5YMEh.gif" /></figure><p>Until next time, Tataaa!!!</p><p><em>Edited and Curated by </em><a href="https://medium.com/u/16989b968303"><em>Gaurav G</em></a><em> for </em><a href="https://www.coffeeinc.in/"><em>Coffee</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89a2a16e137d" width="1" height="1" alt=""><hr><p><a href="https://blog.coffeeinc.in/recipe-gpt-building-a-nextjs-web-app-to-get-a-recipe-with-ingredients-using-gpt-api-part-1-89a2a16e137d">Recipe GPT : Building a NextJS Web App to get a Recipe with Ingredients using GPT API — Part 1</a> was originally published in <a href="https://blog.coffeeinc.in/">Coffee Byte</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>