<?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 YJ Kim on Medium]]></title>
        <description><![CDATA[Stories by YJ Kim on Medium]]></description>
        <link>https://medium.com/@youngjun625?source=rss-e8721502aec3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9ESZLF2cYOqZCSBNmmEBjg.jpeg</url>
            <title>Stories by YJ Kim on Medium</title>
            <link>https://medium.com/@youngjun625?source=rss-e8721502aec3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:38:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@youngjun625/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[[Next.js14] NextAuth v5 (3) — Google Sign In]]></title>
            <link>https://medium.com/@youngjun625/next-js14-nextauth-v5-3-google-sign-in-3683d8fae69c?source=rss-e8721502aec3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3683d8fae69c</guid>
            <category><![CDATA[nextjs14]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[social-login]]></category>
            <category><![CDATA[nextauth]]></category>
            <category><![CDATA[google-sign-in]]></category>
            <dc:creator><![CDATA[YJ Kim]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 07:46:35 GMT</pubDate>
            <atom:updated>2024-01-15T07:48:09.931Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Next.js14] NextAuth v5 (3) — Google Sign In</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WrHkSuql9xI5oOOrKUp-Jg.png" /></figure><p>This is a 3rd tutorial on using NextAuth v5 on Nextjs14. Other tutorials can be found below</p><p><a href="https://medium.com/@youngjun625/list/4f931159cf01">Nextjs14  &amp; NextAuthV5</a></p><h3>Preparation</h3><p>This tutorial will extend on the first tutorial <a href="https://medium.com/@youngjun625/next-js14-nextauth-v5-1-signin-signout-7e30cce52e7f">[Next.js14] NextAuth v5 (1) SignIn/SignOut</a>, so please come back after completing the first tutorial before going on.</p><p>Also, this tutorial is not related to sessions and updates covered in Part 2, so if you’re planning to only implement Google Sign In, feel free to skip the second tutorial.</p><p>There won’t be any changes in the folder structure this time. However, there are a few things that needs to be set up in <a href="https://console.cloud.google.com/apis">https://console.cloud.google.com/apis</a></p><h3>Google Cloud Set-up</h3><p>Head to <a href="https://console.cloud.google.com/apis">https://console.cloud.google.com/apis</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QfEwCpBICFZSqwfvkuR8yA.png" /></figure><p>If it’s your first time using google cloud, make sure to agree to the Terms of Services.</p><p>Continue with the following steps</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dbnKUrrX3c_Tk5DjrsJNpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*inp8NZd12B9FuawCdUCW3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*7Z0x7Pa2QhO0jYtOYGPRQg.png" /></figure><p>Edit the project name to your taste then click ‘CREATE’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SXSCunLvrgjNoDG6Ch6kUw.png" /></figure><p>You will be redirected to this screen</p><p><strong>👉 OAuth Consent Screen</strong></p><p>Let’s first configure our OAuth Consent Scren</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4gE0D4Pqf9rp_SvsiSEAtg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o7jF-fmYxAZwvd8_d2Q8zQ.png" /></figure><p>If you have internal testers in your organization, select Internal User Type. Else continue with External User</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SXBlB9Bu4nsicX5ddx7Jfg.png" /></figure><p>Edit the app name and select the user support email then scroll all the way down until you find “Developer contact information”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vovs5poCGclxdXtRfGXiaw.png" /></figure><p>Fill up the email address and continue by clicking the “SAVE AND CONTINUE” button</p><p>Consequetively press the “SAVE AND CONTINUE” button for the rest of the steps (Scopes, Test Users, Summary)</p><p><strong>👉 Credentials</strong></p><p>Let’s now set up our credentials</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xr15flZwBsdYry6tz8jMVw.png" /></figure><p>First select Application type as ‘Web</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*PUGCUVWUn9V7NtfZTxHJ6Q.png" /></figure><p>Then fill up the “Name” section and press the “ADD URI” button below Authorized redirect URIs.</p><p>Fill up the URIs section with http://localhost:3000/api/auth/callback/google <br>then click on the “CREATE” button</p><p><strong>🔴CAUTION🔴<br>Make sure to edit the URI as<br></strong><strong>https://${DEPLOYING DOMAIN URL}/api/auth/callback/google <br>when deploying your service to avoid errors.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*giz-FY2D00ZDSVD_abnpJQ.png" /></figure><p>After a few seconds, you will be notified that OAuth client has been created and will be able to view and copy the “Client ID” and “Client Secret”</p><p>Finally add the “Client ID” and “Client Secret” to you .env file</p><pre>GOOGLE_CLIENT_ID = ${YOUR GOOGLE CLIENT ID}<br>GOOGLE_CLIENT_SECRET =${YOUR GOOGLE CLIENT SECRET}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iV_b91YJ2FmASr5S08sx5Q.png" /></figure><h3>Code</h3><p>First, add a google provider within <em>src/auth.ts</em></p><pre>// src.auth.ts<br>import NextAuth from &#39;next-auth&#39;;<br>import { authConfig } from &#39;./auth.config&#39;;<br>import Credentials from &#39;next-auth/providers/credentials&#39;;<br>import { User } from &#39;@/lib/definitions&#39;;<br>import google from &#39;next-auth/providers/google&#39;; // added import<br><br>export const { handlers: { GET, POST }, auth, signIn, signOut, update } = NextAuth({<br>  ...authConfig,<br>  providers: [<br>    // **************************************************************<br>    // added provider<br>    google({<br>      clientId: process.env.GOOGLE_CLIENT_ID ?? &#39;&#39;,<br>      clientSecret: process.env.GOOGLE_CLIENT_SECRET ?? &#39;&#39;,<br>    }),<br>    // **************************************************************<br>    Credentials({<br>      async authorize(credentials) {<br>        if (credentials.id &amp;&amp; credentials.password) {<br>          // Add you backend code here<br>          // let loginRes = await backendLogin(credentials.id, credentials.password)<br>          let loginRes = {<br>            success : true,<br>            data : {<br>              user: {<br>                ID: &quot;john_doe&quot;,<br>                NAME: &quot;John Doe&quot;,<br>                EMAIL: &quot;email@email.email&quot;,<br>              },<br>            }<br>          }<br>          // Failed logging in<br>          if (!loginRes.success) return null;<br>          // Successful log in<br>          const user = {<br>            id: loginRes.data.user.ID ?? &#39;&#39;,<br>            name: loginRes.data.user.NAME ?? &#39;&#39;,<br>            email: loginRes.data.user.EMAIL ?? &#39;&#39;,<br>          } as User;<br>          return user;<br>        }<br>        return null;<br>      },<br>    })<br>  ],<br>  callbacks: {<br>    async session({ session, token, user }) {<br>      session.user = token.user as User<br>      return session;<br>    },<br>    async jwt({ token, user, trigger, session }) {<br>      if (user) {<br>        token.user = user;<br>      }<br>      // ***************************************************************<br>      // added code<br>      if (trigger === &quot;update&quot; &amp;&amp; session) {<br>        token = {...token, user : session}<br>        return token;<br>      };<br>       // **************************************************************<br>      return token;<br>    },<br>  },<br>});</pre><p>Create a google sign in method to be called at the client at <em>src/lib/actions.ts</em></p><pre>// src/lib/actions.ts<br>&quot;use server&quot;<br><br>import { signIn } from &quot;../auth&quot;;<br>import { AuthError } from &quot;next-auth&quot;;<br><br>...<br><br>export async function googleAuthenticate(<br>  prevState: string | undefined,<br>  formData: FormData,<br>) {<br>  try {<br>    await signIn(&#39;google&#39;);<br>  } catch (error) {<br>    if (error instanceof AuthError) {<br>      return &#39;google log in failed&#39;<br>    }<br>    throw error;<br>  }<br>}</pre><p>Make sure the file <em>src/app/api/auth/[…nextauth]/route.ts </em>exists</p><pre>// src/app/api/auth/[...nextauth]/route.ts<br>export { GET, POST } from &quot;@/auth&quot;<br>export const runtime = &quot;edge&quot;</pre><p>Finally, create a google sign in button in the login page at <em>src/app/login/page.tsx</em></p><pre>// src/app/login/page.tsx<br>&quot;use client&quot;<br><br>import { authenticate, googleAuthenticate } from &quot;@/lib/actions&quot; // added import<br>import { useFormState } from &quot;react-dom&quot;<br><br>export default function Page() {<br>    const [errorMsg, dispatch] = useFormState(authenticate, undefined)<br>    const [errorMsgGoogle, dispatchGoogle] = useFormState(googleAuthenticate, undefined) //googleAuthenticate hook<br>    return (<br>      &lt;div&gt;<br>        &lt;h1&gt;Log in Page&lt;/h1&gt;<br>        &lt;form className=&quot;flex flex-col&quot; action={dispatch}&gt;<br>            &lt;input className=&quot;bg-blue-300 text-black&quot; name=&quot;id&quot;&gt;&lt;/input&gt;<br>            &lt;input className=&quot;bg-yellow-300 text-black&quot; name=&quot;password&quot; type=&quot;password&quot;&gt;&lt;/input&gt;<br>            &lt;button&gt;<br>                Log In<br>            &lt;/button&gt;<br>            &lt;p&gt;{errorMsg}&lt;/p&gt;<br>        &lt;/form&gt;<br>        {/* Added google sign in button */}<br>        &lt;br /&gt;<br>        &lt;form className=&quot;flex flex-col&quot; action={dispatchGoogle}&gt;<br>            &lt;button&gt;<br>                Google Sign In<br>            &lt;/button&gt;<br>            &lt;p&gt;{errorMsgGoogle}&lt;/p&gt;<br>        &lt;/form&gt;<br>        {/* Added google sign in button */}<br>      &lt;/div&gt;<br>    )<br>  }</pre><p>Now run the Next app using npx next dev or npm run dev , head to <a href="http://localhost:3000/login">http://localhost:3000/login</a> and click on the “Google Sign In” button. You will be redirected to google’s OAuth consent screen.</p><p>Once you successfully signed in to your google account, you will be redirected back to homepage with your google account details printed on your terminal!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pn-TnUFG97-cGvoDNCtF_A.png" /></figure><h3>Source Code &amp; Remarks</h3><p>You can checkout the full source code below! Make sure to switch the branches from tutorial 1 to tutorial 3😊</p><p><a href="https://github.com/youngjun625/nextauth14-nextauthv5">GitHub - youngjun625/nextauth14-nextauthv5: [Next.js14] NextAuth v5 tutorial</a></p><p>You can also check out my other tutorials below</p><p><a href="https://medium.com/@youngjun625/list/4f931159cf01">Nextjs14  &amp; NextAuthV5</a></p><p>Thank you all for your support. Hope this tutorial can help all developers out there seeking for help with Nextjs14 and NextAuthV5!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3683d8fae69c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Next.js14] NextAuth v5 (2) — Session/Update]]></title>
            <link>https://medium.com/@youngjun625/next-js14-nextauth-v5-2-session-update-b977cb6afd47?source=rss-e8721502aec3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b977cb6afd47</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[updates]]></category>
            <category><![CDATA[nextjs14]]></category>
            <category><![CDATA[nextauth]]></category>
            <category><![CDATA[sessions]]></category>
            <dc:creator><![CDATA[YJ Kim]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 05:52:41 GMT</pubDate>
            <atom:updated>2024-01-15T07:58:08.095Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Next.js14] NextAuth v5 (2) — Session/Update</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tzRyct_bIU_ECKJRtKaHxw.png" /></figure><p>This is a 2nd tutorial on using NextAuth v5 on Nextjs14. The full tutorial can be found below😊</p><p><a href="https://medium.com/@youngjun625/list/4f931159cf01">Nextjs14  &amp; NextAuthV5 Tutorial</a></p><h3>Preparation</h3><p>👉<strong> Folder Structure</strong></p><p>Let’s start with the folder structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*QIaPWC2eP7CjWf8MGZ-ZAg.png" /></figure><blockquote>src/app/api/auth/[…nextauth]/route.ts<br>src/app/client/page.tsx<br>src/ui/update_button.tsx<br>src/auth_wrapper.tsx</blockquote><p>4 new files have been added since the previous tutorial</p><p><strong>👉 Server Side Rendering &amp; Client Side Rendering</strong></p><p>Before we go on, let’s briefly talk about distinguishing between Server Side Rendering (SSR) and Client Side Rendering (CSR) of Nextjs14. Detailed comparisons between the two can be found on the internet, so I will only explain the concepts required for this tutorial.</p><p>Nextjs14 uses Server Side Rendering as default to display web components on the screen. Adding a line of &quot;use client&quot; on the top of the component code allows Nextjs14 to display components using Client Side Rendering.</p><p>Adding a console.log(&quot;message&quot;) on Server Side code will display message on the terminal running the Next app, while adding it on Client Side code will display message on the browser console (Browser -&gt; DevTools -&gt; Console)</p><p>Now let’s add a console.log on <em>src/app/page.tsx </em>and write code on<em> src/app/client/page.tsx</em></p><pre>// src/app/page.tsx<br>...<br>export default async function Home() {<br>  console.log(&#39;Server Side Rendering&#39;) // Adding a console.log <br>  return (<br>...</pre><pre>// src/app/client/page.tsx<br>&quot;use client&quot;<br><br>export default function Page() {<br>    console.log(&#39;Client Side Rendering&#39;)<br>    return (<br>      &lt;div&gt;<br>        &lt;h1&gt;Client Side Rendeing Page&lt;/h1&gt;<br>        &lt;h2&gt;Unavailable without auth&lt;/h2&gt;<br>      &lt;/div&gt;<br>    )<br>  }</pre><p>Now heading to <a href="http://localhost:3000/">http://localhost:3000/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*RqYciMKr0OW-e2ANE0wWPw.png" /></figure><p>We can see a message “Server Side Rendering” on the terminal</p><p>Heading to <a href="http://localhost:3000/client">http://localhost:3000/client</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*sc-FIAJlMPjqLCCYGbK6Og.png" /></figure><p>We can now see a message “Client Side Rendering” on the browser console! The reason why we see multiple messages is explained below</p><p><a href="https://stackoverflow.com/questions/71847778/why-my-nextjs-component-is-rendering-twice">Why my nextjs component is rendering twice?</a></p><h3>Session</h3><p>The reason why I talked about SSR and CSR is because the session calling method depends on whether the code is running on Server Side or Client Side.</p><p><strong>👉 Calling session on Server Side, await auth()</strong></p><p>To call session on server side, let’s first edit the code on <em>src/auth.ts</em> and <em>src/app/page.tsx</em></p><pre>// src/auth.ts<br>...<br><br>// { handlers: { GET, POST }, auth, update } has been added<br>export const { handlers: { GET, POST }, auth, signIn, signOut, update } = NextAuth({<br>  ...authConfig,<br>  <br>...</pre><pre>// src/app/page.tsx<br>import { auth, signOut } from &quot;@/auth&quot; // adding { auth }<br><br>export default async function Home() { // is now a &#39;async function&#39;<br>  console.log(&#39;Server Side Rendering&#39;)<br>  const session = await auth() // calling session<br>  console.log(session); // console log to read session<br>  return (<br><br>...</pre><p>Now head to <a href="http://localhost:3000/">http://localhost:3000/</a> , and we can read the session data from the terminal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*1OdqmwZIhwLtdTItYcQRXA.png" /></figure><p><strong>👉 Calling session on Client Side, useSession()</strong></p><p>To call session on client side, we can use a hook ‘useSession()’. In order to use the ‘useSession()’ hook, few things must be done beforehand. We have to set up an internap api and wrap the app with a SessionProvider.</p><pre>// src/app/api/auth/[...nextauth]/route.ts<br>export { GET, POST } from &quot;@/auth&quot;<br>export const runtime = &quot;edge&quot;</pre><pre>// src/app/auth_wrapper.tsx<br>&quot;use client&quot;; <br>// SessionProvider must be used with Client Side Rendering<br>// Therfore we create a separate client side component to run AuthWrapper<br>import { SessionProvider } from &quot;next-auth/react&quot;;<br><br>type Props = {<br>  children:React.ReactNode;<br>}<br><br>export default function AuthWrapper({ children }: Props) {<br>  return &lt;SessionProvider&gt;{children}&lt;/SessionProvider&gt;;<br>}</pre><pre>// src/app/layout.tsx<br>import type { Metadata } from &#39;next&#39;<br>import { Inter } from &#39;next/font/google&#39;<br>import &#39;./globals.css&#39;<br>import AuthWrapper from &#39;../auth_wrapper&#39;<br><br>const inter = Inter({ subsets: [&#39;latin&#39;] })<br><br>export const metadata: Metadata = {<br>  title: &#39;Create Next App&#39;,<br>  description: &#39;Generated by create next app&#39;,<br>}<br><br>export default function RootLayout({<br>  children,<br>}: {<br>  children: React.ReactNode<br>}) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body className={inter.className}&gt;<br>        &lt;AuthWrapper&gt; {/* Wrapping the entire app with AuthWrapper */}<br>          {children}<br>        &lt;/AuthWrapper&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  )<br>}</pre><p>layout.tsx file is a special file that acts as a parant of the page.tsx component.</p><p><a href="https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts#root-layout-required">Routing: Pages and Layouts | Next.js</a></p><p>Now let’s edit<em> src/client/page.tsx</em></p><pre>// src/app/client/page.tsx<br>&quot;use client&quot;<br><br>import { useSession } from &quot;next-auth/react&quot; // adding import<br><br>export default function Page() {<br>    console.log(&#39;Client Side Rendering&#39;)<br>    const { data: session, update } = useSession() // useSession()<br>    console.log(session); // console.log<br>    return (<br>      &lt;div&gt;<br>        &lt;h1&gt;Client Side Rendeing Page&lt;/h1&gt;<br>        &lt;h2&gt;Unavailable without auth&lt;/h2&gt;<br>      &lt;/div&gt;<br>    )<br>  }</pre><p>Head to <a href="http://localhost:3000/client">http://localhost:3000/client</a> , open up the browser console and we can read the session data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*57a9IEJ8AxxLG5_5lTtrDw.png" /></figure><h3>Session Update</h3><p>Before Next Auth v5 came out, updating the session could only be done on the Client Side. With the new v5, session update can be done on the server side as well.</p><p><strong>👉 Editing auth.ts</strong></p><p>Let’s first edit the src/auth.ts file. A codeblock has been added inside callbacks -&gt; jwt</p><pre>// src.auth.ts<br>import NextAuth from &#39;next-auth&#39;;<br>import { authConfig } from &#39;./auth.config&#39;;<br>import Credentials from &#39;next-auth/providers/credentials&#39;;<br>import { User } from &#39;@/lib/definitions&#39;;<br><br>export const { handlers: { GET, POST }, auth, signIn, signOut, update } = NextAuth({<br>  ...authConfig,<br>  providers: [<br>    Credentials({<br>      async authorize(credentials) {<br>        if (credentials.id &amp;&amp; credentials.password) {<br>          // Add you backend code here<br>          // let loginRes = await backendLogin(credentials.id, credentials.password)<br>          let loginRes = {<br>            success : true,<br>            data : {<br>              user: {<br>                ID: &quot;john_doe&quot;,<br>                NAME: &quot;John Doe&quot;,<br>                EMAIL: &quot;email@email.email&quot;,<br>              },<br>            }<br>          }<br>          // Failed logging in<br>          if (!loginRes.success) return null;<br>          // Successful log in<br>          const user = {<br>            id: loginRes.data.user.ID ?? &#39;&#39;,<br>            name: loginRes.data.user.NAME ?? &#39;&#39;,<br>            email: loginRes.data.user.EMAIL ?? &#39;&#39;,<br>          } as User;<br>          return user;<br>        }<br>        return null;<br>      },<br>    })<br>  ],<br>  callbacks: {<br>    async session({ session, token, user }) {<br>      session.user = token.user as User<br>      return session;<br>    },<br>    async jwt({ token, user, trigger, session }) {<br>      if (user) {<br>        token.user = user;<br>      }<br>      // ***************************************************************<br>      // added code<br>      if (trigger === &quot;update&quot; &amp;&amp; session) {<br>        token = {...token, user : session}<br>        return token;<br>      };<br>       // **************************************************************<br>      return token;<br>    },<br>  },<br>});</pre><p><strong>👉 Client Side Session Update</strong></p><p>Let’s deal with client side code first. Edit the code at <em>src/app/client/page.tsx</em></p><pre>// src/app/client/page.tsx<br>&quot;use client&quot;<br><br>import { User } from &quot;@/lib/definitions&quot;<br>import { useSession } from &quot;next-auth/react&quot;<br>import { useEffect, useState } from &quot;react&quot;<br><br>export default function Page() {<br>    const { data: session, update } = useSession()<br>    // useState and useEffect are used to only render the UI<br>    // after the session is retrieved<br>    const [user, setUser] = useState&lt;User&gt;({} as User)<br>    useEffect(() =&gt; {<br>      if(session &amp;&amp; session.user) <br>        {<br>          setUser(session.user as User)<br>          console.log(session.user)<br>        }<br>    }, [session])<br><br>    return (<br>      session &amp;&amp; // UI renders once session has been retrived<br>      &lt;div&gt;<br>        &lt;h1&gt;Client Side Rendeing Page&lt;/h1&gt;<br>        &lt;h2&gt;Unavailable without auth&lt;/h2&gt;<br>        &lt;br /&gt;<br>        &lt;button onClick={ () =&gt; {<br>        // using update() called from the useSession hook<br>          update({...user, name: &#39;Client-Man&#39;});<br>        }}&gt;<br>          Client Side Update<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    )<br>  }</pre><p>Head to <a href="http://localhost:3000/client">http://localhost:3000/client</a> , open up the browser console, then click on the “Client Side Update” button. The console will print updated session’s user data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*9BfWT-gKKIl6mCsCHf1JRA.png" /></figure><p><strong>👉 Server Side Session Update</strong></p><p>There are two ways of updating the session in the server side. The first way is to call a Client Component within the Server Component to run a Client Side Session update.</p><p>The other way is to make use of the new feature from NextAuth v5; using the update method imported from @auth within the server component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*2inrWh71fEdOkkA25UgQug.png" /></figure><p>Let’s try out both methods</p><p><strong>👉 — Client Component within Server Component</strong></p><p>First, let’s create a separate Client Component File inside <em>src/ui/update_button.tsx</em></p><pre>// src/ui/update_button.tsx<br>&quot;use client&quot;<br>import { useSession } from &quot;next-auth/react&quot;<br><br>export default function UpdateButton({newName} : {newName: String}) {<br>    const { data: session, update } = useSession()<br>    return (<br>        &lt;button onClick={() =&gt; {<br>            update({...session!.user, name: newName});<br>          }}&gt;<br>            Client Side Update<br>          &lt;/button&gt;<br>    )<br>}</pre><p>Edit the <em>src/app/page.tsx</em> file</p><pre>// src/app/page.tsx<br>import { auth, signOut } from &quot;@/auth&quot;<br>import UpdateButton from &quot;@/ui/update_button&quot;;<br><br>export default async function Home() {<br>  console.log(&#39;Server Side Rendering&#39;)<br>  const session = await auth() // calling session<br>  console.log(session); // console log to read session<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Home Page&lt;/h1&gt;<br>      &lt;h2&gt;Unavailable without auth&lt;/h2&gt;<br>      &lt;form<br>          action={async () =&gt; {<br>            &#39;use server&#39;;<br>            await signOut();<br>          }}<br>        &gt;<br>          &lt;button&gt;<br>             Log Out<br>          &lt;/button&gt;<br>          &lt;br /&gt; <br>          &lt;UpdateButton newName={&#39;Server-Man&#39;} /&gt;<br>        &lt;/form&gt;<br>    &lt;/div&gt;<br>  )</pre><p>Head to <a href="http://localhost:3000/">http://localhost:3000/</a> , then press on the ‘Client Component Update’ button. Refresh the page or head to a different route (<a href="http://localhost:3000/">http://localhost:3000/</a>client).</p><p>We can check that user.name within the session has been successfully updated to ‘Server-man’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*Y_eONvGSroNg7Of1Ql46Kw.png" /></figure><p><strong>👉 — Using update imported from @auth within Server Component</strong></p><p>Edit the <em>src/app/page.tsx</em> file</p><pre>// src/app/page.tsx<br>import { auth, signOut, update } from &quot;@/auth&quot;<br>import UpdateButton from &quot;@/ui/update_button&quot;;<br><br>export default async function Home() {<br>  console.log(&#39;Server Side Rendering&#39;)<br>  const session = await auth() // calling session<br>  const user = session!.user;<br>  console.log(session); // console log to read session<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Home Page&lt;/h1&gt;<br>      &lt;h2&gt;Unavailable without auth&lt;/h2&gt;<br>      &lt;form<br>          action={async () =&gt; {<br>            &#39;use server&#39;;<br>            await signOut();<br>          }}<br>        &gt;<br>          &lt;button&gt;<br>             Log Out<br>          &lt;/button&gt;<br>          &lt;br /&gt; <br>          &lt;UpdateButton newName={&#39;Server-Man&#39;} /&gt;<br>        &lt;/form&gt;<br>      &lt;br /&gt;<br>      &lt;form<br>          action={async () =&gt; {<br>            &#39;use server&#39;;<br>            await update({...user, name: &#39;Serverserver-man&#39;});<br>          }}<br>        &gt;<br>        &lt;button&gt;<br>          Server Side Update<br>        &lt;/button&gt;<br>      &lt;/form&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>Head to <a href="http://localhost:3000/">http://localhost:3000/</a> , then press on the ‘Server Side Update’ button. Refresh the page or head to a different route (<a href="http://localhost:3000/">http://localhost:3000/</a>client).</p><p>We can check that user.name within the session has been successfully updated to ‘Serverserver-man’</p><p>I’ve noticed that this new update feature seems a little unstable for now. Therefore using the Client Component Update Method will be a more stable option until NextAuth v5 becomes official.</p><h3>Upcoming &amp; Source Code</h3><p>Next tutorial will be about social logins, especially using Google!</p><p><a href="https://medium.com/@youngjun625/next-js14-nextauth-v5-3-google-sign-in-3683d8fae69c">[Next.js14] NextAuth v5 (3) — Google Sign In</a></p><p>You can checkout the full source code below! Make sure to switch the branches from tutorial 1 to tutorial 2 😊</p><p><a href="https://github.com/youngjun625/nextauth14-nextauthv5">GitHub - youngjun625/nextauth14-nextauthv5: [Next.js14] NextAuth v5 tutorial</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b977cb6afd47" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Next.js14] NextAuth v5 (1) SignIn/SignOut]]></title>
            <link>https://medium.com/@youngjun625/next-js14-nextauth-v5-1-signin-signout-7e30cce52e7f?source=rss-e8721502aec3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e30cce52e7f</guid>
            <category><![CDATA[login]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nextjs14]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[nextauth]]></category>
            <dc:creator><![CDATA[YJ Kim]]></dc:creator>
            <pubDate>Fri, 12 Jan 2024 09:16:04 GMT</pubDate>
            <atom:updated>2024-01-15T08:02:21.653Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Next.js14] NextAuth v5 (1) — SignIn/SignOut</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tvruq3KU5V9zpWVIoH8Cuw.png" /></figure><p>This is a tutorial on using NextAuth v5 on Nextjs14. I’ve noticed that there aren’t much sources about NextAuth v5 since it’s still on beta version.</p><p>This tutorial has been written based on <a href="https://nextjs.org/learn?utm_source=next-site&amp;utm_medium=homepage-cta&amp;utm_campaign=home">Next.js14 official tutorial</a> + some of the things I learned on the way of developing with it.</p><p>The full tutorial can be found below😊</p><p><a href="https://medium.com/@youngjun625/list/4f931159cf01">Nextjs14  &amp; NextAuthV5 Tutorial</a></p><h3>Preparation</h3><p>👉<strong> Creating Next App</strong></p><p>First create a next app using the command npx create-next-app@latest . I’ve used typescript, tailwind css, src/ directory and app router.</p><p>👉<strong> Installing Packages</strong></p><p>Next, install next-auth with the command npm install next-auth@beta <br>Make sure &quot;next-auth&quot;: &quot;^5.0.0-beta.4&quot; or above has been added to package.json</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*7t87r-lpBtVn4_omnk-9AA.png" /></figure><h4>👉 Genrating secret key</h4><p>Generate a secret key using openssl with the following commad.</p><pre>openssl rand -base64 32</pre><p>There are many tutorials on installing openssl. Make sure not to share the secret key externally!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/0*0EbRceNAC9BAguRo.png" /></figure><h4>👉 Adding environment variable inside .env file</h4><p>Lastly add a ‘AUTH_SECRET’ variable inside the .env file and we are ready to go. (<strong>Make sure .env is added to .gitignore file</strong>)</p><pre># .env file<br>AUTH_SECRET=2rhmxBZsnncgb392RxtB...</pre><h3>Code</h3><p><strong>👉 Folder Structure</strong></p><p>The folder structure of the project is the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*qClM3Fuk8mQ8yrm6K-XKQw.png" /></figure><blockquote>src/app/login folder,<br>src/lib folder,<br>src/auth.config.ts,<br>src/auth.ts,<br>src/middleware.ts</blockquote><p>has been added to the basic Nextjs14 app.</p><p><strong>👉 App router</strong></p><p>Let’s briefly talk about the app router before we go on. All folders within the app directory becomes a route. For example, running the app with the folder structure above and heading to <a href="http://localhost:3000/login">http://localhost:3000/login</a> will show the component written inside (src/app/login/page.tsx)</p><p>Next has few special files like the ‘pages.tsx’ file that is used for special cases. More information can be found <a href="https://nextjs.org/docs/app/building-your-application/routing">here</a></p><p><strong>👉 Login page</strong></p><pre>// src/app/login/page.tsx<br>&quot;use client&quot;<br><br>// import { authenticate } from &quot;@/lib/actions&quot;<br>// import { useFormState } from &quot;react-dom&quot;<br><br>export default function Page() {<br>    // authenticate() method will be declared later<br>    // const [errorMsg, dispatch] = useFormState(authenticate, undefined)<br>    return (<br>      &lt;div&gt;<br>        &lt;h1&gt;Log in Page&lt;/h1&gt;<br>        &lt;form className=&quot;flex flex-col&quot; &gt; {/* action={dispatch} */}<br>            &lt;input className=&quot;bg-blue-300 text-black&quot; name=&quot;id&quot;&gt;&lt;/input&gt;<br>            &lt;input className=&quot;bg-yellow-300 text-black&quot; name=&quot;password&quot; type=&quot;password&quot;&gt;&lt;/input&gt;<br>            &lt;button&gt;<br>                Log In<br>            &lt;/button&gt;<br>           {/* errorMsg will be declared later <br>            &lt;p&gt;{errorMsg}&lt;/p&gt; */}<br>        &lt;/form&gt;<br>      &lt;/div&gt;<br>    )<br>  }</pre><p><strong>👉 Home page</strong></p><pre>// src/app/page.tsx<br>// import { signOut } from &quot;../auth&quot;<br><br>export default async function Home() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Home Page&lt;/h1&gt;<br>      &lt;h2&gt;Unavailable without auth&lt;/h2&gt;<br>      &lt;form<br>          // action={async () =&gt; {<br>          //   // signOut() Method will be declared later<br>          //   &#39;use server&#39;;<br>          //   await signOut();<br>          // }}<br>        &gt;<br>          &lt;button&gt;<br>             Log Out<br>          &lt;/button&gt;<br>        &lt;/form&gt;<br><br>    &lt;/div&gt;<br>  )<br>}</pre><p>Now let’s run the app with npx next dev or npm run dev or yarn depending on your environment.</p><p><a href="http://localhost:3000/login">http://localhost:3000/login</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*oe9TllEWxthDaOHlOQ2rAQ.png" /></figure><p><a href="http://localhost:3000/">http://localhost:3000/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*_XovPrTG6bSGyJt1wYvmRQ.png" /></figure><p>Let’s move on once we are able to render these 2 pages!</p><p><strong>👉 Authentication and ProtectedRoutes</strong></p><p>Within the src folder, let’s add 3 files : auth.config.ts, auth.ts, middleware.ts <br>and within scr/lib folder, let’s add 2 files : definitions.ts, actions.ts</p><p>In Next.js, a special file name ‘middleware’ always runs before a request is completed. For example, if user requests a connection to <a href="http://localhost:3000/">http://localhost:3000/</a> , the code within ‘middleware.ts’ is ran before the request is accepted.</p><p>Therefore adding the authentication logic within ‘middleware.ts’ will protect certain routes. Authentication logic will be something like “if authenticated then redirect to homepage, else redirect to login page”.</p><p>Sometimes the middleware doesn’t run properly. If that happens, try moving the 3 files outside of the src folder (at the root directory) and see if it fixes the issue</p><p>First, let’s define the type ‘User’</p><pre>// src/lib/definitions.ts<br>export type User = {<br>    id: string<br>    email: string<br>    name : string<br>};</pre><p>Authentication Logic Code</p><pre>// src/auth.config.ts<br>import type { NextAuthConfig } from &#39;next-auth&#39;;<br> <br>export const authConfig = {<br>  pages: {<br>    signIn: &#39;/login&#39;,<br>  },<br>  callbacks: {<br>    authorized({ auth, request: { nextUrl } }) {<br>      // Check if the user is authenticated<br>      const isLoggedIn = !!auth?.user;<br>      // Initialize protected routes<br>      // Here, all routes except the login page is protected<br>      const isOnProtected = !(nextUrl.pathname.startsWith(&#39;/login&#39;));<br>      <br>      if (isOnProtected) {<br>        if (isLoggedIn) return true;<br>        return false; // redirect to /login<br>      } else if (isLoggedIn) {<br>        // redirected to homepage<br>        return Response.redirect(new URL(&#39;/&#39;, nextUrl));<br>      }<br>      return true;<br>    },<br>  },<br>  providers: [], // Add providers with an empty array for now<br>} satisfies NextAuthConfig;</pre><p>Inititializing Next Auth</p><pre>// src/auth.ts<br>import NextAuth from &#39;next-auth&#39;;<br>import { authConfig } from &#39;./auth.config&#39;;<br>import Credentials from &#39;next-auth/providers/credentials&#39;;<br>import { User } from &#39;@/lib/definitions&#39;;<br><br>export const { signIn, signOut } = NextAuth({<br>  ...authConfig,<br>  providers: [<br>    Credentials({<br>      async authorize(credentials) {<br>        if (credentials.id &amp;&amp; credentials.password) {<br>          // Add you backend code here<br>          // let loginRes = await backendLogin(credentials.id, credentials.password)<br>          let loginRes = {<br>            success : true,<br>            data : {<br>              user: {<br>                ID: &quot;john_doe&quot;,<br>                NAME: &quot;John Doe&quot;,<br>                EMAIL: &quot;email@email.email&quot;,<br>              },<br>            }<br>          }<br>          // Failed logging in<br>          if (!loginRes.success) return null;<br>          // Successful log in<br>          const user = {<br>            id: loginRes.data.user.ID ?? &#39;&#39;,<br>            name: loginRes.data.user.NAME ?? &#39;&#39;,<br>            email: loginRes.data.user.EMAIL ?? &#39;&#39;,<br>          } as User;<br>          return user;<br>        }<br>        return null;<br>      },<br>    })<br>  ],<br>  callbacks: {<br>    async session({ session, token, user }) {<br>      session.user = token.user as User<br>      return session;<br>    },<br>    async jwt({ token, user, trigger, session }) {<br>      if (user) {<br>        token.user = user;<br>      }<br>      return token;<br>    },<br>  },<br>});</pre><p>Finally, run NextAuth inside middleware.ts</p><pre>// src/middleware.ts<br>import NextAuth from &#39;next-auth&#39;;<br>import { authConfig } from &#39;./auth.config&#39;;<br> <br>export default NextAuth(authConfig).auth;<br><br>export const config = {<br>  // https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher<br>  matcher: [&#39;/((?!api|_next/static|_next/image|.*\\.png$).*)&#39;],<br>};</pre><p>Next, set up the log in method that will be called by the client</p><pre>// src/lib/actions.ts<br>&quot;use server&quot;<br><br>import { signIn } from &quot;../auth&quot;;<br>import { AuthError } from &quot;next-auth&quot;;<br><br>export async function authenticate(<br>    prevState: string | undefined,<br>    formData: FormData,<br>  ) {<br>    try {<br>      await signIn(&#39;credentials&#39;, formData);<br>    } catch (error) {<br>      if (error instanceof AuthError) {<br>        return &#39;log in failed&#39;<br>      }<br>      throw error;<br>    }<br>  }</pre><p><strong>🔴Now let’s uncomment some lines on </strong><strong>src/app/login/page.tsxand </strong><strong>src/app/page.tsx🔴</strong></p><p><strong>👉 Login page</strong></p><pre>// src/app/login/page.tsx<br>&quot;use client&quot;<br><br>import { authenticate } from &quot;@/lib/actions&quot;<br>import { useFormState } from &quot;react-dom&quot;<br><br>export default function Page() {<br>    const [errorMsg, dispatch] = useFormState(authenticate, undefined)<br>    return (<br>      &lt;div&gt;<br>        &lt;h1&gt;Log in Page&lt;/h1&gt;<br>        &lt;form className=&quot;flex flex-col&quot; action={dispatch}&gt;<br>            &lt;input className=&quot;bg-blue-300 text-black&quot; name=&quot;id&quot;&gt;&lt;/input&gt;<br>            &lt;input className=&quot;bg-yellow-300 text-black&quot; name=&quot;password&quot; type=&quot;password&quot;&gt;&lt;/input&gt;<br>            &lt;button&gt;<br>                Log In<br>            &lt;/button&gt;<br>            &lt;p&gt;{errorMsg}&lt;/p&gt;<br>        &lt;/form&gt;<br>      &lt;/div&gt;<br>    )<br>  }</pre><p><strong>👉 Home page</strong></p><pre>// src/app/page.tsx<br>import { signOut } from &quot;../auth&quot;<br><br>export default async function Home() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Home Page&lt;/h1&gt;<br>      &lt;h2&gt;Unavailable without auth&lt;/h2&gt;<br>      &lt;form<br>          action={async () =&gt; {<br>            &#39;use server&#39;;<br>            await signOut();<br>          }}<br>        &gt;<br>          &lt;button&gt;<br>             Log Out<br>          &lt;/button&gt;<br>        &lt;/form&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><h3>✅ Results</h3><p>Heading to <a href="http://localhost:3000/">http://localhost:3000/</a> without loggin in</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fVgO1nujvtdSZehnYM0F-Q.png" /></figure><p>We are redirected to the login page.</p><p>Now type in any credentials</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mwm4txrfLraXevdMPDZ3wQ.png" /></figure><p>Then press on the ‘Log In’ button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*utcAdlT7U1brSJJWCakXDA.png" /></figure><p>We are successfully logged in and authenticated to view the home page. Try clicking on the ‘Log Out’ button to see what happens as well.</p><p>For now typing in any credentials allows authentication because we have hard coded the use data in src/auth.ts file as</p><pre>user: {<br>  ID: &quot;john_doe&quot;,<br>  NAME: &quot;John Doe&quot;,<br>  EMAIL: &quot;email@email.email&quot;,<br>},</pre><p>Therefore all you need to do is fix the loginRes and User type definition according to your backend code and you are good to go</p><h3>🔴Important Notes when Deploying🔴</h3><p>Before deploying your app, make sure to add the following variables inside you .env file</p><pre>NEXTAUTH_URL= ${deploying domain url}<br>NEXT_PUBLIC_API_URL= ${deploying domain url}</pre><p>If the above is not satisfied, the callback url will be set to localhost:3000 and errors will occur.</p><h3>Upcoming &amp; Source Code</h3><p>Next tutorial is about calling sessions to view user data and ways to update the session!</p><p><a href="https://medium.com/@youngjun625/next-js14-nextauth-v5-2-session-update-b977cb6afd47">[Next.js14] NextAuth v5 (2) — Session/Update</a></p><p>You can checkout the full source code below!</p><p><a href="https://github.com/youngjun625/nextauth14-nextauthv5">GitHub - youngjun625/nextauth14-nextauthv5: [Next.js14] NextAuth v5 tutorial</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e30cce52e7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Nextjs] Error: ws does not work in the browser.]]></title>
            <link>https://medium.com/@youngjun625/nextjs-error-ws-does-not-work-in-the-browser-c48b320ff021?source=rss-e8721502aec3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c48b320ff021</guid>
            <category><![CDATA[wss]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[basic-authentication]]></category>
            <dc:creator><![CDATA[YJ Kim]]></dc:creator>
            <pubDate>Tue, 09 Jan 2024 09:07:45 GMT</pubDate>
            <atom:updated>2024-01-10T01:59:04.621Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Nextjs] Error: ws does not work in the browser. Browser clients must use the native WebSocket object</h3><p>This is a devlog about solving a problem using websockets with the ‘ws’ package on client side of NextJS.</p><blockquote>Error: ws does not work in the browser. Browser clients must use the native WebSocket object</blockquote><p>I’ve faced this error while developing a chat service using Nextjs 14. Our dev team used websockets in the backend to implement real-time chatting. I already developed a mobile app using Flutter with the same given endpoint, so I didn’t think there were going to be much trouble developing on web… but I was wrong.</p><h3>Problem</h3><p>The given websocket endpoint was using ‘wss’ protocal and required ‘basic authentication’ to connect. Therefore I tried using the ‘ws’ package. In order to efficiently develop a chatting UI, I needed to use client side rendering. Then I faced the error ‘ws does not work in the browser’.</p><p>Native WebSocket object was not a solution either because it does not accept headers, therefore basic auth could not be handled.</p><p>‘ws’ package could not be used, native WebSocket was not a option, and fixing the backend code would take up too much of our team’s resources.</p><h3>Solution</h3><p>My solution was to use the ‘ws’ package at the server side of Next to communicate with our backend, and use ‘socket.io’ package to connect the server side and client side of Next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*QTAQ6boM6z0rBZHLxP1SKA.png" /></figure><h3>Code</h3><p>First, install the following packages using npm</p><pre>npm install ws socket.io socket.io-client</pre><p>Folder structure of the project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/175/1*FsHlsYVWP9oj3evR6HCgFw.png" /></figure><p>Next.js 14 uses app router as default. However socket.io is not compatible with app router yet. Therefore an additional pages router was added by creating a new pages/ directory at the root project directory</p><h3>Server side code</h3><pre>// src/types.ts<br>import { Server as NetServer, Socket } from &quot;net&quot;<br>import { NextApiResponse } from &quot;next&quot;<br>import { Server as SocketIOServer } from &quot;socket.io&quot;<br><br>export type NextApiResponseServerIO = NextApiResponse &amp; {<br>    socket: Socket &amp; {<br>        server: NetServer &amp; {<br>            io: SocketIOServer;<br>        }<br>    }<br>}</pre><pre>// pages/api/socket/io.ts<br>import { Server as NetServer } from &quot;http&quot;<br>import { NextApiRequest } from &quot;next&quot;<br>import { Server as SocketServer } from &quot;socket.io&quot;<br>import { NextApiResponseServerIO } from &quot;@/types&quot;<br><br>export const config = {<br>    api : {<br>        bodyParser : false<br>    }<br>}<br><br>const WebSocket = require(&quot;ws&quot;);<br><br>// retrieving Basic Auth data from .env<br>const username = process.env[&#39;KEY_ID&#39;];<br>const password = process.env[&#39;KEY_PASSWORD&#39;];<br>const auth =  Buffer.from(`${username}:${password}`).toString(&quot;base64&quot;);<br><br>const ioHandler = (req: NextApiRequest, res: NextApiResponseServerIO) =&gt; {<br>    if(!res.socket.server.io) {<br>      	// endpoint settings<br>        const path = &quot;/api/socket/io&quot;<br>        const httpServer: NetServer = res.socket.server as any;<br>        const io = new SocketServer(httpServer, {<br>            path: path,<br>            addTrailingSlash: false,<br>            // socket.io requires cors options when deploying on server<br>            // no conflicts in development<br>            // cors: {<br>            //    origin: &quot;${domain url}&quot;,<br>            //    methods: [&quot;GET&quot;, &quot;POST&quot;]<br>            // }<br>        });<br>        res.socket.server.io = io;<br>      	<br>      	// websocket connections<br>      	//****************************************************<br>      	// serverSocket : connection between backend and Next Server side<br>      	// ioScoket : connection between Next server side and Next client side<br>      	//****************************************************<br>        let serverSocket : WebSocket;<br>        io.on(&quot;connection&quot;, (ioSocket) =&gt; {<br>            if(socket.handshake.query[&#39;key&#39;]) {<br>              	// query from client side can be retrieved<br>              	// retrieved query can be used as parameters in URL<br>                const value = ioSocket.handshake.query[&quot;key&quot;];<br>              	// WebSocket object is from the &#39;ws&#39; package NOT native<br>                serverSocket = new WebSocket(`wss://${endpoint}/?key=${value}`, {<br>                    // adding headers<br>                    headers: {<br>                        &quot;authorization&quot;: `Basic ${auth}`<br>                    }<br>                });<br>                serverSocket.onopen = (e) =&gt; {<br>                    // connection between Next server and backend wss established<br>                    console.log(&quot;serverSocket connected.&quot;);<br>                }<br>                serverSocket.onmessage = (e) =&gt; {<br>                    // receiving json data from backend wss<br>                    const data = JSON.parse(e.data);<br>                    // emitting(sending) data to client<br>                    // form of ioSocket.emit(key, value)<br>                    ioSocket.emit(&quot;message&quot;, data);<br>                }<br>                serverSocket.onclose = (e) =&gt; {<br>                    console.log(&quot;socket disconnected.&quot;);<br>                }<br>            }<br>          	<br>            // retrieving data from client side<br>            ioSocket.on(&quot;dataToServer&quot;, (data) =&gt; {<br>              	// sending data retrieved from client to backend wss<br>                serverSocket.send(JSON.stringify({<br>                    sender : data.sender,<br>                    chat: data.chat,<br>                    created_at: data.created_at<br>                }));<br>            })<br>        })<br>    }<br>    res.end()<br>}<br><br>export default ioHandler</pre><pre>// pages/api/socket/messages.ts<br>import { NextApiRequest } from &quot;next&quot;;<br>import { NextApiResponseServerIO } from &quot;@/types&quot;;<br><br>// method for sedning message from client side<br>export default async function handler(<br>    req: NextApiRequest, <br>    res: NextApiResponseServerIO<br>) {<br>    if(req.method !== &quot;POST&quot;) {<br>        return res.status(405).json({ message: &quot;Method not allowed&quot; });<br>    }<br><br>    try {<br>      	// io?.emit(key, value)<br>        res?.socket?.server?.io?.emit(&quot;dataToServer&quot;, req.body);<br>        return res.status(200).json({ message: &quot;OK&quot; });<br>    } catch (error) {<br>        return res.status(500).json({ message: &quot;Internal Error&quot; });<br>    }<br>}</pre><h3>Client side code</h3><pre>&quot;use client&quot;<br>import axios from &quot;axios&quot;;<br>import { io } from &quot;socket.io-client&quot;;<br>import { useEffect, useRef, useState } from &quot;react&quot;;<br><br>export interface Message {<br>    sender: string;<br>    chat: string;<br>    createdAt: string;<br>}<br><br>export default function Page() {<br>    // user id of current user, could be retrieved from session<br>    let myid = &quot;user1&quot;<br>    const [chats, setChats] = useState&lt;Array&lt;Message&gt;&gt;([])<br>    useEffect(() =&gt; {<br>        // *******************************************************************************<br>      	// NEXT_PUBLIC_API_URL = ${domain url]<br>        // Must be stated at .env file before deploying<br>        // default value is: http://localhost:3000<br>        // *******************************************************************************<br>        const ioSocket =  io(process.env.NEXT_PUBLIC_API_URL!, {<br>            path: &quot;/api/socket/io&quot;,<br>            addTrailingSlash: false,<br>            query: {<br>                // query send to server side code<br>                &quot;key&quot; : &quot;value&quot;<br>            },<br>            upgrade: false,<br>        })<br>        ioSocket.on(&quot;connect&quot;, () =&gt; {<br>            console.log(&#39;connected socket&#39;)<br>        })<br><br>        // retrieving value with key of &#39;message&#39;, then added to chats<br>        ioSocket.on(&quot;message&quot;, (data) =&gt; {<br>            setChats((prev)=&gt;[...prev, {<br>              sender: data.sender,<br>              chat: data.chat, <br>              createdAt: data.created_at<br>            } as Message])<br>        })<br>        ioSocket.on(&quot;disconnect&quot;, () =&gt; {<br>            console.log(&#39;disconnected socket&#39;)<br>        })<br>        return () =&gt; {<br>            ioSocket.disconnect();<br>        }<br>    }, [])<br>    <br>    const scrollRef = useRef(null);<br>    useEffect(() =&gt; {<br>        //scrolls screen to bottom whenver new chat is added<br>        scrollRef.current?.scrollTo({<br>            top: scrollRef.current?.scrollHeight,<br>            behavior: &#39;smooth&#39;,<br>        });<br>      }, [chats]);<br>    <br>    let userChat = &#39;&#39;;<br>    const textAreaRef = useRef(null);<br>    const handleSubmit = () =&gt; {<br>        axios.post(`/api/socket/messages`, {<br>            sender : myId,<br>            chat : userChat,<br>            created_at : new Date().getTime(),<br>        })<br>        textAreaRef.current.value = &#39;&#39;<br>    }<br><br>    return (<br>        &lt;div className=&quot;flex flex-col h-screen&quot;&gt;<br>            &lt;div className=&quot;flex flex-col flex-1 overflow-scroll scrollbar-hide&quot;<br>                ref={scrollRef}<br>            &gt;<br>               { chats.map((chat) =&gt; {<br>                    return &lt;h1 className={`${chat.sender==myid ? &quot;self-end&quot;: &quot;self-start&quot;}`}&gt;{chat.chat}&lt;/h1&gt;<br>                })<br>               }<br>            &lt;/div&gt;<br>            &lt;div className=&quot;w-full rounded-[10px] bg-grey1&quot;&gt;<br>                &lt;textarea<br>                    autoFocus ={true}         <br>                    ref={textAreaRef}<br>                    className=&quot;w-[calc(100%-40px)] sm:w-full bg-transparent resize-none overflow-auto outline-none scrollbar-hide h-[38px] &quot;<br>                    placeholder={ &quot;메세지&quot;}<br>                    onChange={(event) =&gt; userChat = event.target.value}<br>                    onKeyDown={(event) =&gt; {<br>                      if (event.code === &#39;Enter&#39;){<br>                          event.preventDefault();<br>                      }<br>                      if (event.code === &#39;Enter&#39; &amp;&amp; userChat !== &#39;&#39; &amp;&amp; event.nativeEvent.isComposing === false) {<br>                           handleSubmit();    <br>                      }<br>                    }<br>                &gt;<br>                &lt;/textarea&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    )<br>}</pre><p>Felt like a long way around and it definitely has room for improvements. Please feel free to comment about anything!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c48b320ff021" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>