0
0
NextjsHow-ToBeginner · 4 min read

How to Use Credentials Provider with NextAuth.js in Next.js

To use the CredentialsProvider in next-auth with Next.js, import it from next-auth/providers/credentials and add it to the providers array in your [...nextauth].js API route. Implement the authorize function to verify user credentials and return a user object on success.
📐

Syntax

The CredentialsProvider is imported from next-auth/providers/credentials. It requires an authorize function where you check the user's credentials. If valid, return a user object; otherwise, return null to deny access.

You add this provider inside the providers array in the NextAuth configuration.

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

export default NextAuth({
  providers: [
    CredentialsProvider({
      name: "Credentials",
      credentials: {
        username: { label: "Username", type: "text" },
        password: { label: "Password", type: "password" }
      },
      async authorize(credentials) {
        // Validate credentials here
        if (credentials.username === "user" && credentials.password === "pass") {
          return { id: 1, name: "User" };
        }
        return null;
      }
    })
  ]
});
💻

Example

This example shows a complete Next.js API route using NextAuth with the Credentials Provider. It checks if the username is "user" and password is "pass" and returns a user object if valid. Otherwise, it denies access.

javascript
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", placeholder: "user" },
        password: { label: "Password", type: "password" }
      },
      async authorize(credentials) {
        const { username, password } = credentials;
        if (username === "user" && password === "pass") {
          return { id: 1, name: "User", email: "user@example.com" };
        }
        return null;
      }
    })
  ],
  session: {
    strategy: "jwt"
  },
  pages: {
    signIn: "/auth/signin"
  }
});
Output
When a user submits the sign-in form with username 'user' and password 'pass', they are authenticated and signed in; otherwise, sign-in fails.
⚠️

Common Pitfalls

  • Not returning null in authorize when credentials are invalid causes unexpected behavior.
  • Forgetting to handle the credentials object safely can cause errors if fields are missing.
  • Not setting up a sign-in page or handling errors can confuse users.
  • Using plain text passwords without hashing is insecure; always hash passwords in real apps.
javascript
/* Wrong: Missing null return on failed login */
async authorize(credentials) {
  if (credentials.username === "user" && credentials.password === "pass") {
    return { id: 1, name: "User" };
  }
  // Missing return null here
  return null;
}

/* Right: Return null explicitly */
async authorize(credentials) {
  if (credentials.username === "user" && credentials.password === "pass") {
    return { id: 1, name: "User" };
  }
  return null;
}
📊

Quick Reference

Use this quick guide when setting up Credentials Provider:

StepDescription
Import CredentialsProviderimport from 'next-auth/providers/credentials'
Add to providers arrayInclude CredentialsProvider in NextAuth config
Implement authorize()Check credentials and return user or null
Return user objectMust include at least an id property
Handle sign-in pageOptionally customize sign-in UI

Key Takeaways

Import and add CredentialsProvider to NextAuth providers array in your API route.
Implement the authorize function to verify credentials and return a user object or null.
Always return null on failed login to prevent errors.
Use secure password handling in real applications, not plain text.
Customize sign-in pages for better user experience.