JavaScript API (NAHNLSAuth)
window.NAHNLSAuth is a small browser library that signs users in with passkeys and magic links, completes two-factor challenges, and manages passkeys. It wraps the plugin’s REST routes in promise-based methods and handles the WebAuthn details for you. Use it when you build your own login screen, a slide-out login drawer, or a headless front end.
If you only need a button on a normal WordPress page, the PHP helpers are simpler. See Passwordless API. For the underlying routes see REST API.
Load the script#
When passkey sign-in is on and the page is HTTPS, nahnls-auth.js is already on the page in these places: the login screen, the WooCommerce login form, the Login & security panel, and wherever you print nahnls_passkey_button(). On any other page, load it yourself.
From PHP (recommended):
add_action( 'wp_enqueue_scripts', function () {
if ( defined( 'NAHNLS_API_VERSION' ) && NAHNLS_API_VERSION >= 2 && function_exists( 'nahnls_enqueue_auth_script' ) ) {
nahnls_enqueue_auth_script();
}
} ); nahnls_enqueue_auth_script() loads the script with its REST settings and translated messages, even when passkeys are turned off. Use it on any page that calls twoFactorVerify(), twoFactorEmail(), twoFactorPasskey() or requestMagicLink().
By hand:
wp_enqueue_script( 'nahnls-auth', NAHNLS_URL . 'assets/js/nahnls-auth.js', [], NAHNLS_VERSION, true );
wp_localize_script( 'nahnls-auth', 'NAHNLSAuthConfig', [
'restUrl' => rest_url( 'nahnls/v1/' ),
'restNonce' => wp_create_nonce( 'wp_rest' ),
'credentials' => 'same-origin', // 'include' for a front end on another host
] ); Configuration#
The library looks for its settings in these places, in this order. The first one found wins for each key:
window.NAHNLSAuthConfigwindow.NAHNLSPasskeysLogin(set by the plugin’s own login button)window.NAHNLSPasskeys(set by the passkey management panel)window.wpApiSettings(rootandnonce, set by WordPress’swp-api-requestscript)- The
<link rel="https://api.w.org/">tag in the page head
On most WordPress pages no configuration is needed.
| Key | Meaning |
|---|---|
restUrl | The base of the plugin’s REST routes, for example https://site.example/wp-json/nahnls/v1/ |
restNonce | wp_create_nonce( 'wp_rest' ). Sent as X-WP-Nonce on routes that need a signed-in user only |
credentials | The fetch credentials mode: 'same-origin' (default) or 'include' for a front end on another host |
i18n | Optional translated messages |
For a front end on another host, see the cross-origin notes in REST API.
Methods#
Every method that talks to the server returns a promise.
| Method | Resolves with | Notes |
|---|---|---|
isPasskeyAvailable() | boolean | True when the browser supports WebAuthn and the page is a secure context |
isConditionalAvailable() | boolean | True when the browser supports passkey autofill |
passkeyLogin( opts ) | { redirect, user_id, pending_2fa } | Sets the login cookie. You send the browser to redirect yourself |
passkeyRegister( name ) | the new passkey’s public record | For signed-in users only |
passkeyRemove( id, { userId } ) | { removed, passkeys } | userId needs the edit_users capability |
passkeyList( { userId } ) | array of passkey records | |
requestMagicLink( identifier, redirect, { origin } ) | { sent: true } | Rejects on HTTP 429. origin: 'wc' (API 2) makes a later 2FA step open on the WooCommerce My Account page |
twoFactorVerify( nonceKey, { code, backupCode } ) (API 2) | { redirect } | Sets the login cookie. You navigate to redirect |
twoFactorEmail( nonceKey ) (API 2) | { sent, email_masked } | Emails a new code |
twoFactorPasskey( nonceKey, { signal, onStage } ) (API 2) | { redirect } | Runs the whole passkey step, then sets the login cookie |
mySecurity() | an object | GET me/security: the signed-in user’s 2FA and passkey summary |
apiVersion | number | Mirrors NAHNLS_API_VERSION in PHP. Currently 2 |
passkeyLogin( opts )
| Option | What it does |
|---|---|
redirect | Where to go after signing in |
remember | Ask for a persistent session |
mediation | Set to 'conditional' to show passkeys in the browser’s autofill list |
signal | An AbortSignal to cancel the flow |
onStage | A callback for progress stages |
When pending_2fa is true, no session exists yet, and redirect is the 2FA challenge page. Send the browser there.
NAHNLSAuth.passkeyLogin({ redirect: '/members/' })
.then(({ redirect }) => window.location.assign(redirect))
.catch((e) => showError(e.message)); requestMagicLink( identifier, redirect, opts )
NAHNLSAuth.requestMagicLink('user@example.com', '/members/')
.then(() => showMessage('Check your inbox.'))
.catch((e) => showError(e.message)); The result is always { sent: true }, whether or not the account exists. A rejection means a rate limit or a hard stop (blocked IP, lockout, geo-block).
Finishing a two-factor step
Start the challenge in PHP with nahnls_start_2fa_challenge(), which gives you a nonce_key. Then:
// The password step returned { two_factor: c }.
NAHNLSAuth.twoFactorVerify(c.nonce_key, { code: input.value })
.then(({ redirect }) => window.location.assign(redirect))
.catch((e) => {
if (e.code === 'nahnls_2fa_invalid') {
showError(e.message + ' (' + e.attempts_left + ' left)');
} else if (e.code === 'nahnls_2fa_expired' || e.code === 'nahnls_2fa_locked') {
backToPassword(e.message);
} else {
showError(e.message);
}
});
// "Email me a code"
NAHNLSAuth.twoFactorEmail(c.nonce_key).then(({ email_masked }) => showMessage('Sent to ' + email_masked));
// Passkey button
NAHNLSAuth.twoFactorPasskey(c.nonce_key).then(({ redirect }) => window.location.assign(redirect)); Use { backupCode: '...' } instead of code to send a backup code. Spaces in a code are removed for you.
Errors#
Rejections are Error objects with these properties:
| Property | Meaning |
|---|---|
message | A readable message you can show |
code | The REST error code, or one of the browser-side codes below |
status | The HTTP status, when the server answered |
server | true when the error came from the server |
kind | Which flow failed, for example passkey_login, two_factor, two_factor_email, two_factor_passkey |
attempts_left | Only on nahnls_2fa_invalid |
Browser-side codes:
| Code | When |
|---|---|
cancelled | The user closed the prompt, or it timed out |
unsupported | The browser or the page doesn’t support passkeys |
insecure_context | The browser raised a security error, for example the passkey domain does not match the page. A page that isn’t HTTPS gives unsupported |
invalid_state | The browser refused the request, for example the passkey already exists |
network | The request failed to reach the server |
REST error codes (such as nahnls_2fa_invalid, nahnls_2fa_expired, nahnls_2fa_locked and nahnls_2fa_rate) are listed in REST API.
Events#
The library fires events on document. Read the details from event.detail.
| Event | Detail |
|---|---|
nahnls:passkey:login | { user_id, redirect, pending_2fa } |
nahnls:passkey:registered | the new passkey’s record |
nahnls:passkey:removed | { id, user_id } |
nahnls:magiclink:requested | { sent } |
nahnls:2fa:verified (API 2) | { method }: 'code', 'backup_code' or 'passkey' |
nahnls:error | { kind, message, code, status } |
document.addEventListener('nahnls:passkey:login', function (e) {
analytics.track('login', { method: 'passkey', user: e.detail.user_id });
});
document.addEventListener('nahnls:error', function (e) {
console.warn(e.detail.kind, e.detail.code);
}); A deliberate cancel (when another flow takes over) doesn’t fire nahnls:error.
Low-level helpers#
For your own flows, NAHNLSAuth.util offers:
| Helper | What it does |
|---|---|
decodeRequestOptions( publicKey ) | Turns the server’s sign-in options into what navigator.credentials.get() expects |
decodeCreateOptions( publicKey ) | The same for navigator.credentials.create() |
encodeAssertion( credential ) | Turns the result of get() into JSON for the server |
encodeAttestation( credential ) | Turns the result of create() into JSON for the server |
b64urlToBuffer( string ), bufferToB64url( buffer ) | Base64url conversion |
request( path, options ) | A fetch call to the plugin’s REST base with the right credentials and nonce |
restBase() | The REST base address |
const { publicKey } = await fetch('/wp-json/nahnls/v1/passkeys/login/options', { method: 'POST' })
.then(r => r.json());
const cred = await navigator.credentials.get({
publicKey: NAHNLSAuth.util.decodeRequestOptions(publicKey)
});
await fetch('/wp-json/nahnls/v1/passkeys/login/verify', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ credential: NAHNLSAuth.util.encodeAssertion(cred), redirect: '/app' })
}); Example: a React button#
// Load nahnls-auth.js and set window.NAHNLSAuthConfig = { restUrl: 'https://site.example/wp-json/nahnls/v1/' }.
function PasskeyButton() {
const [error, setError] = React.useState('');
const signIn = () =>
window.NAHNLSAuth.passkeyLogin({ redirect: '/app' })
.then(({ redirect, pending_2fa }) => {
window.location.assign(pending_2fa ? redirect : '/app');
})
.catch((e) => setError(e.message));
return (
<>
<button onClick={signIn}>Sign in with a passkey</button>
{error && <p role="alert">{error}</p>}
</>
);
} Good to know#
- Passkeys need HTTPS. On other pages,
isPasskeyAvailable()isfalseandpasskeyLogin()rejects withunsupported. passkeyLogin()andtwoFactorPasskey()set the login cookie but never navigate. You decide where to go next.- A passkey sign-in can still lead to a 2FA challenge. Check
pending_2fa. - The library doesn’t load itself twice. If
window.NAHNLSAuthalready exists, a second copy does nothing. - The CAPTCHA widget has its own object,
NAHNLSWidget. See CAPTCHA widget in JavaScript forms.
Was this helpful?
Thanks for your feedback!
✓ Feedback received. Thank you!