X Enterprises
fastify-xauth-local

password.compare

Compare a plaintext password against a bcrypt hash, returning true if they match.

password.compare

Compares a plaintext password against a bcrypt hash and returns true if they match. Use this when implementing custom login logic outside the built-in local routes.

Signature

fastify.xauthlocal.password.compare(
  password: string,
  hash: string
): Promise<boolean>

Params

NameTypeRequiredDescription
passwordstringYesThe plaintext password to verify
hashstringYesThe bcrypt hash stored in your database

Returns

A Promise<boolean>true if the password matches the hash, false otherwise.

Throws

Rejects if hash is not a valid bcrypt string.

Examples

Basic: custom login handler

fastify.post("/auth/login", async (request, reply) => {
  const { email, password } = request.body;
  const user = await db.users.findByEmail(email);

  if (!user) {
    return reply.code(401).send({ error: "Invalid credentials" });
  }

  const valid = await fastify.xauthlocal.password.compare(password, user.password);
  if (!valid) {
    return reply.code(401).send({ error: "Invalid credentials" });
  }

  const api = fastify.xauthlocal.get("api");
  const token = api.jwt.sign({ id: user.id, email: user.email });
  return { token };
});

Advanced: re-verify current password before allowing a change

fastify.put("/api/change-password", async (request, reply) => {
  const { currentPassword, newPassword } = request.body;
  const user = await db.users.findById(request.auth.id);

  const valid = await fastify.xauthlocal.password.compare(currentPassword, user.password);
  if (!valid) {
    return reply.code(400).send({ error: "Current password is incorrect" });
  }

  const hash = await fastify.xauthlocal.password.hash(newPassword);
  await db.users.updatePassword(user.id, hash);
  return { updated: true };
});

See Also

AI Context

package: "@xenterprises/fastify-xauth-local"
method: fastify.xauthlocal.password.compare(plaintext, hash)
use-when: Compare a plaintext password against a stored bcrypt hash
returns: Promise<boolean>
Copyright © 2026