Email & Password

Sign in your users with an email and a password stored in your own database.

Overview

The credentials provider lets your users sign in with an email and a password. Light-Auth handles the endpoints, the CSRF protection and the session cookie, while you keep full control over your users: you write the functions that verify the credentials, register a user and reset a password, against your own database.

There is no redirection to a third party: the browser posts the credentials to Light-Auth, which creates the session right away.

The credentials provider can be used alone, or together with OAuth providers (Google, GitHub...) in the same application.

Create the credentials provider

Create the provider with createCredentialsProvider. Only verifyCredentials is required, the other functions enable the registration and the password reset endpoints:

./lib/credentials-provider.ts
import { createCredentialsProvider } from "@light-auth/core";
import { randomBytes } from "node:crypto";
import bcrypt from "bcrypt";
import { db } from "./db";

export const credentialsProvider = createCredentialsProvider({
  // the credentials endpoints look for the provider named "credentials"
  providerName: "credentials",

  // required: returns the user claims, or null when the credentials are invalid (401)
  verifyCredentials: async (email, password) => {
    const user = await db.user.findUnique({ where: { email } });
    if (!user || !(await bcrypt.compare(password, user.passwordHash))) return null;

    return { sub: user.id, email: user.email, name: user.name };
  },

  // optional: enables the registration endpoint, returns null when the user already exists (409)
  registerUser: async (email, password, additionalData) => {
    if (await db.user.findUnique({ where: { email } })) return null;

    const passwordHash = await bcrypt.hash(password, 12);
    const user = await db.user.create({ data: { email, passwordHash, name: additionalData?.name ?? email } });

    return { sub: user.id, email: user.email, name: user.name };
  },

  // optional: enables the password reset request endpoint
  requestPasswordReset: async (email) => {
    const user = await db.user.findUnique({ where: { email } });
    if (!user) return false; // the response is the same, it never reveals if the email exists

    const token = randomBytes(32).toString("base64url");
    await db.passwordReset.create({ data: { token, userId: user.id, expiresAt: new Date(Date.now() + 60 * 60 * 1000) } });
    await sendPasswordResetEmail(email, `${process.env.LIGHT_AUTH_URL}/reset-password?token=${token}`);
    return true;
  },

  // optional: enables the password reset confirmation endpoint, returns false for an invalid token (400)
  resetPassword: async (token, newPassword) => {
    const reset = await db.passwordReset.findUnique({ where: { token } });
    if (!reset || reset.expiresAt < new Date()) return false;

    await db.user.update({ where: { id: reset.userId }, data: { passwordHash: await bcrypt.hash(newPassword, 12) } });
    await db.passwordReset.delete({ where: { token } });
    return true;
  },
});
The provider must be named "credentials": the /credentials/* endpoints look for the provider with this name.
FunctionDescription
verifyCredentials(email, password, metadata?)Required. Returns the user claims (sub, email, name, optional picture and any custom claim), or null when the credentials are invalid. metadata is the request context given by your framework adapter.
registerUser(email, password, additionalData?)Creates the user and returns its claims, or null when the registration fails (the user already exists, for instance). additionalData contains the name and the additionalData sent by the client.
requestPasswordReset(email)Starts a password reset, typically by sending an email with a reset link.
resetPassword(token, newPassword)Checks the reset token and saves the new password. Returns false for an invalid or expired token.
hashPassword(password), comparePassword(password, hash)Optional helpers you can attach to the provider. They are not called by Light-Auth itself.

Add it to your configuration

./lib/auth.ts
import { CreateLightAuth } from "@light-auth/nextjs";
import { createGoogleProvider } from "@light-auth/core";
import { credentialsProvider } from "./credentials-provider";

const googleProvider = createGoogleProvider({
  clientId: process.env.GOOGLE_CLIENT_ID!,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
});

export const { providers, handlers, signIn, signOut, getAuthSession, getUser } = CreateLightAuth({
  providers: [credentialsProvider, googleProvider],
});

No extra route is needed: the credentials endpoints are served by the API handlers you already exposed.

Client functions

The browser calls the credentials endpoints with the functions exported by @light-auth/core/client. They fetch a CSRF token and send it back automatically, and never throw: they return an object with a success flag and an error message.

import {
  credentialsLogin,                // POST /credentials/login
  credentialsRegister,             // POST /credentials/register
  credentialsResetPasswordRequest, // POST /credentials/reset-password/request
  credentialsResetPasswordConfirm, // POST /credentials/reset-password/confirm
} from "@light-auth/core/client";

const config = { basePath: "/api/auth" };

await credentialsLogin({ config, email, password, callbackUrl: "/profile" });
// { success: true, session: { email, name, providerName } } or { success: false, error: "Invalid email or password" }

await credentialsRegister({ config, email, password, name, autoLogin: true, additionalData: { company: "Contoso" } });
// { success: true, message, session } or { success: false, error: "Registration failed. User may already exist." }

await credentialsResetPasswordRequest({ config, email });
// { success: true, message: "If an account with that email exists, a password reset link has been sent." }

await credentialsResetPasswordConfirm({ config, token, newPassword });
// { success: true, message } or { success: false, error: "Invalid or expired reset token" }
config.basePath is required, it must match the base path of your server configuration. You can reuse the basePath returned by CreateLightAuthClient().

Login form

credentialsLogin does not navigate: once it succeeds, the HTTP-only session cookie is set, and you redirect the user yourself.

./components/credentials-login-form.tsx
"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { credentialsLogin } from "@light-auth/core/client";

export function CredentialsLoginForm() {
  const router = useRouter();
  const [error, setError] = useState<string>();

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const form = new FormData(e.currentTarget);

    const result = await credentialsLogin({
      config: { basePath: "/api/auth" },
      email: String(form.get("email")),
      password: String(form.get("password")),
    });

    if (!result.success) return setError(result.error);

    router.push("/profile");
    router.refresh(); // re-render the server components with the new session
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="email" type="email" autoComplete="email" required />
      <input name="password" type="password" autoComplete="current-password" required />
      {error && <p>{error}</p>}
      <button type="submit">Sign in</button>
    </form>
  );
}

Registration

With autoLogin (default true), the user is signed in as soon as it is registered. Set it to false to only create the account, if you want to verify the email first for instance.

const result = await credentialsRegister({
  config: { basePath: "/api/auth" },
  email,
  password,
  name,
});

if (result.success) router.push("/profile");
else setError(result.error);

Password reset

1

A "forgot password" page calls credentialsResetPasswordRequest. Light-Auth calls your requestPasswordReset function, which sends an email with a link containing a reset token.

2

The page of the link calls credentialsResetPasswordConfirm with the token and the new password. Light-Auth calls your resetPassword function, which checks the token and saves the new password.

./app/reset-password/reset-password-form.tsx
"use client";

import { useSearchParams } from "next/navigation";
import { credentialsResetPasswordConfirm } from "@light-auth/core/client";

export function ResetPasswordForm() {
  const token = useSearchParams().get("token") ?? "";

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const newPassword = String(new FormData(e.currentTarget).get("password"));

    const result = await credentialsResetPasswordConfirm({ config: { basePath: "/api/auth" }, token, newPassword });
    alert(result.success ? result.message : result.error);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="password" type="password" autoComplete="new-password" required />
      <button type="submit">Reset my password</button>
    </form>
  );
}

Endpoints

All the credentials endpoints accept a JSON body with the POST method, and require a valid CSRF token (see below).

RouteBodyResponses
/api/auth/credentials/login{ email, password, callbackUrl? }200 signed in, 400 missing email or password, 401 invalid email or password, 500 authentication failed
/api/auth/credentials/register{ email, password, name?, autoLogin?, additionalData? }201 registered (and signed in when autoLogin is true, default), 400 missing email or password, 409 registerUser returned null, 501 no registerUser function, 500 registration failed
/api/auth/credentials/reset-password/request{ email }200 always the same message, whether the email exists or not, 400 missing email, 501 no requestPasswordReset function
/api/auth/credentials/reset-password/confirm{ token, newPassword }200 password reset, 400 missing values or invalid token, 501 no resetPassword function, 500 reset failed

Errors are returned as { error: string }. The callbackUrl of the login is restricted to a path of your application.

Calling the endpoints with your own fetch

The CSRF protection uses the double-submit pattern: getCsrfToken stores a signed token in the light_auth_csrf_token cookie and returns it, and the same token must be sent back in the x-light-auth-csrf-token header:

import { getCsrfToken } from "@light-auth/core";

const config = { basePath: "/api/auth" };
const csrfToken = await getCsrfToken({ config });

const response = await fetch(`${config.basePath}/credentials/login`, {
  method: "POST",
  headers: { "Content-Type": "application/json", "x-light-auth-csrf-token": csrfToken ?? "" },
  body: JSON.stringify({ email, password }),
});

Session and user

After a successful login, the session is created from the claims returned by verifyCredentials (or registerUser):

  • sub becomes the providerUserId, and providerName is "credentials".
  • Your custom claims are copied into the session, and picture into the user. The session is stored in a cookie: keep the custom claims small.
  • The onSessionSaving, onUserSaving and event hooks are called as for any other provider (onLogin, onRegister, onPasswordReset, onError).
  • Credentials users have no access token nor refresh token: token refresh and token revocation do not apply.

Then use getAuthSession(), getUser() and signOut() exactly as with OAuth providers.

Security recommendations

  • Never store plain text passwords: hash them with bcrypt, scrypt or argon2.
  • Protect the credentials endpoints against brute force attacks with a rate limiter.
  • Use random, single use and short-lived password reset tokens, and store them hashed when possible.
  • The reset request always answers the same message, so that it can't be used to find out which emails have an account. Keep the same behavior in your own pages.