Set up the next-auth library with github provider in nextjs
Set up the next-auth library with GitHub provider in nextjs.

How to set up the next-auth library for development and production in nextjs?

Set up the NextJS auth library with the GitHub provider. In this article, I solve those problems that beginner developers face at integration time.

Rajdeep Singh
Published in
6 min readJul 20, 2022

--

The article’s primary focus is on the setup of the next-auth library for development and production.

In this article, I set up the next-auth with the GitHub provider in nextjs. I will use Facebook, Twitter, and LinkedIn in the upcoming article to provide authorization.

The setup of the next auth is a copy-paste of code. I teach you all the processes step by step.

Steps

  1. Demo and code
  2. Install the nextjs
  3. Install next-auth in the project
  4. Setup the next-auth API
  5. Setup the SessionProvider
  6. How to use the useSession hook
  7. Environment setup for next-auth

Recommendation

The article is enormous. If you are a beginner developer, plz watch at least one tutorial on youtube and then follow this article.

Demo and code

You play with code using an online IDE or download it locally.

Check out the website demo https://next-auth-gamma.vercel.app/.

Install the nextjs

You install a new project with npm, yarn, and pnpm. The installation process is the same.

npx create-next-app my-apporyarn create next-apporpnpm create next-app

Otherwise, you can use my code as a temple with all configurations.

git clone https://github.com/officialrajdeepsingh/next-auth
cd next-auth
npm install && npm run dev

You can already create a project and add the next-auth to the existing project. Then feel free to skip this section.

Install next-auth in the project

Install the next-auth library in your nextjs project using npm, yarn, or pnpm.

npm install next-authoryarn add next-authorpnpm add next-auth

Setup the next-auth API

Firstly create pages/api/auth/[...nextauth].js file in the nextjs

// pages/api/auth/[...nextauth].jsimport NextAuth from "next-auth"import GitHubProvider from "next-auth/providers/github";
// add providers with NextAuth
export default NextAuth({ providers: [
GitHubProvider({

secret: process.env.SECRET,
clientId: process.env.GITHUB_ID, clientSecret: process.env.GITHUB_SECRET }) ]})

Setup the SessionProvider

In a new project, you replace the _app.js file code with the following code. If you have already set up the _app.js file, wrap the nextjs component with SessionProvider.

SessionProvider is a high-order component. It provides useSession hook support on the nextjs app.

// _api.js
import '../styles/globals.css'
import { SessionProvider } from "next-auth/react"export default function App({
Component, pageProps: { session, ...pageProps }, }) {
return (<SessionProvider session={session}><Component {...pageProps} /></SessionProvider>)}

How to use the useSession hook

With the help of useSession hook, we check the user authorization in nextjs.

import { useSession, signIn, signOut } from "next-auth/react"export default function Component() {
const { data: session } = useSession()

if (session) {

return (
<>
Signed in as {session.user.name} <br />
<button onClick={() => signOut()}>Sign out</button>
</>
)
}return (
<>
Not signed in <br />
<button onClick={() => signIn()}>Sign in</button>
</>
)
}

Environment setup for next-auth

You use GitHub authorization in your nextjs app. you need the following environment variable.

  1. secret
  2. NEXTAUTH_SECRET
  3. NEXTAUTH_URL
  4. GITHUB_ID
  5. GITHUB_SECRET

Require Environment variables for Local development

secret= v7COYqKpEdnCbd5aISAw9BxjupOLKYCgBVZ2kwusMNs=GITHUB_ID = Iv1****1bGITHUB_SECRET= a220c******************968NEXTAUTH_SECRET = v7COYqKpEdnCbd5aISAw9BxjupOLKYCgBVZ2kwusMNs=NEXTAUTH_URL= http://localhost:3000/

Require Environment variables for Local development

GITHUB_ID = Iv1****1bGITHUB_SECRET= a220c******************968NEXTAUTH_SECRET = v7COYqKpEdnCbd5aISAw9BxjupOLKYCgBVZ2kwusMNs=NEXTAUTH_URL= http://localhost:3000/

secret and NEXTAUTH_SECRET Environment

The secret and NEXTAUTH_SECRET are both the same. The secret and NEXTAUTH_SECRET is a strings with a bunch of random numbers and characters. Secret and NEXTAUTH_SECRET help to generate an encrypted token for your next app.

Note

The secret environment variable works only in local development, and the NEXTAUTH_SECRET environment variable is used for production.

How to generate a secret environment in the computer?

You generate a secret key with the help of a openssl command.

$ openssl rand -base64 32
How to generate a secret in next-auth library?
Generate a secret with the nextjs help of the OpenSSL command.

What happens when we do not provide a secret in the next-auth?

When you do not provide a secret in your next auth, you face a no-secret error or warning in the next auth.

without secret, you face a NO_SECRET error in next-auth.
without a secret, you face a NO_SECRET error in next-auth

NEXTAUTH_URL

The NEXTAUTH_URL is your canonical URL. in the simple meaning of your current website domain name with HTTP or HTTPS.

Example

// local development
NEXTAUTH_URL= http://localhost:3000/
or// production development
NEXTAUTH_URL= https://next-auth-gamma.vercel.app/

What happens when we do not provide a NEXTAUTH_URL in the next-auth?

When we do not pass or forget the NEXTAUTH_URL environment variable in nextjs. Then we face a NEXTAUTH_URL warning or error in the next-auth.

NEXTAUTH_URL warning or error in next-auth.
NEXTAUTH_URL warning or error in next-auth

GITHUB_ID and GITHUB_SECRET

Github provides the GITHUB_ID and GITHUB_SECRET. You get both values inside your GitHub setting

There are two ways to get GITHUB_ID and GITHUB_SECRET.

  1. OAuth Apps ( Easy )
  2. Github Apps

OAuth Apps

You go to the GitHub developer and create a new OAuth application.

Github -> settings -> developers -> OAuth Apps -> create a new OAuth app and file all the details.

  1. Create any name for the application
  2. Enter Home page Url
  3. Enter the Authorization callback URL. Same for everyone if you create a custom route in your next auth. Then it changes according to your logic.
  4. Click the Register application button.
Authorization callback URL for productionhttps://next-auth-gamma.vercel.app/api/auth/callback/githuborAuthorization callback URL for developmenthttps://http://localhost:3000/auth/callback/github
Create a new OAuth app on Github.
Create a new OAuth app on Github.

Copy your client Id and paste it into the GITHUB_ID section after clicking the Generate a new client secret button after you see Client secrets and store it in GITHUB_SECRET.

GITHUB_ID = Paste client IdGITHUB_SECRET= Paste Client secrets
create a client Id and client secret in github for next-auth
Create a client Id and client secret in GitHub for next-auth.

Github Apps

You go to the GitHub developer and create a new Github app.

Github -> settings -> developers -> Github Apps -> create New Github app and file all the details.

Create a Github App for next-auth
Create a Github App for next-auth.
  1. Enter the name
  2. Add Home URL
  3. The callback URL is the same for everyone. If you create any custom router, then it changes. But by default, it is the same.
  4. Select your Repository permissions, Organization permissions, and User permissions. In my case, I’m only selecting User permissions after using Profile Information.
  5. Click the create GitHub app button.
Authorization callback URL for productionhttps://next-auth-gamma.vercel.app/api/auth/callback/githuborAuthorization callback URL for developmenthttps://http://localhost:3000/auth/callback/github

On the next page, you Copy your client Id and paste it into the GITHUB_ID section, and after clicking the Generate a new client secret button after you see Client secrets and store them in GITHUB_SECRET.

GITHUB_ID = Paste client IdGITHUB_SECRET= Paste Client secrets
create a client Id and client secret in github for next-auth.
Create a client Id and client secret in Github for next-auth.

Now you start the dev server in nextjs.

Conclusion

Next-auth is an excellent library for nextjs to handle the authorization in-app. Now a day, there are a lot of providers who help to handle authorization in nextjs, for example, supabase.

The next auth is open source, and a prominent community member handles and maintains the code.

On the other hand, supabase and other providers are not free. They come with zero configuration.

First-time next-auth is so tricky for beginners. Suppose you know the basics of API. It is effortless to configure the next auth.

For me, the hard part is collecting the client ID and Client secrets for GitHub, Facebook, LinkedIn, Twitter, etc.

You can follow and read more articles on officialrajdeepsingh.dev and follow on Twitter and Linkedin.

Read More content on Nextjs. Sign up for a free newsletter and join the nextjs community on medium.

--

--

Rajdeep Singh

Follow me if you learn more about JavaScript | TypeScript | React.js | Next.js | Linux | NixOS | https://linktr.ee/officialrajdeepsingh