Bird
Raised Fist0
NextJSframework~20 mins

NextAuth.js (Auth.js) setup in NextJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
NextAuth.js Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this NextAuth.js sign-in callback?

Consider this NextAuth.js configuration snippet. What will be the value of token.userRole after a successful sign-in?

NextJS
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";

export default NextAuth({
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        username: { label: "Username", type: "text" },
        password: { label: "Password", type: "password" }
      },
      async authorize(credentials) {
        if (credentials.username === "admin" && credentials.password === "pass") {
          return { id: 1, name: "Admin User", role: "admin" };
        }
        return null;
      }
    })
  ],
  callbacks: {
    async jwt({ token, user }) {
      if (user) {
        token.userRole = user.role;
      }
      return token;
    }
  }
});
Aundefined
B"admin"
C"user"
Dnull
Attempts:
2 left
💡 Hint

Look at the authorize function and what it returns for the user object.

📝 Syntax
intermediate
2:00remaining
Which option correctly configures NextAuth.js to use Google provider?

Choose the correct NextAuth.js provider configuration for Google OAuth.

A
import GoogleProvider from "next-auth/providers/google";

providers: [
  GoogleProvider({
    clientId: process.env.GOOGLE_ID,
    clientSecret: process.env.GOOGLE_SECRET
  })
]
B
import GoogleAuth from "next-auth/providers/google";

providers: [
  GoogleAuth({
    id: process.env.GOOGLE_ID,
    secret: process.env.GOOGLE_SECRET
  })
]
C
import GoogleProvider from "next-auth/providers/google";

providers: [
  GoogleProvider({
    client_id: process.env.GOOGLE_ID,
    client_secret: process.env.GOOGLE_SECRET
  })
]
D
import GoogleProvider from "next-auth/providers/google";

providers: [
  GoogleProvider({
    clientId: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET
  })
]
Attempts:
2 left
💡 Hint

Check the exact property names required by NextAuth.js Google provider.

🔧 Debug
advanced
2:00remaining
Why does this NextAuth.js session callback cause an error?

Examine this session callback code. What error will it cause when running?

NextJS
callbacks: {
  async session({ session, token }) {
    session.user.id = token.sub;
    session.user.role = token.userRole;
    return session;
  }
}
AReferenceError: token is not defined
BTypeError: Cannot set properties of undefined (setting 'id')
CSyntaxError: Unexpected token
DNo error, session updated correctly
Attempts:
2 left
💡 Hint

The session.user object is always available and mutable in the session callback.

state_output
advanced
2:00remaining
What is the value of session.user.email after sign-in with this NextAuth.js config?

Given this NextAuth.js configuration, what will session.user.email be after a user signs in?

NextJS
import NextAuth from "next-auth";
import GitHubProvider from "next-auth/providers/github";

export default NextAuth({
  providers: [
    GitHubProvider({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET
    })
  ],
  callbacks: {
    async session({ session, token }) {
      session.user.email = token.email ?? "no-email@example.com";
      return session;
    },
    async jwt({ token, user, account }) {
      if (user) {
        token.email = user.email;
      }
      return token;
    }
  }
});
AThe user's GitHub email address
B"no-email@example.com"
Cundefined
Dnull
Attempts:
2 left
💡 Hint

Look at how the jwt callback sets token.email and how session callback uses it.

🧠 Conceptual
expert
2:00remaining
Which statement about NextAuth.js adapter usage is correct?

NextAuth.js supports adapters to connect to databases. Which of these statements is true about using an adapter?

AAdapters are required for all providers to store user sessions in a database.
BAdapters automatically encrypt user passwords before storing them in the database.
CAdapters allow NextAuth.js to persist user accounts and sessions but are optional for JWT-based sessions.
DAdapters replace the need for callbacks like jwt and session in NextAuth.js.
Attempts:
2 left
💡 Hint

Think about when adapters are necessary and how sessions can be managed.

Practice

(1/5)
1. What is the main purpose of NextAuth.js in a Next.js application?
easy
A. To optimize images automatically
B. To manage database connections
C. To style components with CSS
D. To handle user authentication and login flows easily

Solution

  1. Step 1: Understand NextAuth.js role

    NextAuth.js is a library designed to simplify adding authentication to Next.js apps.
  2. Step 2: Identify main functionality

    It manages login flows, sessions, and providers for user authentication.
  3. Final Answer:

    To handle user authentication and login flows easily -> Option D
  4. Quick Check:

    NextAuth.js = Authentication helper [OK]
Hint: NextAuth.js is all about login and user sessions [OK]
Common Mistakes:
  • Confusing NextAuth.js with styling or database tools
  • Thinking it manages images or CSS
  • Assuming it handles API routing unrelated to auth
2. Which file path is the correct place to create the NextAuth.js API route in a Next.js app?
easy
A. /pages/api/auth/[...nextauth].js
B. /pages/auth/nextauth.js
C. /api/auth.js
D. /pages/api/nextauth.js

Solution

  1. Step 1: Recall NextAuth.js API route convention

    NextAuth.js requires a catch-all API route named [...nextauth].js inside /pages/api/auth/.
  2. Step 2: Match the correct path

    Only /pages/api/auth/[...nextauth].js matches the required path: /pages/api/auth/[...nextauth].js.
  3. Final Answer:

    /pages/api/auth/[...nextauth].js -> Option A
  4. Quick Check:

    API route = /api/auth/[...nextauth] [OK]
Hint: NextAuth.js uses catch-all API route [...nextauth].js [OK]
Common Mistakes:
  • Placing the file outside /api/auth/
  • Using a non-catch-all filename
  • Missing the brackets in filename
3. Given this NextAuth.js configuration snippet, what will be the value of session.user.name after a successful login?
import NextAuth from "next-auth";
import GithubProvider from "next-auth/providers/github";

export default NextAuth({
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET
    })
  ],
  callbacks: {
    async session({ session, user }) {
      session.user.name = "CustomName";
      return session;
    }
  }
});
medium
A. The GitHub username
B. "CustomName"
C. Undefined
D. The user's email

Solution

  1. Step 1: Understand the session callback

    The session callback modifies the session object before it is returned to the client.
  2. Step 2: Check the modification

    It sets session.user.name explicitly to "CustomName" regardless of original data.
  3. Final Answer:

    "CustomName" -> Option B
  4. Quick Check:

    Session callback overrides user.name = "CustomName" [OK]
Hint: Session callback can override user data before sending [OK]
Common Mistakes:
  • Assuming user.name stays as GitHub username
  • Thinking session.user.name is undefined by default
  • Confusing email with name property
4. You wrote this NextAuth.js provider config but get an error: TypeError: GithubProvider is not a function. What is the likely cause?
import { GithubProvider } from "next-auth/providers/github";

export default NextAuth({
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET
    })
  ]
});
medium
A. Provider config must be inside callbacks
B. Missing environment variables
C. Incorrect import syntax; should use default import without braces
D. NextAuth must be imported from 'next-auth/client'

Solution

  1. Step 1: Check import style for GithubProvider

    GithubProvider is the default export, so it should be imported without braces.
  2. Step 2: Identify correct import syntax

    Use import GithubProvider from "next-auth/providers/github"; instead of curly braces.
  3. Final Answer:

    Incorrect import syntax; should use default import without braces -> Option C
  4. Quick Check:

    Default export = no braces in import [OK]
Hint: Default exports import without braces {} [OK]
Common Mistakes:
  • Using named import syntax for default export
  • Assuming environment variables cause this error
  • Placing provider config inside callbacks
5. You want to add Google and GitHub login providers in NextAuth.js with environment variables. Which is the correct way to configure both providers in /pages/api/auth/[...nextauth].js?
hard
A. import GoogleProvider from "next-auth/providers/google"; import GithubProvider from "next-auth/providers/github"; export default NextAuth({ providers: [ GoogleProvider({ clientId: process.env.GOOGLE_ID, clientSecret: process.env.GOOGLE_SECRET }), GithubProvider({ clientId: process.env.GITHUB_ID, clientSecret: process.env.GITHUB_SECRET }) ] });
B. import { GoogleProvider, GithubProvider } from "next-auth/providers"; export default NextAuth({ providers: [ GoogleProvider(process.env.GOOGLE_ID, process.env.GOOGLE_SECRET), GithubProvider(process.env.GITHUB_ID, process.env.GITHUB_SECRET) ] });
C. import GoogleProvider from "next-auth/providers/google"; import GithubProvider from "next-auth/providers/github"; export default NextAuth({ providers: { google: GoogleProvider, github: GithubProvider } });
D. import GoogleProvider from "next-auth/providers/google"; import GithubProvider from "next-auth/providers/github"; export default NextAuth({ providers: [ GoogleProvider, GithubProvider ] });

Solution

  1. Step 1: Import providers correctly

    Each provider is a default export from its own module and must be imported separately.
  2. Step 2: Configure providers as array with clientId and clientSecret

    Providers must be called as functions with an object containing clientId and clientSecret from environment variables.
  3. Step 3: Validate options

    import GoogleProvider from "next-auth/providers/google"; import GithubProvider from "next-auth/providers/github"; export default NextAuth({ providers: [ GoogleProvider({ clientId: process.env.GOOGLE_ID, clientSecret: process.env.GOOGLE_SECRET }), GithubProvider({ clientId: process.env.GITHUB_ID, clientSecret: process.env.GITHUB_SECRET }) ] }); correctly imports and configures both providers in an array with proper keys.
  4. Final Answer:

    Correct import and provider function calls with env variables -> Option A
  5. Quick Check:

    Providers array with clientId/clientSecret = import GoogleProvider from "next-auth/providers/google"; import GithubProvider from "next-auth/providers/github"; export default NextAuth({ providers: [ GoogleProvider({ clientId: process.env.GOOGLE_ID, clientSecret: process.env.GOOGLE_SECRET }), GithubProvider({ clientId: process.env.GITHUB_ID, clientSecret: process.env.GITHUB_SECRET }) ] }); [OK]
Hint: Providers need clientId and clientSecret in array [OK]
Common Mistakes:
  • Importing providers as named imports from a single module
  • Passing env vars directly without object keys
  • Using object instead of array for providers