The Credential Management API: Sign-In From JavaScript
How the Credential Management API signs users in with navigator.credentials: passwords, passkeys with WebAuthn, conditional UI and storing credentials.

Signing in is where the browser and the website have to cooperate. The browser knows the passwords, passkeys and federated accounts the user has saved, and the site knows how to verify them. Before the Credential Management API, the only connection was form autofill, which guessed which fields to fill and offered no way for script to say "sign the user in" or "save this login". The API adds a single entry point, navigator.credentials, with get(), create(), store() and preventSilentAccess(), and one model for several kinds of credentials: passwords, federated sign-in and, most importantly today, public key credentials, the passkeys of WebAuthn. This post explains how the Credential Management API works: the methods and the credential types, how to sign in with a saved password and how to save one after a registration, how to create and use a passkey, conditional mediation that shows passkeys in the username field's autofill, how to sign out so that automatic sign-in stops, feature detection, the security requirements and how to test it. It is documented on MDN and the WebAuthn specification, and the core is supported in current Chromium browsers, Safari and Firefox, with credential types varying: passkeys are widely supported, while PasswordCredential and FederatedCredential are Chromium-only, so check each. It needs a secure context, which means HTTPS or localhost.
The entry point
navigator.credentials offers four methods. get() asks the browser for a credential, which may show an account chooser. create() makes a new credential, such as a passkey. store() saves a credential object after a successful sign-in. preventSilentAccess() tells the browser not to sign the user in automatically next time. Every method returns a promise.
console.log("credentials" in navigator);
console.log(typeof window.PublicKeyCredential);
console.log(typeof window.PasswordCredential);true
function
functionThe last line is undefined in browsers without PasswordCredential. Always feature-detect each type, and keep the ordinary form working, since the API is an enhancement on top of a standard sign-in page.
Passwords: get and store
In browsers that support PasswordCredential, get({ password: true }) returns the saved credential for the site, with the id and password, and the page sends them to the server.
async function trySavedPassword() {
if (!window.PasswordCredential) return null;
const credential = await navigator.credentials.get({
password: true,
mediation: "optional",
});
if (credential?.type !== "password") return null;
const response = await fetch("/api/sign-in", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username: credential.id, password: credential.password }),
});
return response.ok ? credential : null;
}
trySavedPassword().then((c) => console.log(c ? "signed in as " + c.id : "show the form"));signed in as [email protected]The mediation option controls whether the browser may act without asking: silent returns a credential only if it can do so without any user interface, optional shows a chooser if needed and required always shows one. After a successful sign-in with a form, save the credential so the browser can offer it next time.
async function rememberSignIn(form) {
if (!window.PasswordCredential) return;
const credential = new PasswordCredential(form);
await navigator.credentials.store(credential);
console.log("offered to save", credential.id);
}offered to save [email protected]The PasswordCredential constructor reads the form's fields, using the autocomplete attributes username and current-password to find them, so mark the inputs correctly, which also helps password managers in every browser.
Passkeys: create and get
A passkey is a public key credential bound to your site. Registration creates a key pair on the user's device, or in their password manager, keeps the private key there and gives the site the public key. Sign-in proves possession of the private key by signing a challenge. The browser API for both is navigator.credentials.create() and get() with a publicKey option, and the server side verifies the results. The challenge must be random and come from the server, and it must be used once.
async function registerPasskey() {
const options = await fetch("/api/passkeys/options", { method: "POST" }).then((r) => r.json());
const credential = await navigator.credentials.create({
publicKey: {
challenge: Uint8Array.from(atob(options.challenge), (c) => c.charCodeAt(0)),
rp: { name: "Example", id: "example.com" },
user: {
id: Uint8Array.from(atob(options.userId), (c) => c.charCodeAt(0)),
name: options.username,
displayName: options.displayName,
},
pubKeyCredParams: [
{ type: "public-key", alg: -7 },
{ type: "public-key", alg: -257 },
],
authenticatorSelection: { residentKey: "required", userVerification: "preferred" },
},
});
console.log(credential.type, credential.id.length > 0);
return credential;
}public-key trueThe algorithm identifiers are COSE values: -7 is ES256 and -257 is RS256. residentKey: "required" creates a discoverable credential, which is what lets the user sign in without typing a username. The credential's response holds the attestation object and client data as ArrayBuffers, which you encode, for instance as base64url, and send to the server for verification with a server library, since checking attestation correctly is not something to write by hand. The rp.id must be the site's domain or a registrable suffix of it, which ties the credential to the origin and is what makes passkeys resistant to phishing: a lookalike domain cannot use them.
Signing in uses get():
async function signInWithPasskey() {
const options = await fetch("/api/passkeys/challenge", { method: "POST" }).then((r) => r.json());
const assertion = await navigator.credentials.get({
publicKey: {
challenge: Uint8Array.from(atob(options.challenge), (c) => c.charCodeAt(0)),
rpId: "example.com",
userVerification: "preferred",
},
});
const body = {
id: assertion.id,
clientDataJSON: btoa(String.fromCharCode(...new Uint8Array(assertion.response.clientDataJSON))),
};
const result = await fetch("/api/passkeys/verify", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
console.log(result.ok);
}trueThe example sends only part of the response for brevity. A real server needs the authenticator data and the signature as well, and verifies the signature with the stored public key, checks the challenge, the origin and the sign count. Newer browsers also provide PublicKeyCredential.parseCreationOptionsFromJSON(), parseRequestOptionsFromJSON() and credential.toJSON(), which handle the base64url conversion for you, so check support and prefer them where available.
Conditional UI
A button "Sign in with a passkey" is one option. The better experience shows the user's passkeys in the autofill list of the username field, so the user taps the field and picks an account, or types a password as before. That is conditional mediation. Add webauthn to the field's autocomplete attribute, and call get() with mediation: "conditional" on page load.
<input name="username" autocomplete="username webauthn" autofocus>
<input name="password" type="password" autocomplete="current-password">(the browser lists passkeys when the user focuses the username field)async function startConditionalSignIn() {
if (!(await PublicKeyCredential.isConditionalMediationAvailable?.())) return;
const options = await fetch("/api/passkeys/challenge", { method: "POST" }).then((r) => r.json());
const controller = new AbortController();
try {
const assertion = await navigator.credentials.get({
mediation: "conditional",
signal: controller.signal,
publicKey: {
challenge: Uint8Array.from(atob(options.challenge), (c) => c.charCodeAt(0)),
rpId: "example.com",
},
});
console.log("chosen:", assertion.id);
} catch (error) {
if (error.name !== "AbortError") throw error;
}
}
startConditionalSignIn();chosen: kZ3m...The call stays pending until the user chooses a passkey from the field, so run it once when the page loads and keep the AbortController, so you can cancel it if the user starts another flow, because only one request can be pending at a time. If the user types a password instead, abort the conditional request.
Signing out
Automatic sign-in, which returns a credential with mediation: "silent", is convenient and dangerous after a sign-out: the user clicks Sign out and the browser signs them straight back in. Call preventSilentAccess() on sign-out to prevent that, until the user signs in again deliberately.
async function signOut() {
await fetch("/api/sign-out", { method: "POST" });
await navigator.credentials.preventSilentAccess();
console.log("signed out, auto sign-in disabled");
}signed out, auto sign-in disabledFederated identity
FederatedCredential and IdentityCredential cover sign-in through an identity provider. The older FederatedCredential is Chromium-only and has been overtaken by the Federated Credential Management API (FedCM), which the browser mediates with navigator.credentials.get({ identity: { providers: [...] } }), and by provider libraries. Treat them as separate topics, and use the provider's recommended library for third-party sign-in.
Errors
The common rejections are NotAllowedError, which covers the user canceling, a timeout and a call outside a user gesture where one is required, InvalidStateError for an authenticator that already has a credential for that user, NotSupportedError for algorithms the device cannot make and SecurityError when rp.id does not match the origin. Treat NotAllowedError as "the user said no" and keep the other sign-in methods available, without an error banner.
try {
await navigator.credentials.get({ publicKey: { challenge: new Uint8Array(32), rpId: "other.example" } });
} catch (error) {
console.log(error.name);
}SecurityErrorServer side and security
The browser is half of the flow. The server generates the challenge, stores it with a short lifetime, verifies the attestation or assertion, checks the origin and relying party ID, stores the credential ID and public key per user, and updates the signature counter. Use a maintained WebAuthn library for your language instead of writing verification yourself. Keep a recovery path for users who lose their devices, such as another passkey or a verified email flow, since a passkey on a lost phone is otherwise a lockout, though synced passkeys in a password manager reduce that risk.
Testing
Chromium DevTools has a WebAuthn panel with virtual authenticators, so you can test registration and sign-in without hardware, including resident keys and user verification. Playwright and WebDriver also expose virtual authenticators for automated tests. Test the fallback paths too: a browser without the API, a canceled prompt and the ordinary password form.
Pitfalls
Skipping feature detection. Generating the challenge in the browser. Reusing a challenge. Using the wrong rp.id. Not aborting a pending conditional request. Forgetting preventSilentAccess() at sign-out. Verifying passkey responses by hand. Removing the password form before passkeys are reliable for all your users. And making the passkey prompt appear without a user gesture, where the browser may ignore it.


