0PricingLogin
React Academy · Lesson

Credentials Provider & Custom Login

Authenticate users against a database with a credentials provider and a custom login form.

When to Use Credentials Provider

Use the Credentials provider when you authenticate against your own database (email + password) rather than an OAuth provider. It requires careful handling of password hashing and security.

Defining the Credentials Provider

Add Credentials to the providers array. The authorize function receives the submitted credentials and returns a user object or null.

import Credentials from 'next-auth/providers/credentials';
import bcrypt from 'bcryptjs';

export const { handlers, auth } = NextAuth({
  providers: [
    Credentials({
      name: 'Credentials',
      credentials: {
        email: { label: 'Email', type: 'email' },
        password: { label: 'Password', type: 'password' },
      },
      async authorize(credentials) {
        const user = await db.user.findUnique({ where: { email: credentials.email as string } });
        if (!user) return null;
        const valid = await bcrypt.compare(credentials.password as string, user.passwordHash);
        if (!valid) return null;
        return { id: user.id, name: user.name, email: user.email };
      },
    }),
  ],
});

All lessons in this course

  1. Setting Up Auth.js in Next.js App Router
  2. Session Management & useSession Hook
  3. Credentials Provider & Custom Login
  4. Middleware-Based Route Protection
← Back to React Academy