<?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 Abil Savio on Medium]]></title>
        <description><![CDATA[Stories by Abil Savio on Medium]]></description>
        <link>https://medium.com/@abilsavio?source=rss-27255858c890------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RwZdtQm7kDyBb7z2WTUWyA.jpeg</url>
            <title>Stories by Abil Savio on Medium</title>
            <link>https://medium.com/@abilsavio?source=rss-27255858c890------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 08:09:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abilsavio/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[Email contact form using NextJS (App router)]]></title>
            <link>https://medium.com/@abilsavio/email-contact-form-using-nextjs-app-router-60c29fe70644?source=rss-27255858c890------2</link>
            <guid isPermaLink="false">https://medium.com/p/60c29fe70644</guid>
            <category><![CDATA[react-hook-form]]></category>
            <category><![CDATA[nodemailer]]></category>
            <category><![CDATA[contact-form]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Abil Savio]]></dc:creator>
            <pubDate>Tue, 18 Jul 2023 10:32:34 GMT</pubDate>
            <atom:updated>2024-08-28T23:14:52.380Z</atom:updated>
            <content:encoded><![CDATA[<h4>Simple tutorial for using NextJS with app router to create a contact form to send messages to your email using nodemailer</h4><h3>An overview of what we’ll be doing here</h3><p>You must have come across contact forms on a lot of websites on the internet. We will be building a similar contact form. We will be using <a href="https://nextjs.org/"><strong>NextJS</strong></a> with the app router and first, build our Contact Form UI. Then we will use route handlers to create an API route to send an email to our gmail with the form details using <a href="https://nodemailer.com/"><strong>Nodemailer</strong></a>.</p><figure><img alt="Blog banner" src="https://cdn-images-1.medium.com/max/1024/1*E7ineOhtl2y9LqoNqAxMMw.png" /></figure><h3>Create a new NextJS project</h3><p>I’m using NextJS version 13.4 for this tutorial. The app router is now stable from this version onwards. To create a new project type:</p><pre>pnpm create next-app</pre><p>Provide a project name and continue with the defaults. TailwindCSS will be now installed by default which we can use for styling the form. Open the project folder in <strong>VSCode</strong> (or any IDE that you are using).</p><figure><img alt="Project structure" src="https://cdn-images-1.medium.com/max/256/1*cIh6pnfhEuxhcYDCOR08bQ.png" /><figcaption>Initial project structure</figcaption></figure><p>This is the basic project structure. Now let&#39;s start the NextJS development server using:</p><pre>npm run dev</pre><p>The server now starts at <a href="http://localhost:3000/">http://localhost:3000</a>. You can view the website by going to this URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*chU_H4NXv-wCWpcMnjt7-A.png" /><figcaption>Default NextJS starter page</figcaption></figure><h3>Creating a simple contact form</h3><p>Let&#39;s start by editing <strong>app/page.tsx</strong>. Now let&#39;s remove the boilerplate code and just retain the <strong>main</strong> tag. We will be building our form inside it. Since will be doing some client-side interactions with our form, It must be a client component. So we can either convert the file <strong>page.tsx</strong> into a <strong>client component</strong> (which is not recommended as we usually use components in that file as server components) or we can create a new file and then make it a client component which is what we’re going to do. Let’s create a <strong>component</strong> folder and then new file <strong>contact.tsx</strong> where we will be creating the form. We will be installing <a href="https://www.react-hook-form.com/"><strong>react-hook-form</strong></a> for managing our forms.</p><p>To install <strong>react-hook-form</strong>:</p><pre>pnpm i react-hook-form</pre><p>Also, we will be separating the email sending logic into a separate file in the <strong>utils</strong> folder for simplifying our codebase. Check the following images to remove any confusion as of now.</p><figure><img alt="Current project structure" src="https://cdn-images-1.medium.com/max/239/1*Jk6VaoAgPAgjfTENG5WrTQ.png" /><figcaption>Current project structure</figcaption></figure><figure><img alt="Basic UI flow" src="https://cdn-images-1.medium.com/max/1024/1*ZvJXszDY9CUkBk7nFAaOiQ.png" /><figcaption>Our basic UI flow</figcaption></figure><p>I will be adding here the code snippets for <strong>page.tsx</strong> and <strong>contact.tsx</strong> below for your reference</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/999be7f57defb3283e1b9243c59df4f4/href">https://medium.com/media/999be7f57defb3283e1b9243c59df4f4/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c420c064d4cef5e83c17e5efbbb9e2a/href">https://medium.com/media/1c420c064d4cef5e83c17e5efbbb9e2a/href</a></iframe><blockquote>Note that I have added <strong>‘use client’; </strong>to the first line which makes <strong>Contact</strong> a client component. We need to use this syntax from now on in NextJS if we are using app router because by default every components are server components. Go to <a href="https://nextjs.org/docs/getting-started/react-essentials">this link</a> to know more about server and client components.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7874c24ff1fc85ec92fe3faecad68c1c/href">https://medium.com/media/7874c24ff1fc85ec92fe3faecad68c1c/href</a></iframe><p>For now our form UI is completed, and as you can see the data from the form will be just logged to the console by the <strong>sendEmail</strong> function as of now. We just need to call an api to send the email inside that function. As you can see in the snippet I have added some styling for our components using <strong>tailwindcss</strong> classes just that it looks nice. Also the logic for the form is handled by <strong>react-hook-form</strong> which simplifies a lot of stuff regarding handling of forms in react. Right here I have used only a basic implementation of the library. You can go to <a href="https://www.react-hook-form.com/">react-hook-form.com</a> or read through this <a href="https://www.freecodecamp.org/news/how-to-create-forms-in-react-using-react-hook-form">tutorial from freecodecamp</a> to learn more about it.</p><p>This is how our form looks now:</p><figure><img alt="Form UI" src="https://cdn-images-1.medium.com/max/1024/1*4SCL9NUtaBzVLX8hoblinQ.png" /><figcaption>Form UI</figcaption></figure><h3>Setting up Nodemailer and API</h3><p>Now that our basic form is completed, let’s build our API using <strong>route handlers</strong> in NextJS. But first, we need to install <strong>nodemailer</strong>. Nodemailer is a module for Node.js that makes sending emails from a server an easy task. To install it along with its types:</p><pre>pnpm i nodemailer @types/nodemailer</pre><p>Create a new folder <strong>api</strong> and another folder <strong>email </strong>inside it. Now create a new file <strong>route.ts</strong> inside it. The file path will be <strong>app/api/email/route.ts</strong>. It is done this way to create our api with the endpoint as <strong>“api/email”</strong>. Check out <a href="https://nextjs.org/docs/app/building-your-application/routing/router-handlers">this doc</a> for more information. The current project structure will be as follows:</p><figure><img alt="Project structure" src="https://cdn-images-1.medium.com/max/235/1*48w4Uioy1PqdJZGQNz2kWg.png" /><figcaption>Current project structure</figcaption></figure><p>We can create a simple POST req route using the following snippet:</p><pre>import { type NextRequest, NextResponse } from &#39;next/server&#39;;<br><br>export async function POST(request: NextRequest) {<br>  return NextResponse.json(&#39;Hello from API!&#39;);<br>}</pre><p>We will be building the rest inside this function. But first we need our Gmail credentials for nodemailer which we will store as environment variables in a .env file.</p><pre>MY_EMAIL=youremail@gmail.com<br>MY_PASSWORD=*******(App password)</pre><p>From now onwards we cannot provide our actual gmail password for this purpose. Previously we could have enabled <strong>less secure apps</strong> option and continue with our actual password. But from now on we need <strong>App password</strong> to be used here. For getting an app password we need to first enable <strong>2FA (2 Factor Authentication)</strong> in our google account. For that we need to go to <a href="https://myaccount.google.com/">myaccount.google.com</a> and enable 2FA first which is a simple process. After that go to <a href="https://myaccount.google.com/apppasswords">myaccount.google.com/apppasswords</a> to setup app password. You might be asked to verify its you again.</p><figure><img alt="App password" src="https://cdn-images-1.medium.com/max/802/1*qLwCAVRVqGPdxXVrQPgS3A.png" /><figcaption>App password</figcaption></figure><p>From the UI select app as <strong>Mail</strong> and device as <strong>custom</strong> and then provide any name you want. (I provided <strong>nodemailer</strong> here).</p><figure><img alt="Generated app password" src="https://cdn-images-1.medium.com/max/796/1*Ks6C3IMXU509ZKwRYoSOMQ.png" /><figcaption>Generated app password</figcaption></figure><p>Copy the generated app password and then paste it in your <strong>.env</strong> file. Now we can continue setting up nodemailer.</p><p>We need to create and <strong>SMTP transport</strong> with nodemailer to configure it to send emails from our gmail. For that we will use the following snippet:</p><pre>import nodemailer from &#39;nodemailer&#39;;<br><br>const transport = nodemailer.createTransport({<br>  service: &#39;gmail&#39;,<br>  /* <br>      setting service as &#39;gmail&#39; is same as providing these setings:<br><br>      host: &quot;smtp.gmail.com&quot;,<br>      port: 465,<br>      secure: true<br>      <br>      If you want to use a different email provider other than gmail, you need to provide these manually.<br>      Or you can go use these well known services and their settings at<br>      https://github.com/nodemailer/nodemailer/blob/master/lib/well-known/services.json<br>  */<br>  auth: {<br>    user: process.env.MY_EMAIL,<br>    pass: process.env.MY_PASSWORD,<br>  },<br>});</pre><p>Next we need to set up the mail options which includes the message we are sending via email. For that we will use the following snippet:</p><pre>import Mail from &#39;nodemailer/lib/mailer&#39;;<br><br>const mailOptions: Mail.Options = {<br>  from: process.env.MY_EMAIL,<br>  to: process.env.MY_EMAIL,<br>  // cc: email, (uncomment this line if you want to send a copy to the sender)<br>  subject: `Message from ${name} (${email})`,<br>  text: message,<br>};</pre><p>We are basically sending an email from our address to our own address itself. If we want to send a copy of this mail back to the sender, we can use <strong>cc (Carbon Copy)</strong> option in the mailOptions and provide in the email. We can then use <strong>transport.sendMail</strong> function along with these mailOptions to send our email. The <strong>sendMail</strong> function is a synchronous function and hence we will be wrapping it with a promise to make it asynchronous. The snippet for it will be as follows:</p><pre>const sendMailPromise = () =&gt;<br>  new Promise&lt;string&gt;((resolve, reject) =&gt; {<br>    transport.sendMail(mailOptions, function (err) {<br>      if (!err) {<br>        resolve(&#39;Email sent&#39;);<br>      } else {<br>        reject(err.message);<br>      }<br>    });<br>  });</pre><p>The fully complete code for <strong>route.ts</strong> will be as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2596d71caf99f191cca565764f7fe8d/href">https://medium.com/media/b2596d71caf99f191cca565764f7fe8d/href</a></iframe><h3>Completing our form</h3><p>Now our api is complete and the only thing left is to send the data from our form. Remember we had created a function <strong>sendEmail</strong> previously right? Now we just have to send the form data to our endpoint <strong>api/email</strong> via a POST request which can be done easily with the fetch function. The completed <strong>send-email.ts</strong> file will be as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/141ab1e75ae8a6d8502d24118d2f1a6f/href">https://medium.com/media/141ab1e75ae8a6d8502d24118d2f1a6f/href</a></iframe><p>You can see that I’m sending alerts for confirmation. You can customise this behaviour in whatever way you like. Here is a sample message that I sent from the form:</p><figure><img alt="The email" src="https://cdn-images-1.medium.com/max/1020/1*NROTk1K3arMzbCA5uJzf5g.png" /><figcaption>This is how the email looks like</figcaption></figure><p>This tutorial is complete and we have a fully working form😌. You can check this repository for the entire project.</p><p><a href="https://github.com/ByteCrak07/nextjs-contact-form">GitHub - ByteCrak07/nextjs-contact-form</a></p><h3>Further reading</h3><p>You can optimise the form logic by adding loading states to improve user experience. Also check out libraries like <a href="https://swr.vercel.app/">SWR</a> and <a href="https://tanstack.com/query/latest">React-Query</a> to improve data fetching and sending. Also check out <a href="https://react.email/">React Email</a> to send beautiful emails using react rather than just sending plain text messages.</p><p>Go check out my website at <a href="https://abilsavio.dev/">abilsavio.dev</a> to know more about me. I have used SWR and React Email to send emails from my contact form. This is how an email from my website by filling the contact form looks like which was built using <strong>React Email</strong>.</p><figure><img alt="Email from abilsavio.tech" src="https://cdn-images-1.medium.com/max/1024/1*KK2fvJ1Rmtv6VACetnQMHw.png" /><figcaption>Email from <a href="https://abilsavio.dev/">abilsavio.dev</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60c29fe70644" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pocketbase OAuth on NextJS]]></title>
            <link>https://medium.com/@abilsavio/pocketbase-oauth-on-nextjs-6e93bd998490?source=rss-27255858c890------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e93bd998490</guid>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[google-oauth]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[github-oauth]]></category>
            <category><![CDATA[pocketbase]]></category>
            <dc:creator><![CDATA[Abil Savio]]></dc:creator>
            <pubDate>Tue, 07 Mar 2023 12:12:48 GMT</pubDate>
            <atom:updated>2024-08-28T23:13:15.412Z</atom:updated>
            <content:encoded><![CDATA[<h4>A simple tutorial on implementing Google &amp; GitHub OAuth in NextJS using Pocketbase</h4><h3>A brief introduction to Pocketbase &amp; NextJS</h3><p>Most of you folks must have already heard about <a href="https://pocketbase.io/"><strong>Pocketbase</strong></a> and also about <a href="https://nextjs.org/"><strong>Next.JS</strong></a> and that&#39;s why you are here in the first place. But for the newbies out there here&#39;s a small intro.</p><figure><img alt="Pocketbase website" src="https://cdn-images-1.medium.com/max/1024/1*p6nOO2A315jnevQq35_YWQ.png" /><figcaption>Check out their website at <a href="https://pocketbase.io/">pocketbase.io</a></figcaption></figure><p><strong>Pocketbase</strong> is an “Open Source backend for your next SaaS and Mobile app in 1 file” and that&#39;s true literally!! It is written in the <a href="https://go.dev/">Go</a> language and it consists of:</p><ul><li>embedded database (<em>SQLite</em>) with real-time subscriptions</li><li>built-in files and users management along with S3 support</li><li>an Admin dashboard UI built using <a href="https://svelte.dev/">Svelte</a></li><li>and a simple REST-ish API</li></ul><p>At the time of writing this Pocketbase is in beta at version 0.13.1 and is in active development. They’ve also created <a href="https://pocketbase.io/docs/client-side-integration">client-side SDKs for JavaScript and Dart</a>. Do check out their <a href="https://pocketbase.io/docs">documentation</a> and <a href="https://github.com/pocketbase/pocketbase">GitHub</a>. I love the amazing stuff their team is building. Also, you can play a little bit around the gopher on their website which is pretty cool 😄.</p><figure><img alt="NextJs website" src="https://cdn-images-1.medium.com/max/1024/1*_2OupyUGgIkG-xMCsyFvUw.png" /><figcaption>Check out their website at <a href="https://nextjs.org/">nextjs.org</a></figcaption></figure><p><strong>Next.JS</strong> is a JavaScript framework developed by the <a href="https://vercel.com/">Vercel</a> team which lets you build amazing web apps using React with server-side and static rendering. Nowadays it is much more than that and is the go-to React Framework. NextJs for me has made working with React honestly a fun and enjoyable experience.</p><h3>Installing Pocketbase</h3><p>Now onto the fun part. Let&#39;s install pocketbase on our local system.<br>Go on to their <a href="https://pocketbase.io/docs">official docs</a> and then download the zip file specific to your OS which is just around <strong>14 MB!!</strong> I downloaded the Linux version for my system.</p><p>Now create a new folder in your system like <strong>pocketbase-oauth </strong>and unzip the downloaded zip file in that folder. You can find the pocketbase executable in the folder and that’s it — the entire backend in 1 file.</p><p>To start our pocketbase just open a new terminal in the folder and then type:</p><pre>./pocketbase serve</pre><p>You will get an output similar to this if the server started successfully.</p><pre>2023/03/05 21:06:13 Server started at http://127.0.0.1:8090<br> ➜ REST API: http://127.0.0.1:8090/api/<br> ➜ Admin UI: http://127.0.0.1:8090/_/</pre><p>If you go to the Admin UI url from the terminal at <a href="http://127.0.0.1:8090/_/">http://127.0.0.1:8090/_/</a> output you will be greeted with the following webpage:</p><figure><img alt="Pocketbase Admin create" src="https://cdn-images-1.medium.com/max/1024/1*0UE9M5ZCmSK9nSCiJLuw7Q.png" /><figcaption>Create an admin account</figcaption></figure><p>This is a one-time configuration. You need to provide an admin email and a password to create an admin account which is required to log into the admin page. After login, you can view something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*792r5bzMO-TuHy1NmExvaw.png" /><figcaption>Pocketbase Admin UI</figcaption></figure><p>If you get up to this point… Congrats🎉. You have successfully installed and set up Pocketbase in your system.</p><h3>Configuring Google OAuth</h3><p>For adding google auth to pocketbase first we need to <a href="https://console.cloud.google.com/projectcreate">create a new project in <strong>google cloud</strong></a> which is free. Give any project name that you like and click on create. You will be greeted with the project dashboard.</p><p>Now to set up google oAuth in pocketbase we need a <strong>Client ID</strong> and <strong>Client Secret. </strong>For that, we need to go to the <strong>OAuth consent screen</strong> from the side menu &gt; APIs &amp; Services &gt; OAuth consent screen.</p><figure><img alt="Oauth consent screen" src="https://cdn-images-1.medium.com/max/497/1*mI7eCcvW2gTRKsslupj-Bg.png" /><figcaption>OAuth consent screen</figcaption></figure><p>Select <strong>User Type</strong> as <strong>External </strong>and click on create. Now fill the first page with details about our app. You can provide any details that you like. Only the App Name, User support email, and developer email are required to be filled in for our purpose. The rest of the details must be required if you are building a production application.</p><p>On the next page for scopes click on <strong>ADD OR REMOVE SCOPES </strong>and then select the following three scopes from the drawer on the right and then click on update for OAuth to work:</p><figure><img alt="OAuth scopes" src="https://cdn-images-1.medium.com/max/1024/1*RiyqJPBMy49BzQcuV1uafA.png" /><figcaption>OAuth scopes</figcaption></figure><p>After updating the scopes save and continue to the next page to add T<strong>est users</strong>, which is completely optional. Save and continue into the <strong>Summary</strong> page and then go to the dashboard.</p><p>Now go to the C<strong>redentials</strong> page from the left menu &gt; <strong>Create Credentials</strong> &gt; <strong>OAuth client ID</strong>.</p><figure><img alt="OAuth client ID" src="https://cdn-images-1.medium.com/max/1024/1*ifleY2EYjVTG_wC3tqmpcg.png" /><figcaption>OAuth client ID</figcaption></figure><p>Now, select the application type as a <strong>Web application </strong>and then provide a name. For <strong>Authorized JavaScript origins</strong> and <strong>Authorized redirect URIs</strong> set the values as the following:</p><figure><img alt="Setting authorized URIs" src="https://cdn-images-1.medium.com/max/573/1*v6n6sLl-qqRkcXWWLnw3Ww.png" /><figcaption>Setting authorized URIs</figcaption></figure><p>Now click on create. The OAuth client will be created and a pop-up modal will appear displaying your <strong>Your Client ID</strong> and <strong>Your Client Secret</strong>. Do not close the modal yet, or copy the values, or you can access these values later under <strong>OAuth 2.0 Client IDs</strong> on the same page.</p><figure><img alt="Google OAuth Client ID and secret" src="https://cdn-images-1.medium.com/max/638/1*dYC08y6abOix0FoWhT0mxQ.png" /><figcaption>Google OAuth Client ID and secret</figcaption></figure><p>Now go back to our Pocketbase admin panel then go to <strong>Settings</strong> &gt; <strong>Auth providers</strong> &gt; <strong>Google</strong>, enable it, and paste our client ID and client secret we got earlier. And then <strong>save these changes.</strong></p><figure><img alt="Setup google oauth" src="https://cdn-images-1.medium.com/max/1024/1*jzuF205f_DJDCyWqYrEmiw.png" /><figcaption>Setup google oauth</figcaption></figure><h3>Configuring GitHub OAuth</h3><p>Phew… Configuring Google OAuth was a real pain😅. But for GitHub, this process is much easier. So let&#39;s start. First, click on your GitHub avatar and go to <strong>Settings</strong> &gt; <strong>Developer settings</strong> &gt; <strong>OAuth Apps</strong> and then click on <strong>New OAuth App</strong>. Or just go directly <a href="https://github.com/settings/applications/new">to this link</a> which does the same. Now fill out the form with the following details and then register.</p><figure><img alt="GitHub OAuth" src="https://cdn-images-1.medium.com/max/615/1*Hv_qunI7YRR_Q-mad57ceg.png" /><figcaption>Configuring GitHub OAuth</figcaption></figure><p>The <strong>Application name</strong> can be whatever you like. Now we must generate our Client ID and Client Secret for GitHub. Click on Generate a new client secret and you will get something similar to this.</p><figure><img alt="GitHub OAuth Client ID and secret" src="https://cdn-images-1.medium.com/max/1024/1*pPUBDHZT33Ej1jbfAA-YWg.png" /><figcaption>GitHub OAuth Client ID and secret</figcaption></figure><p>Copy both the Client ID and Client secret and go to our Pocketbase admin panel and then <strong>Settings</strong> &gt; <strong>Auth providers</strong> &gt; <strong>GitHub</strong>, enable it, and then paste in the Client ID and secret we got earlier. Now click save changes and that&#39;s it. We have successfully enabled both Google and GitHub OAuth in Pocketbase🎉🎉</p><blockquote><strong>Some things to note</strong>: If you have noticed I have pasted <a href="http://localhost:3000/signin">http://localhost:3000/signin</a> as <strong>redirect url </strong>and <strong>authorization callback url </strong>in<strong> Google </strong>and<strong> GitHub </strong>respectively because by default NextJs runs on <strong>port 3000</strong>. If your NextJS application is running on a different port, change these urls accordingly. Also when running in production changes these values to your website URL.</blockquote><h3>Some more minor configs with Pocketbase</h3><p>This part is <strong>optional. </strong>If we need to collect the profile image from Google or GitHub accounts which are used to sign in to our applications. For that, we need to add a new field <strong>avatarUrl </strong>in the Users collection. Go to Pocketbase Admin Ui and then to <strong>Collections</strong> &gt; <strong>Users</strong> &gt; <strong>Edit collection (settings icon)</strong> &gt; <strong>New field</strong> and then provide type <strong>URL</strong> and field name <strong>avatarUrl </strong>and then save the changes.</p><figure><img alt="Configuring avatarUrl" src="https://cdn-images-1.medium.com/max/1024/1*hAYTYqcuBL7ASr45goiZDw.png" /><figcaption>Configuring avatarUrl</figcaption></figure><h3>Create a new NextJS project</h3><p>Now that we have set up our Pocketbase successfully we can begin creating our NextJS app. Here I’m using NextJs version 13.2 with <strong>TypeScript</strong>, but without the app directory which is currently experimental. Also, I’m using <strong>pnpm</strong> for this tutorial instead of npm or yarn which is completely up to your preference. To create a new project type:</p><pre>pnpm create next-app --typescript</pre><p>Provide a project name and continue with the defaults. Open the project folder in <strong>VSCode</strong> (or any IDE that you are using). Start the NextJS development server using:</p><pre>npm run dev</pre><p>The server now starts at <a href="http://localhost:3000/">http://localhost:3000</a>. You can view the website by going to this URL.</p><figure><img alt="Default NextJS starter page" src="https://cdn-images-1.medium.com/max/1024/1*CGBsUqK6zealElLbpZ3TpA.png" /><figcaption>Default NextJS starter page</figcaption></figure><p>Now we need to install the <strong>Pocketbase SDK</strong> as a dependency on this project. For that use:</p><pre>pnpm install pocketbase</pre><p>And that&#39;s it, our basic project creation is done. Now let&#39;s continue by configuring our Pocketbase SDK.</p><h3>Configuring Pocketbase in NextJS</h3><p>First, create a <strong>.env.local</strong> file in the project root folder and add the following env for Pocketbase:</p><pre>NEXT_PUBLIC_PB_URL=http://localhost:8090</pre><p>Now create a new <strong>lib</strong> folder in the project root and create a new file <strong>pocketbase.ts</strong> as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4334e4836660cbbe87d00c8a779640c/href">https://medium.com/media/c4334e4836660cbbe87d00c8a779640c/href</a></iframe><p>Basically, in this file Pocketbase is configured with the URL we provided in the env and exports the <strong>pb</strong> object to be used anywhere within our app. Also, I’ve set <strong>pb.autoCancellation </strong>to <strong>false</strong> only when the server is in development mode. Auto cancellation is a feature of pocketbase that cancels duplicated requests. For more details check out here. But since NextJs uses <strong>React strict mode</strong>, every component is rendered twice and this auto cancellation feature can result in request failure in NextJS even if the request was processed fine.</p><h3>Setting up OAuth in our app</h3><p>Now let&#39;s create an <strong>AuthWrapper</strong> which holds all the authentication states, user data, and helper functions and use the <strong>useContext</strong> hook to make it globally available to our application. For that create a new folder <strong>contexts</strong> and then a new file <strong>AuthWrapper.tsx</strong> as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d4be087d0ab0625263e0b9b4ffefdac/href">https://medium.com/media/6d4be087d0ab0625263e0b9b4ffefdac/href</a></iframe><p>Here we are exporting <strong>googleSignIn</strong>, <strong>githubSignIn</strong>, <strong>setUserData,</strong> and <strong>signOut</strong> functions along with the <strong>user</strong> object storing the <strong>user data</strong> via a new <strong>usePbAuth</strong> hook which is created using the <strong>useContext </strong>hook so that we can use them globally in our application. Also, I have created types for the user object and context. To use these functions we can just import the usePbAuth hook and destructure them inside any component as follows:</p><pre>const { user, googleSignIn, githubSignIn, setUserData, signOut } = usePbAuth()</pre><p>Now we need to wrap our app in <strong>pages/_app.tsx</strong> with the <strong>AuthWrapper</strong> we just exported. For that, we can wrap the <strong>&lt;Component /&gt; </strong>as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b58bdb768ef8f675ac0e3150f2e58a3/href">https://medium.com/media/8b58bdb768ef8f675ac0e3150f2e58a3/href</a></iframe><p>Now we can create our <strong>signin</strong> page. There we can implement both our sign-in logic as well as two buttons for signing in via Google and GitHub OAuth. You can copy the following code to the <strong>pages/signin.tsx </strong>file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99a8fefafd43d4ef5f825017f69f443e/href">https://medium.com/media/99a8fefafd43d4ef5f825017f69f443e/href</a></iframe><p>As you can see there are two buttons <strong>Sign in with Google</strong> and <strong>Sign in with GitHub. </strong>On clicking either one of these buttons the page will be redirected to their respective sign-in pages. On signing in from those pages we will be redirected back to our <strong>signin</strong> page. If you check the current page URL you can see a lot of parameters that contain our login information which will be handled by the <strong>useEffect</strong> block. There we extract the data from the parameters and provide them to the <strong>Pocketbase OAuth login</strong> function. On successful login get our name and avatarUrl from the response and store it in our Pocketbase database. We have successfully completed our task🎉🎉</p><h3>View our profile on sign in</h3><p>Now that our OAuth sign-in part is completed we can edit our <strong>pages/index.tsx</strong> file to display the <strong>SignIn</strong> button, our profile details, and the <strong>SignOut</strong> button. So edit the <strong>index.tsx</strong> file as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5af6f36d0394c17697288fa045a18393/href">https://medium.com/media/5af6f36d0394c17697288fa045a18393/href</a></iframe><p>Here the page will display the SignIn button which when clicked redirects to the sign-in page. If the user is signed in, then the user details will be shown similarly to this:</p><figure><img alt="User details" src="https://cdn-images-1.medium.com/max/526/1*KVdof4A1wJ-qLD_XAj-AMw.png" /><figcaption>User details</figcaption></figure><p><strong>Username</strong> is automatically generated by Pocketbase. We can change them later. This is just a basic implementation. The entire code for this tutorial is available on my GitHub:</p><p><a href="https://github.com/ByteCrak07/pocketbase-nextjs-oauth">GitHub - ByteCrak07/pocketbase-nextjs-oauth</a></p><p>Go check out my website at <a href="https://abilsavio.dev/">abilsavio.dev</a> to know more about me and the cool stuff I’m building.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e93bd998490" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>