ViraStack
  • Academy
  • About
  • Support
HomeGet StartedExamples

Getting started

  • Introduction
  • Upgrade from 1.0
  • llms.txt
  • llms-full.txt

Usage

  • useViraPassword()
  • Strength
  • Confirm password
  • React Hook Form
  • Accessibility
  • Customization

Server

  • Server validation
  • Leaked passwords

Reference

  • Helpers
  • Types
  • UI libraries
  • Comparison

Server validation

Run the same policy in Server Actions and API routes with @virastack/password/server.

Server entry

The browser can be skipped, so the server decides. validatePassword uses the same engine as the form; the same input gives the same issues on both sides. Use it for sign-up, password reset and password change.

import { validatePassword } from "@virastack/password/server"
 
const result = validatePassword(formData.get("password"), policy, {
  forbidden: [formData.get("email")],
  confirm: formData.get("confirm"), // adds password.mismatch when it differs
})
// result.valid, result.issues, result.score, result.password (NFKC)

Anything that isn't a string (a missing field, a File) counts as an empty password.

Server Action

// components/signup-form.tsx
"use client";
 
import { useActionState, useState } from "react";
 
import { useViraPassword } from "@virastack/password";
 
import { passwordMessages } from "@/lib/password-messages";
import { policy } from "@/lib/password-policy";
import { signup, type SignupState } from "@/app/signup/actions";
 
export function SignupForm() {
  const [state, action, pending] = useActionState<SignupState, FormData>(signup, null);
  const [password, setPassword] = useState("");
 
  // No form library: plain state; the form still posts its own FormData.
  const { inputProps, btnProps } = useViraPassword({
    policy,
    inputProps: {
      name: "password",
      value: password,
      onChange: (event) => setPassword(event.target.value),
    },
  });
  const { inputProps: confirmProps, btnProps: confirmButton } = useViraPassword({
    matchWith: password,
    inputProps: { name: "confirm" },
  });
 
  return (
    <form action={action}>
      <label htmlFor="email">Email</label>
      <input
        id="email"
        name="email"
        type="email"
        autoComplete="username"
        defaultValue="hello@virastack.com"
      />
 
      <label htmlFor={inputProps.id}>New password</label>
      <div>
        <input {...inputProps} />
        <button {...btnProps} />
      </div>
 
      <label htmlFor={confirmProps.id}>Confirm password</label>
      <div>
        <input {...confirmProps} />
        <button {...confirmButton} />
      </div>
 
      <button type="submit" disabled={pending}>
        Create account
      </button>
 
      {state?.ok && <p>The server accepted the password.</p>}
      {state && !state.ok && (
        <ul role="alert">
          {state.issues.map((issue) => (
            <li key={issue}>{passwordMessages[issue]}</li>
          ))}
        </ul>
      )}
    </form>
  );
}
// app/signup/actions.ts
"use server";
 
import { validatePassword } from "@virastack/password/server";
import type { PasswordIssue } from "@virastack/password/strength";
 
import { policy } from "@/lib/password-policy";
 
export type SignupState = { ok: boolean; issues: PasswordIssue[] } | null;
 
export async function signup(_state: SignupState, formData: FormData): Promise<SignupState> {
  // The browser can be skipped; the server checks again with the same policy.
  const result = validatePassword(formData.get("password"), policy, {
    forbidden: [formData.get("email")],
    confirm: formData.get("confirm"),
  });
  if (!result.valid) return { ok: false, issues: result.issues };
 
  // await createUser(email, await hash(result.password)) — result.password is NFKC-normalized
  return { ok: true, issues: [] };
}
// app/api/password/route.ts
import { validatePassword } from "@virastack/password/server"
import { policy } from "@/lib/password-policy"
 
export async function POST(request: Request) {
  const { password, email } = await request.json()
  const result = validatePassword(password, policy, { forbidden: [email] })
  return Response.json({ valid: result.valid, issues: result.issues })
}

What to hash

Hash result.password: it is NFKC-normalized, so the same password typed on another keyboard still verifies at login. Normalize the login input the same way with normalizePassword.

SSR & Next.js

  • Only @virastack/password has "use client". Server Components, Server Actions and route handlers import /server or /strength.
  • Keep the policy in a shared file without "use client".
  • The hook renders the same markup on the server and the client (ids come from useId), so there is no hydration mismatch.
  • Tested with Next.js in next dev and next start.
PreviousCustomizationNextLeaked passwords

On this page

  • Server entry
  • Server Action
  • What to hash
  • SSR & Next.js
Something wrong? Fix it