DEV Community

Cover image for Authentication for apps -> How can utilize next-auth for authentication?
Vijendra-Tech
Vijendra-Tech

Posted on

Authentication for apps -> How can utilize next-auth for authentication?

Log in using GitHub: https://poc-next-auth.netlify.app/

Authentication and Authorization is an integral processes to keep the application secure. Without proper authentication measures in place, unauthorized users could gain access to sensitive information or perform actions that could harm the application or its users.

Authentication can be done using the User's Google account or GitHub Apple etc.

How can we implement such an authentication process?
There are several ways to implement but today we can check how we can utilize the next-auth library for GitHub authentication and it can be extended to any other authentication (google, apple, Reddit etc).

Steps for GitHub authentication :
1.First, get Github Client ID and secret Id by creating a new OAuth app from (Setting ->Developer setting -> New OAuth app-> provide URL and callback URLs) then generate the client Id.

Image description

2.Keep the Client ID and secret ID in the env file (.env file)

Authentication (NextAuth.js)

NEXTAUTH_URL=localhost:3000

NEXTAUTH_SECRET=

GITHUB_CLIENT_ID=

GITHUB_CLIENT_SECRET=

GITHUB_ACCESS_TOKEN=
3.

 // Keep  this Option in any folder(lib->auth.js)
   import GithubProvider from "next-auth/providers/github"

   export const authOptions = {
     // Configure one or more authentication providers
     providers: [
       GithubProvider({
         clientId: process.env.NEXT_GITHUB_CLIENT_ID,
         clientSecret: process.env.NEXT_GITHUB_CLIENT_SECRET,
       }),
       // ...add more providers here
     ],
     secret:process.env.NEXT_JWT_SECRET
   }
Enter fullscreen mode Exit fullscreen mode

4.create a folder under (src->pages->auth->[...nextauth].js file and add these lines of codes.

import NextAuth from "next-auth"

import { authOptions } from "@/lib/auth"

// @see ./lib/auth
export default NextAuth(authOptions)
Enter fullscreen mode Exit fullscreen mode

5.Then import sign/signout/ from next-auth/react and call on the login and signout button.

 import { signIn } from "next-auth/react"
   <button
             type="button"
              className="bg-white border border-slate-200 hover:bg-white-100 dark:border-slate-700 dark:text-slate-100 p-10 rounded"
              onClick={() => {
                signIn();
              }}
            >
              Login With GitHub
            </button>

Enter fullscreen mode Exit fullscreen mode

With all these changes we will be able to GitHub log in.

DEMO URL: https://poc-next-auth.netlify.app/

CODE: https://github.com/Vijendra-Tech/poc_next_auth

Happy Coding :)

Top comments (0)