0
0
NextJSframework~10 mins

NextAuth.js (Auth.js) setup in NextJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - NextAuth.js (Auth.js) setup
Import NextAuth and Providers
Create authOptions object
Configure providers (e.g., GitHub)
Export NextAuth with authOptions
NextAuth API route handles requests
User signs in/out, session managed
Protected pages check session
Access granted or denied
This flow shows how NextAuth.js is set up by importing, configuring providers, exporting the handler, and managing user sessions.
Execution Sample
NextJS
import NextAuth from "next-auth";
import GitHubProvider from "next-auth/providers/github";

export const authOptions = {
  providers: [GitHubProvider({ clientId: process.env.GITHUB_ID, clientSecret: process.env.GITHUB_SECRET })],
};

export default NextAuth(authOptions);
This code sets up NextAuth with GitHub as an authentication provider.
Execution Table
StepActionEvaluationResult
1Import NextAuth and GitHubProviderModules importedReady to configure auth
2Create authOptions objectAdd GitHub provider with env varsProviders configured
3Export NextAuth handler with authOptionsNextAuth function called with configAPI route ready to handle auth
4User visits sign-in pageNextAuth shows GitHub sign-in buttonUser can click to sign in
5User clicks sign-inRedirect to GitHub OAuthUser authenticates on GitHub
6GitHub redirects back with tokenNextAuth verifies tokenSession created
7User accesses protected pageSession checkedAccess granted if signed in
8User signs outSession clearedUser logged out
9End of flowNo more actionsAuthentication cycle complete
💡 Authentication flow ends when user signs out or session expires.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 6Final
authOptionsundefined{"providers":["GitHubProvider config"]}{"providers":["GitHubProvider config"]}{"providers":["GitHubProvider config"]}{"providers":["GitHubProvider config"]}
sessionnullnullnull{"user":{...}, "expires":"..."}null or session depending on sign out
Key Moments - 3 Insights
Why do we use environment variables for clientId and clientSecret?
Environment variables keep sensitive info like clientId and clientSecret safe and out of the codebase, as shown in Step 2 of the execution_table.
What happens if the user is not signed in and tries to access a protected page?
NextAuth checks the session (Step 7). If no session exists, access is denied or redirected to sign-in, ensuring security.
How does NextAuth handle the OAuth redirect from GitHub?
After user authenticates on GitHub (Step 5), GitHub redirects back with a token (Step 6), which NextAuth verifies to create a session.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the state of authOptions after Step 3?
ANull
BAn object with GitHub provider configured
CUndefined
DA string with client secrets
💡 Hint
Check the 'After Step 3' column in variable_tracker for authOptions.
At which step does NextAuth create a user session?
AStep 4
BStep 7
CStep 6
DStep 8
💡 Hint
Look at the execution_table row describing token verification and session creation.
If the environment variables for GitHub clientId and clientSecret are missing, what happens at Step 2?
ANextAuth throws an error or fails to authenticate
BProviders configured successfully
CUser is signed in automatically
DSession is created without provider
💡 Hint
Step 2 shows provider configuration depends on environment variables.
Concept Snapshot
NextAuth.js setup:
1. Import NextAuth and providers.
2. Create authOptions with providers using env vars.
3. Export NextAuth handler with authOptions.
4. NextAuth manages sign-in, session, and sign-out.
5. Protect pages by checking session.
Use environment variables for secrets.
Full Transcript
NextAuth.js setup in Next.js starts by importing NextAuth and authentication providers like GitHubProvider. Then, you create an authOptions object that configures providers using environment variables for clientId and clientSecret to keep secrets safe. Next, you export the NextAuth handler with this configuration. When a user visits the sign-in page, NextAuth shows sign-in options. Clicking sign-in redirects the user to GitHub for authentication. After successful login, GitHub redirects back with a token, which NextAuth verifies to create a session. Protected pages check this session to allow or deny access. Signing out clears the session. This flow ensures secure and easy authentication in Next.js apps.