DEV Community

Hein Htoo
Hein Htoo

Posted on

Integrating GitHub Authentication with NextAuth.js: A Step-by-Step Guide

I am going to share my experience about integrating GitHub authentication with NextAuth.js.

Previous Post: Implementing auth.js v5 with Prisma and Supabase in Next.js

My GitHub Repo for next-auth Repo

Step 1: Create an OAuth App on GitHub

Go to this link and create new OAuth App.

OAuth app configure

You can add home page URL as http://localhost:3000

Note. GitHub only provides single Authorization callback URL so we need to create two OAuth app, one for localhost and one for production.

Authorization callback URL should point to Next.js API routes where NextAuth.js handles authentication

http://localhost:3000/api/auth/callback/github
Enter fullscreen mode Exit fullscreen mode

Copy the Client ID and Client Secret for environment variables.


![Secrets](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cpu1lim6jscv4748c9oo.png)
Enter fullscreen mode Exit fullscreen mode

Step 2: Adding Environment variables

Create environment variables in .env.local by adding the following environment variables

AUTH_GITHUB_ID=your-github-client-id
AUTH_GITHUB_SECRET=your-github-client-secret
Enter fullscreen mode Exit fullscreen mode

Step 3: Configure NextAuth.js for GitHub

In previous post, we added auth.js like this

// auth.ts
import NextAuth from "next-auth"
import { PrismaAdapter } from "@auth/prisma-adapter"
import { prisma } from "@/prisma"
export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [],
})
Enter fullscreen mode Exit fullscreen mode

Now we are going to add GitHub provider

// auth.ts
import NextAuth from "next-auth"
import { PrismaAdapter } from "@auth/prisma-adapter"
import { prisma } from "@/prisma"
import GitHubProvider from "next-auth/providers/github";

export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [
    GitHubProvider({
      clientId: process.env.AUTH_GITHUB_ID ?? "",
      clientSecret: process.env.AUTH_GITHUB_SECRET ?? "",
    })
  ],
})
Enter fullscreen mode Exit fullscreen mode

That's all the part of setting up.

Step 4: Login with GitHub

You can either login from http://localhost:3000/api/auth/signin or you can create your custom sign-in page.

If you want to customize the sign-in experience, you can create a custom sign-in page.

First, create a file at app/sign-in/page.tsx

import { signIn } from 'next-auth/react'

export default function SignIn() {
  return (
    <div>
      <h1>Sign In</h1>
      <button onClick={() => signIn('github')}>Sign in with GitHub</button>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

And that's all for setting up with GitHub integration in Auth.js

Happy Coding ^_^

Top comments (0)