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.
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
- Demo and code
- Install the nextjs
- Install next-auth in the project
- Setup the next-auth API
- Setup the SessionProvider
- How to use the useSession hook
- 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 NextAuthexport 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.
- secret
- NEXTAUTH_SECRET
- NEXTAUTH_URL
- GITHUB_ID
- 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
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.
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.
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.
- OAuth Apps ( Easy )
- 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.
- Create any name for the application
- Enter Home page Url
- 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.
- 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
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
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.
- Enter the name
- Add Home URL
- The callback URL is the same for everyone. If you create any custom router, then it changes. But by default, it is the same.
- Select your Repository permissions, Organization permissions, and User permissions. In my case, I’m only selecting User permissions after using Profile Information.
- 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
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.