<?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 Saad Masood on Medium]]></title>
        <description><![CDATA[Stories by Saad Masood on Medium]]></description>
        <link>https://medium.com/@mrsaadmasood1?source=rss-9a598a0687c4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*aI48WAhS9r11BfPp</url>
            <title>Stories by Saad Masood on Medium</title>
            <link>https://medium.com/@mrsaadmasood1?source=rss-9a598a0687c4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 18:11:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mrsaadmasood1/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[Exploring the Depths of Next-Auth Hell! !! Part — 2]]></title>
            <link>https://medium.com/@mrsaadmasood1/exploring-the-depths-of-next-auth-hell-part-2-07710a04985b?source=rss-9a598a0687c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/07710a04985b</guid>
            <category><![CDATA[nextauth]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[authjs]]></category>
            <category><![CDATA[auth]]></category>
            <dc:creator><![CDATA[Saad Masood]]></dc:creator>
            <pubDate>Fri, 05 Jul 2024 18:10:52 GMT</pubDate>
            <atom:updated>2024-07-06T13:35:43.731Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring the Depths of Next-Auth Hell! !! Part — 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0woH5lOfAA1_FTQHbUAFRg.jpeg" /></figure><h3><strong>Introduction:</strong></h3><p>So you have learned how to do the basic auth with Next-auth / Auth js. That part covered very basic use case of next-auth where you just need to check if the user is signed in. Now lets dive deeper and see what real world use of next-auth looks like.</p><h3>Prerequisites:</h3><p>You must have the basic understanding of how Next-Auth works including its basic config with “Credentials” and “OAuth” providers. If you are unfamiliar with it you can go and look at <a href="https://medium.com/@mrsaadmasood1/exploring-the-depths-of-next-auth-hell-part-1-17e9b86399ce">Exploring the Depths of Next-Auth Hell! !! Part — 2</a></p><p>That’s all you need. You are a pro now. Close this blog and go where ever you like. The end! LOL! Let’s continue</p><h3>The Problem:</h3><p>If you have applied the basic next-auth config in your project for auth you would have come across a problem, the session object would look like this:</p><pre>{<br>  data: {<br>    user: {<br>      name: &quot;Mr Noob&quot;,<br>      email : &quot;thebestnoob@email.com&quot;,<br>      image : &quot;https://noob-picture.com&quot;,<br>      // some random properties<br>    }<br>  }<br>}</pre><p>You would wonder why I am getting this user when I am querying from the database and then returning that user? Why is this happening!</p><p>Suppose your database user schema looks like this:</p><pre>{<br>  name: &quot;Mr Noob&quot;,<br>  email : &quot;thebestnoob@email.com&quot;,<br>  image : &quot;https://noob-picture.com&quot;,<br>  isSubscribed : &quot;none&quot;<br>  login_method: &quot;normal&quot; || &quot;google&quot;<br>}</pre><p>Why are you not getting the fields like <strong>isSubscribed</strong> and <strong>login_method</strong> in the session object and why you getting only half baked properties there? How can you extend this?</p><p>Well that will be your first question if you are building a real world web app. You are saying you make static websites in JS? and need login to show static pages? So much for being a pro! Are you sure you don’t want to use PHP?</p><p>Anyways… lets see the solution.</p><h3>The Solution:</h3><p>Well… Hail the Next-Auth callbacks!</p><h3><strong>Callbacks:</strong></h3><p>You are now going to learn callbacks in Authjs. That’s where the authjs hell officially began for me. I was waiting for a prince to come save me. I even left my sandal at many places. No prince came for me nor will for you.</p><p>“There is no paradise for you to escape to”- Guts/Berserk</p><p>What are these callbacks?</p><p>They are the function that are called in specific sequence / at specific events by the authjs internally and can help us extend our user object primarily — plus help us with some additional tasks that I will explain later.</p><h3>Basic Config:</h3><p>Untill now our basic config for auth js looks something like this:</p><pre>/auth.ts<br><br>import { sql } from &quot;@vercel/postgres&quot;;<br>import Credentials from &quot;next-auth/providers/credentials&quot;<br>import bcrypt from &quot;bcryptjs&quot;<br><br>export const { handlers, signIn, signOut, auth } = NextAuth({<br>  session: {<br>    strategy: &quot;jwt&quot; <br>  },<br>  providers: [<br>    Google,<br>    Credentials({<br>      credentials: {<br>        email: {},<br>        password: {}<br>      },<br>      async authorize(credentials) {<br>        let customUser = await sql&lt;User&gt;<br>          `SELECT * FROM users WHERE email = ${credentials.email as email}`<br>        <br>        const matchPassword = await bcrypt.compare(<br>          credentials.password as string, customUser.rows[0].password<br>        )<br>        if (!matchPassword) throw new Error(&quot;Failed to Login User&quot;)<br>        return customUser.rows[0]<br>      }<br>    })<br>  ],<br>  pages: {<br>    signIn: &quot;/login&quot;,<br>    signOut: &quot;/login&quot;,<br>    error: &quot;/error&quot;<br>  },<br>})</pre><p>You don’t know what this config is doing? WTH! What are you doing here then? Go read the <a href="https://medium.com/@mrsaadmasood1/exploring-the-depths-of-next-auth-hell-part-1-17e9b86399ce">part 1</a> of the blog.</p><h3>Diving Deep:</h3><p>Let change out config and add the callbacks in it.</p><pre><br>import bcrypt from &quot;bcryptjs&quot;<br>import NextAuth from &quot;next-auth&quot;<br>import Credentials from &quot;next-auth/providers/credentials&quot;<br>import Google from &#39;next-auth/providers/google&#39;<br><br>export const { handlers, signIn, signOut, auth } = NextAuth({<br>  session: {<br>    strategy: &quot;jwt&quot;<br>  },<br>  providers: [<br>    Google,<br>    Credentials({<br>      credentials: {<br>        email: {},<br>        password: {},<br>        role: {}<br>      },<br>      async authorize(credentials) {<br>        // authenticating with database here.<br>      }<br>    })<br>  ],<br>  pages: {<br>    signIn: &quot;/login&quot;,<br>    signOut: &quot;/login&quot;,<br>    error: &quot;/error&quot;<br>  },<br>  callbacks: {<br>    async jwt({ token, user, account }) {<br>       // user from authorize function is returned here after<br>       // if signIn callback returns true<br>      return token<br>    },<br>    async session({ session, token }) {<br>      // token from the jwt callback is returned here<br>      return session<br>    },<br>    async signIn({ user, account }) {<br>      // user from authorize function is return first here and<br>      // it controls if the user is allowed to sign in<br>      return true<br>    }<br>  }<br>})</pre><p>This is the as simple as it gets. Now I will start explaining what each callback is doing and where they can be utilized:</p><h3>1- signIn:</h3><p>It is used to control whether the user is allowed to sign in! Basically what happens is when the user is returned either from “credentials” or “Oauth” provider, it is first received here and we can check if the user should be allowed to sign in. This is the last checkpoint, where you can perform operations like only allowing users with specific roles to sign in or filtering for some users etc.</p><p>What I am using this signIn function is for users who are logging in from OAuth Providers like google and since they do not create an account from the Sign Up page, we are going to create their account automatically as they are signing in. Here is how that looks:</p><pre><br>export const { handlers, signIn, signOut, auth } = NextAuth({<br>  session: {<br>    strategy: &quot;jwt&quot;<br>  },<br>  providers: [<br>    Google,<br>    Credentials({<br>      // credientials logic as above<br>  ],<br>  pages: {<br>    signIn: &quot;/login&quot;,<br>    signOut: &quot;/login&quot;,<br>    error: &quot;/error&quot;<br>  },<br>  callbacks: {<br>    async signIn({ user, account }) {<br>      if (account?.provider === &quot;google&quot;) {<br>        const userExists = await <br>          sql`SELECT noob_user FROM users WHERE id = ${user.id}`<br>        if (!userExists.rowCount) {<br>          // creating the new user with login method as google<br>          const userCreated = await <br>            sql`INSERT INTO users (// column names) VALUES (// values)`<br>          if (!userCreated.rowCount) return false<br>        }<br>      }<br>      return true<br>    }<br>  }<br>})</pre><p>Here the <strong>account.provider</strong> contains the information about the OAuth provider that is being used to log in and will not be available for the normal “credentails” login. You get the idea now go and delete the production database my soldiers 😛.</p><p>YOU MUST RETURN A BOOLEAN HERE!</p><h3>2- jwt:</h3><p>The jwt callback is called, <strong>read carefully,</strong></p><p><strong>1- </strong>After the signIn callback returns true i.e at sign in.</p><p><em>The arguments user, account and profile are only passed the first time this callback is called on a new session, after the user signs in. In subsequent calls, only </em><em>token will be available.</em></p><p><strong>2-</strong> Whenever the session object is accessed in the client.</p><p>Still not clear what this call back does? Its simple. On successfull sign in, the jwt callback is invoked with user object that is returned from the “authorize” callback containing all your custom user fields that you return there. But in case of sign in using the OAuth providers the user in the jwt is populated with the data the provider gives.</p><p>Well you might say, if you cant return your custom user through the Oauth providers , whats the point, we are back to square one. Yes! You are right, I agree with you. But here inside the jwt callback we can make another call to the database using the user’s email and get the user which we stored / created in the previous <strong>“signIn”</strong> callback.</p><p>Too much work and things to understand here! Dont know why I am doing this? Whats the problem with regular manual auth? Well I dont know? I am still looking for answers. 😥.</p><p>Here is how the code looks now:</p><pre>import { JWT } from &quot;next-auth/jwt&quot;<br><br>export const { handlers, signIn, signOut, auth } = NextAuth({<br>  session: {<br>    strategy: &quot;jwt&quot;<br>  },<br>  providers: [<br>    Google,<br>    Credentials({<br>      // credientials logic as above<br>  ],<br>  pages: {<br>  // custom pages<br>  },<br>  callbacks: {<br>    async jwt({ token, user, account }) {<br>      if (user) {<br>        let customUser = user as RoleBasedUser<br>        if (account?.provider === &quot;google&quot;) {<br>          const googleUser = await <br>            sql`give me user with email = ${user.email}`<br>          if (!googleUser.rowCount) throw new Error<br>          customUser = googleUser.rows[0]<br>        }<br>        return {<br>          ...token,<br>          name : customUser.name,<br>          email : customUser.email,<br>          image : customUser.image,<br>          login_method: customUser.login_method,<br>          free_tokens: customUser.free_tokens,<br>          subscription_type: customUser.subscription_type,<br>          id: customUser.id<br>        } as JWT<br>      }<br>      return token as JWT<br>    }<br>  }<br>})</pre><p>Since the “user” object is only available on signIn and not for other subsequent calls, we check if the user exists then we check if the account.provider exists? If yes, then we query our database for that user and replace the user. Finally, we return the original token object from the callback and add the properties manually to the returned object. Basically we are extending our token object here. Buy why? Dont half explain things!! 😡😡😡</p><p>Woahh. Patience dear. Its because this token object will be reflected in out session object. So you can make any changes here and modify it as you like to make those properties avaiable in your application.</p><p>We only do this for signIn, when the user is available for all other subsequent calls we just return the token. What? You forgot when the jwt callback is invoked? 🤭🤭🤭</p><p>Two down ! One more to go!!!!</p><h3>3- session callback:</h3><p>Lastly, we have the session callback. As the name suggests , it return the session object that we access in the application. The token object you return from the “jwt” callback is passed to this function here you can extend the session object , change its structure (though I have not tried that yet, only did minor changes, but I think that’s it inteded purpose) and then return that changed session object which will finally be available in the application.</p><p><strong>NOTE: </strong>It is the return value of <strong>session callback</strong> that is accessible in the application and not the jwt callback’s return value (which is just passed to the session callback).</p><pre>import { JWT } from &quot;next-auth/jwt&quot;<br><br>export const { handlers, signIn, signOut, auth } = NextAuth({<br>  session: {<br>    strategy: &quot;jwt&quot;<br>  },<br>  providers: [<br>    Google,<br>    Credentials({<br>      // credientials logic as above<br>  ],<br>  pages: {<br>  // custom pages<br>  },<br>  callbacks: {<br>     async session({ session, token }) {<br>      return {<br>        ...session,<br>        user: {<br>          ...token<br>        }<br>      }<br>    }<br>  }<br>})</pre><p>We are just copying the token object what we returned in the jwt callback inside the user property in the session object that we are returning.</p><p>Now if you again console log the session object, you will get this:</p><pre>{<br>  name: &quot;Mr Noob&quot;,<br>  email : &quot;thebestnoob@email.com&quot;,<br>  image : &quot;https://noob-picture.com&quot;,<br>  isSubscribed : &quot;none&quot;<br>  login_method: &quot;normal&quot; || &quot;google&quot;<br>}</pre><p>Congratulations!!!! That covers most of the use cases.</p><h3>Types Extenstion:</h3><p>If you are using typescript you would have already come up with some ugly errors and when you try to access the <strong>session.user</strong> in the application. You would see that the intelliSense is not showing the extended session.user object plus those ugly type errors on callbacks.</p><p>Lets do some module augmentation in typescript!</p><p>Module Augmentation is basically extendingf/patching the some interfaces by importing a module and then updating it to include new types too thorugh declaration.</p><pre>import NextAuth, { DefaultSession } from &quot;next-auth&quot;;<br>import { JWT, DefaultJWT } from &quot;next-auth/jwt&quot;<br><br>interface RoleBasedUser {<br>  name : string<br>  email : string<br>  image : string<br>  login_method: string<br>  isSubscribed : string<br>  role : &quot;user&quot;<br>} | {<br>  id: string<br>  role: &quot;admin&quot;<br>  playername: &quot;noobadmin&quot;<br>  email: string<br>}<br><br>declare module &quot;next-auth&quot; {<br>// extend the session object<br>  interface Session {<br>    user: RoleBasedUser &amp; DefaultSession[&#39;user&#39;]<br>  }<br>// extend the user object<br>  interface User extends RoleBasedUser { }<br><br>}<br><br>// extend the return value of the jwt callback<br>declare module &quot;next-auth/jwt&quot; {<br>  interface JWT extends RoleBasedUser { }<br>}</pre><p><strong>DefaultSession </strong>here refers the built-in next-auth user types. We are updating the session object to include both the built in types and extended types. The cool thing about module augmentation is that it looks at the declarations of that module, match the interfaces and then update them without us having to change anything in the source declaration files.</p><h3><strong>Role Based Authentication</strong></h3><p>This is the last thing I promise. Pinky Promise!</p><p>Lets say you have both users an admins in you schema where user looks like:</p><pre>{<br>  name: &quot;Mr Noob&quot;,<br>  email : &quot;thebestnoob@email.com&quot;,<br>  image : &quot;https://noob-picture.com&quot;,<br>  isSubscribed : &quot;none&quot;,<br>  login_method: &quot;normal&quot; || &quot;google&quot;,<br>  role : &quot;user&quot;<br>}</pre><p>and the admin as:</p><pre>{<br>  id: string<br>  role: &quot;admin&quot;<br>  playername: string,<br>  email: string<br>}</pre><p>For role based authentication you can just use the “<strong>Credentials</strong>” providers and add another extra property based on the search params when invoking the signIn function:</p><pre><br>const isAdmin = searchParams.get(&quot;admin&quot;)<br><br>await signIn(&quot;credentials&quot;, { email, password, role: isAdmin ? &quot;admin&quot; : &quot;user&quot;, redirectTo: &quot;/&quot; })</pre><p>You need to change the configuration file to add the role as well:</p><pre>/auth.ts<br><br>export const { handlers, signIn, signOut, auth } = NextAuth({<br>  providers: [<br>    Credentials({<br>      credentials: {<br>        email: {},<br>        password: {},<br>        role : {}<br>      },<br>      async authorize(credentials) {<br>        if(credentials.role === &quot;admin&quot;){<br>          const admin = await <br>            sql`SELECT * FROM admins <br>              WHERE email = ${credentials.email} <br>              AND  role = ${credentials.role}`<br>          if(!admin.rowCount) throw new Error<br>          return admin.rows[0]<br>        }<br>        const user = sql`getting user`<br>        return user.rows[0]<br>      }<br>    })<br>  ],<br>  pages: {<br>    // custom pages<br>  },<br>  callbacks: {<br>    async jwt({ token, user, account }) {<br>      if (user) {<br>        let customUser = user as RoleBasedUser<br>        if (customUser.role === &quot;admin&quot;) {<br>          return {<br>            ...token,<br>            id: customUser.id,<br>            email: customUser.email,<br>            playername: customUser.playername,<br>            role: customUser.role<br>          }<br>        }<br>        return {<br>          ...token,<br>          first_name: customUser.first_name,<br>          last_name: customUser.last_name,<br>          login_method: customUser.login_method,<br>          free_tokens: customUser.free_tokens,<br>          subscription_type: customUser.subscription_type,<br>          id: customUser.id,<br>          role: customUser.role<br>        } as JWT<br>      }<br>      return token as JWT<br>    },<br>})</pre><p>We are just querying in the authorzie function to give us either the admin or the user based on the role and then in the jwt callback we are returning the properties based on the role.</p><p>To access that role in the application you can just do:</p><pre>/app/page.tsx<br><br>import { auth } from &quot;/auth&quot;<br><br>export default async function Random(){<br>  const session = await auth()<br>  if(session?.user.role === &quot;admin&quot;){<br>    return &lt;div&gt;I am a noob admin! plz save save me&lt;/div&gt;<br>  }<br>  else {<br>    return &lt;div&gt; I , the reader am noob who does not now how to implement <br>      basic auth manually. I the reader got skill issues. &lt;/div&gt;<br>  }<br>}</pre><p>One more thing. Man why does this not stop! Plz I beg you end this or I’ll start to cry.</p><p>Okay! Okay!</p><p>We just need to update the middleware like this</p><pre>import { auth } from &quot;@/lib/authJs/auth&quot;<br><br>export default auth((req) =&gt; {<br>  if (<br>    !req.auth &amp;&amp; req.nextUrl.pathname.startsWith(&quot;/dashboard/user&quot;))<br>    return Response.redirect(<br>      new URL(&quot;/login&quot;, req.nextUrl.origin)<br>    )<br><br>  if (req.auth &amp;&amp; req.auth.user.role === &quot;user&quot; &amp;&amp; <br>        req.nextUrl.pathname.startsWith(&quot;/dashboard/admin&quot;))<br>    return Response.redirect(new URL(&quot;/dashboard/user&quot;, req.nextUrl.origin))<br><br>  if (req.auth &amp;&amp; req.auth.user.role === &quot;admin&quot; &amp;&amp; <br>      req.nextUrl.pathname.startsWith(&quot;/dashboard/user&quot;))<br>    return Response.redirect(new URL(&quot;/dashboad/admin&quot;, req.nextUrl.origin))<br>})<br><br>export const config = {<br>  matcher: [&quot;/((?!api|_next/static|_next/image|favicon.ico).*)&quot;]<br>}<br><br></pre><p>This is a sample middleware where we are first checking if the user is not signed in the redirect the user to the login page. Else, based on the role if the user is trying to access the page opposite to its role, we redirect the user to the appropriate urls.</p><p>Well! How would you do role based authentication with OAuth providers where we cant return the user ourselves. I think that it is a limiting factor here as I could not find a way to implement admin creation through OAuth providers. At least till now. What are the reason? Try to implement it youself and you’ll understand the limitation of authjs. If you figure out a way to do this message me at:</p><p><a href="https://www.linkedin.com/in/saad-masood-8b100125b/">LinkedIn</a></p><p>Here is how your complete config file might look like:</p><pre>import { signInSignUpUser } from &quot;@/actions/action&quot;<br>import bcrypt from &quot;bcryptjs&quot;<br>import { randomUUID } from &quot;crypto&quot;<br>import NextAuth from &quot;next-auth&quot;<br>import { JWT } from &quot;next-auth/jwt&quot;<br>import Credentials from &quot;next-auth/providers/credentials&quot;<br>import Google from &#39;next-auth/providers/google&#39;<br>import { getAdminQuery, getUserQuery } from &quot;@/SQLqueries/queries&quot;<br>import { QueryResult } from &quot;pg&quot;<br><br>export const { handlers, signIn, signOut, auth } = NextAuth({<br>  session: {<br>    strategy: &quot;jwt&quot;<br>  },<br>  providers: [<br>    Google,<br>    Credentials({<br>      credentials: {<br>        email: {},<br>        password: {},<br>        role: {}<br>      },<br>      async authorize(credentials) {<br>        let customUser: QueryResult&lt;RoleBasedUser&gt;<br>        if (credentials.role === &quot;admin&quot;) {<br>          customUser = await getAdminQuery(credentials.email as string)<br>        }<br>        else {<br>          customUser = await getUserQuery(credentials.email as string)<br>        }<br>        const matchPassword = await bcrypt.compare(credentials.password as string, customUser.rows[0].password)<br>        if (!matchPassword) throw new Error(&quot;Failed to Login User&quot;)<br>        return customUser.rows[0]<br>      }<br>    })<br>  ],<br>  pages: {<br>    signIn: &quot;/login&quot;,<br>    signOut: &quot;/login&quot;,<br>    error: &quot;/error&quot;<br>  },<br>  callbacks: {<br>    async jwt({ token, user, account }) {<br>      if (user) {<br>        let customUser = user as RoleBasedUser<br>        if (account?.provider === &quot;google&quot;) {<br>          const googleUser = await getUserQuery(token.email!, &#39;google&#39;)<br>          if (!googleUser.rowCount) throw new Error(&quot;Failed to get the google user&quot;)<br>          customUser = googleUser.rows[0]<br>        }<br>        if (customUser.role === &quot;admin&quot;) {<br>          return {<br>            ...token,<br>            id: customUser.id,<br>            email: customUser.email,<br>            username: customUser.username,<br>            role: customUser.role<br>          }<br>        }<br>        return {<br>          ...token,<br>          first_name: customUser.first_name,<br>          last_name: customUser.last_name,<br>          login_method: customUser.login_method,<br>          free_tokens: customUser.free_tokens,<br>          subscription_type: customUser.subscription_type,<br>          id: customUser.id,<br>          role: customUser.role<br>        } as JWT<br>      }<br>      return token as JWT<br>    },<br>    async session({ session, token }) {<br>      return {<br>        ...session,<br>        user: {<br>          ...token<br>        }<br>      }<br>    },<br>    async signIn({ user, account }) {<br>      if (account?.provider === &quot;google&quot;) {<br>        const userExists = await getUserQuery(user.email!, &quot;google&quot;)<br>        console.log(&quot;loggin the finding of google user&quot;)<br>        if (!userExists.rowCount) {<br><br>          const userCreated = await signInSignUpUser(&quot;signup&quot;, {<br>            username: user.name!,<br>            email: user.email!,<br>            password: user.id || randomUUID(),<br>            loginMethod: &#39;google&#39;<br>          }, &#39;user&#39;)<br>          if (!userCreated) return false<br>        }<br>      }<br>      return true<br>    }<br>  }<br>})</pre><p>THE END!!!!!!!</p><p>I hope it saves you time!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07710a04985b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the Depths of Next-Auth Hell! !! Part — 1]]></title>
            <link>https://medium.com/@mrsaadmasood1/exploring-the-depths-of-next-auth-hell-part-1-17e9b86399ce?source=rss-9a598a0687c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/17e9b86399ce</guid>
            <category><![CDATA[auth]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[jwt-authentication]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[nextauth]]></category>
            <dc:creator><![CDATA[Saad Masood]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 16:37:46 GMT</pubDate>
            <atom:updated>2024-07-05T18:38:01.500Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring the Depths of Next-Auth Hell! !! Part — 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0woH5lOfAA1_FTQHbUAFRg.jpeg" /><figcaption>Auth.js</figcaption></figure><h3>Introduction:</h3><p>3rd Party Auth solutions are geting quite popular and I too decided to ride on the train and train such a solution. For a new Developer like me it was One HELL OF A RIDE!!! The shit I went through was so frustrating while i was figuring out how to implement next-auth (I really think that spending an entire Afing week on it) was not worth the effort, but how would i call myself a developer if i left things incomplete after starting them. After successfully implementing it, I thought that NO ONE absolutely NO ONE should go through the pain i went through just because of some shitty documentation at least at this point I am writing the article. So hop on, I will try to explain it as simply as possible and try to cover some advanced cases that go beyond the normal use.</p><h3>Why Next-Auth/ Auth-js:</h3><p>If you ask me why should we use next-auth?</p><p>Honestly I dont know!!! Why ? Coz this bitch gave me an afing hell trying to implement it. I went in with the hype train that next-auth is a good solution to implement auth and very flexible and REALLY easy to implement. Like Come On!!! Due to the poor documentation and not many articles to read online it was a very frustrating task trying to first understand how it works and then implementing it. I still can’t understand why you would prefer it over doing auth yourself ( which is really easy and wayyyy more flexible than any 3rd party solution once you have configured it to your needs, its just copy pasting after that point and adjusting it according to your recent use case) especially when your use case goes beyond just checking if the user is signed in and want to do more like Role Based Access using custom and OAuth, creating users in your database and using that user data in you application.</p><p>I would love to hear you arguments on this. Help me broaden my perspective. You can send me a message at <a href="https://www.linkedin.com/in/saad-masood-8b100125b/">LinkedIn</a></p><h3>What This Part Covers:</h3><p>1- Custom pages with next-auth</p><p>2- Credentials Provider</p><p>3- OAuth provider</p><p>4- Basic Configuration</p><p>5- Next-auth in Middleware</p><h3>Prerequisites:</h3><p>1- You must have some knowledge of Nextjs. I wont be teaching you how to walk.</p><p>2- Knowledge of how basic auth is implemented.</p><h3>Getting Started With Next-Auth:</h3><p>One thing to keep in mind is that if you using the latest version of Next js / app router you need to go to the <a href="https://authjs.dev/"><strong>https://authjs.dev/</strong></a> install the latest version of the next-auth. They are basically the same but <a href="https://next-auth.js.org/">https://next-auth.js.org/</a> is for Legacy code/ page router.</p><p>P.S: most of the tutorials I found were of the later and were serving me no purpose.</p><h3>NextJs Setup:</h3><p>The /login route:</p><pre>/app/login/page.tsx<br><br>import { useState, FormEvent } from &#39;react&#39;;<br><br>const LoginPage = () =&gt; {<br>  const [email, setEmail] = useState&lt;string&gt;(&#39;&#39;);<br>  const [password, setPassword] = useState&lt;string&gt;(&#39;&#39;);<br><br>  const handleSubmit = (e: FormEvent) =&gt; {<br>    e.preventDefault();<br><br>    if (!email || !password) {<br>      // handle error yourself! You Noob :) :)<br>      return;<br>    }<br>  };<br><br>  return (<br>      &lt;form onSubmit={handleSubmit}&gt;<br>        &lt;div&gt;<br>          &lt;label htmlFor=&quot;email&quot;&gt;Email&lt;/label&gt;<br>          &lt;input<br>            type=&quot;email&quot;<br>            id=&quot;email&quot;<br>            value={email}<br>            onChange={(e) =&gt; setEmail(e.target.value)}<br>          /&gt;<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>          &lt;label htmlFor=&quot;password&quot;&gt;Password&lt;/label&gt;<br>          &lt;input<br>            type=&quot;password&quot;<br>            id=&quot;password&quot;<br>            value={password}<br>            onChange={(e) =&gt; setPassword(e.target.value)}<br>          /&gt;<br>        &lt;/div&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Login&lt;/button&gt;<br>      &lt;/form&gt;<br>  );<br>};<br><br><br>export default LoginPage;</pre><p>/ is prtocted route which only signed in users can have access to:</p><pre>/app/page.tsx <br><br>export default function Dashboard() {<br>  return (<br>    &lt;div&gt;this is a custom dashboard that is project&lt;/div&gt;<br>  )<br>}</pre><h3>Installing Next-Auth/Auth-js:</h3><p>Now lets start serving the main dish. Install Auth-js using the command:</p><pre>npm install next-auth@beta</pre><p>Yes! Its a beta version that is most likely be stable by the time you were reading it. Somethings might change with the stable version I’ll try to update the blog if that happens and and IF i would still be using next-auth 😝 .</p><h3>Environment Variabales:</h3><p>Installed auth-js ?? Good! Now it wont work out of the box and need some necessary environment variables.</p><p>Well, at minimum you just need one env in you .env.local file</p><pre>AUTH_SECRET=secret_random_string</pre><p><strong>NOTE:</strong></p><p>The variable must be the same names, Both this one and ones that will come later. Its written in their docs. If you want to provide different variable names then you would need to mention that in the Authjs Configuration file.</p><p>Anyways, the above variable can be any random string, a random hex string like you use for secrets in JWT authentication. It serves the same purpose too. This secret is used to encode and decode the JWTs that are created by Auth-js.</p><p>You can run</p><pre>npx auth secret</pre><p>to genreate the secret or use any method you might like. What do you mean? You dont know Openssl? Noob!!!</p><h3>Auth-js Configuration:</h3><p>Now comes the juicy part where the hell begins ( atleast mine began)!!!</p><p>All you are left now is to configure the Auth-js application **According to the docs** and voila, you are done with the auth. No, not quite its not as simple as it seems. But dont worry princess, You Knight has come to save you!.</p><p>Create a file /auth.ts file at the root really doesn’t matter where you create it just DO IT and import and export the following:</p><pre>/auth.ts<br><br>import NextAuth from &quot;next-auth&quot;;<br><br>export const { handlers, signIn, signOut, auth } = NextAuth({<br>  // here goes the configuration<br>})</pre><p>You might be wondering what are these exports!!!!</p><p>The <strong>signIn, SignOut</strong> are functions/ methods that which are as you guessed it used to sign in and log out of the application, given some parameters which you will see later.</p><p><strong>auth</strong> here is a method that gives you the session object containing user information and <strong>handlers…. </strong>I dont know too!!! LOL!</p><p>now lets start the main configuration:</p><pre>/auth.ts<br><br>import { sql } from &quot;@vercel/postgres&quot;;<br>import Credentials from &quot;next-auth/providers/credentials&quot;<br>import bcrypt from &quot;bcryptjs&quot;<br><br>export const { handlers, signIn, signOut, auth } = NextAuth({<br>  session: {<br>    strategy: &quot;jwt&quot; <br>  },<br>  providers: [<br>    credentials({<br>      credentials: {<br>        email: {},<br>        password: {}<br>        // username: { label: &quot;Username&quot; },<br>        // password: { label: &quot;Password&quot;, type: &quot;password&quot; }<br><br>        // this define the properties like label, type etc. if you<br>        // dont want to make a custom login page yourself and instead use<br>        // use the one provided by the auth-js one<br>      <br>      },<br>      async authorize(credentials) {<br>        let customUser = await sql&lt;User&gt;<br>          `SELECT * FROM users WHERE email = ${credentials.email as email}`<br>        <br>        const matchPassword = await bcrypt.compare(<br>          credentials.password as string, customUser.rows[0].password<br>        )<br>        if (!matchPassword) throw new Error(&quot;Failed to Login User&quot;)<br>        return customUser.rows[0]<br>      }<br>    })<br>  ],<br>  pages: {<br>    signIn: &quot;/login&quot;,<br>    signOut: &quot;/login&quot;,<br>    error: &quot;/error&quot;<br>  },<br>})</pre><p>Woah!!! Woah!! Woah!! slow down! WTH happended here? Let me explain princess:</p><p><strong>1-</strong> First we need to define our auth strategy which we will be using. There are two Strategies that i read: <strong>jwt</strong> and <strong>database</strong>.</p><p><strong>JWT: </strong>For creating sessions using JWT that are sent in Set-Cookie Headers.</p><p><strong>Database:</strong> For creating and storing the sessions in the database. If you are using the database strategy you need to define an adapter in the configuration but then i’ll would have to leave you alone in the wild as I have only personally tried it to some extent and dont know that strategy well. I am weak!!! Thorfin you must become a true warrier!!</p><p>You can read more about each session strategy here: <a href="https://authjs.dev/concepts/session-strategies"><strong>https://authjs.dev/concepts/session-strategies</strong></a></p><p><strong>NOTE: </strong>JWT strategy is used by default. but its still better to mention it when using async functions in the providers. It was giving me errors when i did now specify the strategy type and was doing database calls in the authorize function.</p><p><strong>2- Providers: </strong>The provideres is an array of function where you provide the different authentication method that would be in you application like OAuth providers e.g Google, Github (which will come later) or you own manual auth mechanism which goes by the name <strong>credentials</strong> imported from “next-auth/providers/credentials”.</p><p><strong>3- Credentials:</strong> The credentials provider that take some options where you define the fields that will be provided.</p><p><strong>NOTE: </strong>I am leaving the fields empty for email, password as i am using the custom login page and the input validation is handled at the frontend. So I am just consuming the values. If you dont want to handle that, you need to provide the options as in the commented lines above and then handle the inputs validation on the server side. Auth js will create and provde a the built-in login page which is really not that good for production cases!!!</p><p><strong>4- Authorize: </strong>The authorize method will be where you can define the custom login for handling the inputs like a database query to find the user. Do whateber you want there. You <strong>MUST</strong> return the user object from the authorize method. This user object will be the one that will stored in the JWT session and will be accessible to you in the application.</p><p><strong>5- Pages:</strong> At last comes the pages. This is where you define the custom pages which you will use for Authentication. Make sure the pages are there. Otherwise if auth js default auth pages will be used for authentication with the given providers.</p><p>Whewwwww!!!! That covers a major portion of the authjs, at least to get you started.</p><h3>OAuth Providers:</h3><p>Using OAuth with auth-js is pretty straightward I can give you that. Like for example with Google, you need two things</p><p>1- Google Client Id,</p><p>2- Google Client Secret</p><p>which are present in the google cloud developer console.</p><p>What?? You want me to tell you how to get those and you dont now how to implement OAuth without 3rd party libraries? Seriously? Like seriously?</p><p>Dont mind! Just youtube it its very easy.</p><p>Now add these two variables in the .env.local file for the google client id and secret</p><pre>.env.local<br><br>AUTH_SECRET=&quot;secret_random_string&quot;<br>AUTH_GOOGLE_ID=&quot;google_client_id&quot;<br>AUTH_GOOGLE_SECRET=&quot;google_client_secret&quot;</pre><p>If you dont keep the variable with the same name in the .env file you will need to mention them youself in the configuration file. Now you just need to import Google provider from “next-auth/providers/google” and add it in the config file:</p><pre>/auth.ts<br><br>import Google from &#39;next-auth/providers/google&#39;<br>// rest imports<br><br>export const { handlers, signIn, signOut, auth } = NextAuth({<br>  session: {<br>    strategy: &quot;jwt&quot; <br>  },<br>  providers: [<br>    Google,<br><br>   // Google({<br>   //   clientId : process.env.CLIENT_ID,<br>   //   clientSecret: process.env.CLIENT_SECRET<br>   // }),<br><br>  // for custom client id and secret names<br><br>    credentials({<br>      credentials: {<br>        //rest of code<br>      },<br>      async authorize(credentials) {<br>        // rest of code<br>      }<br>    })<br>  ],<br>  pages: {<br>   // rest of code<br>  },<br>})</pre><p>Now you are set up. Lets add 2 more lines of code and get things started for real:</p><p>Create a <strong>/app/api/[…next-auth]/route.ts</strong> file</p><pre>import { handlers } from &quot;/auth&quot;<br>export const { GET, POST } = handlers</pre><p>Yes, its the same handler object that we exported from out auth config file.</p><p>The GET and POST methods are used internally by next-auth.</p><h3><strong>Update Login Page:</strong></h3><p>Lets update the login page and connect it to authjs:</p><pre>/app/login/page.tsx<br><br>import { signIn } from &quot;/auth&quot;<br>// rest imports<br><br><br>const LoginPage = () =&gt; {<br>  const [email, setEmail] = useState&lt;string&gt;(&#39;&#39;);<br>  const [password, setPassword] = useState&lt;string&gt;(&#39;&#39;);<br><br>  const handleSubmit = async (e: FormEvent) =&gt; {<br>    e.preventDefault();<br><br>    if (!email || !password) {<br>      // handle error yourself! You Noob :) :)<br>      return;<br>    }<br>     await signIn(&quot;credentials&quot;, { email, password, role, redirectTo: &quot;/&quot; })<br>  };<br>  <br>  const handleGoogleLogin = async () =&gt;{<br>    await signIn(&quot;google&quot;, { redirectTo : &quot;/&quot; })<br>  }<br>  return (<br>    &lt;&gt;<br>      &lt;form onSubmit={handleSubmit}&gt;<br>        // rest of form<br>      &lt;/form&gt;<br>      &lt;button onClick={handleGoogleLogin}&gt;Login with Google &lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default LoginPage;</pre><p>With this our Login page is now ready.Hers what I have done:</p><p>I imported the signIn function form the auth config. This function takes two parameters.</p><p><strong>1- </strong>Method of authentication like for OAuth with Google, you give “google” and for manual authentication you give “credentials”.</p><p><strong>2-</strong> Options where you can provide custom data incase of authentication with “credentials” like, emial, password, role etc.</p><p><strong>3- </strong>The <strong>redirectTo</strong> option where you define the path for the user to naviagate to on successfull authentication. Next-auth handles it internally.</p><p><strong>NOTE:</strong> You <strong>must not</strong> wrap it in the try-catch block as next auth uses next js router api internally which does not work when inside the try-catch block. Another option is to not give any redirect path, await it and then handler the routing based on the result yourself.</p><h3>Middleware:</h3><p>Lets also configure the middleware for our app. The Auth js gives us a nice utility to easily protect the routes.</p><p>Create a middleware.ts file in the root of you project</p><pre>import { auth } from &quot;/auth&quot;<br><br>export default auth((req) =&gt; {<br>  if (!req.auth &amp;&amp; req.nextUrl.pathname === &quot;/&quot;) <br>    return Response.redirect(<br>      new URL(&quot;/login&quot;, req.nextUrl.origin)<br>    )<br>  })<br>  <br>// exclude the paths you want middleware to not run for<br>export const config = {<br>  matcher: [&quot;/((?!api|_next/static|_next/image|favicon.ico).*)&quot;],<br>}<br><br></pre><p>Whats this middleware doing you would ask. Well!!! 🤔</p><p>You are taking the auth function exported from the configuration file and giving it a callback which is a req object containing the auth status i.e either <strong>Null</strong> or object with <strong>user. </strong>The middleware runs for every route in your application and we are getting the path the user is currently at, checking if the usre is signed in to be able to access that path and then we are redirecting basedon its auth status.</p><p>Now you may say I understand but what is the config variable doing here. Its excluding the paths the middleware should not run for. Here its excluding the middleware to run for static images and favicons.</p><p>Now you basic auth flow is ready.</p><h3><strong>Accessing Session:</strong></h3><p>To access the session in your application you must wrap the application in the session provider i.e in the root layout if you want it to be available in the whole application:</p><pre>/app/layout.tsx<br><br>import { SessionProvider } from &quot;next-auth/react&quot;<br>import { auth } from &quot;/auth&quot;;<br>export default async function RootLayout({<br>  children,<br>}: Readonly&lt;{<br>  children: React.ReactNode;<br>}&gt;) {<br>  const session = await auth()<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body className={inter.className}&gt;<br>        &lt;SessionProvider session={session}&gt;<br>          {children}<br>        &lt;/SessionProvider&gt;<br>      &lt;/body&gt;<br>    &lt;/html &gt;<br>  );<br>}</pre><p>Now you can access it in the whole application. In next js server components it is done by invoking the</p><pre>import { auth } from &quot;/auth&quot;;<br><br>const session = await auth()</pre><p>While in the client components you can use:</p><pre>import { useSession } from &quot;next-auth/react&quot;<br> <br>const session = useSession()</pre><p>You are evolving now to a next-auth pro !!!</p><p><a href="https://medium.com/@mrsaadmasood1/exploring-the-depths-of-next-auth-hell-part-2-07710a04985b">Exploring the Depths of Next-Auth Hell! !! Part — 2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17e9b86399ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>