Docs

JavaScript API (NAHNLSAuth)

6 min readUpdated November 19, 2026

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:

  1. window.NAHNLSAuthConfig
  2. window.NAHNLSPasskeysLogin (set by the plugin’s own login button)
  3. window.NAHNLSPasskeys (set by the passkey management panel)
  4. window.wpApiSettings (root and nonce, set by WordPress’s wp-api-request script)
  5. The <link rel="https://api.w.org/"> tag in the page head

On most WordPress pages no configuration is needed.

KeyMeaning
restUrlThe base of the plugin’s REST routes, for example https://site.example/wp-json/nahnls/v1/
restNoncewp_create_nonce( 'wp_rest' ). Sent as X-WP-Nonce on routes that need a signed-in user only
credentialsThe fetch credentials mode: 'same-origin' (default) or 'include' for a front end on another host
i18nOptional 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.

MethodResolves withNotes
isPasskeyAvailable()booleanTrue when the browser supports WebAuthn and the page is a secure context
isConditionalAvailable()booleanTrue 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 recordFor 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 objectGET me/security: the signed-in user’s 2FA and passkey summary
apiVersionnumberMirrors NAHNLS_API_VERSION in PHP. Currently 2

passkeyLogin( opts )

OptionWhat it does
redirectWhere to go after signing in
rememberAsk for a persistent session
mediationSet to 'conditional' to show passkeys in the browser’s autofill list
signalAn AbortSignal to cancel the flow
onStageA 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));
Code
// 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:

PropertyMeaning
messageA readable message you can show
codeThe REST error code, or one of the browser-side codes below
statusThe HTTP status, when the server answered
servertrue when the error came from the server
kindWhich flow failed, for example passkey_login, two_factor, two_factor_email, two_factor_passkey
attempts_leftOnly on nahnls_2fa_invalid

Browser-side codes:

CodeWhen
cancelledThe user closed the prompt, or it timed out
unsupportedThe browser or the page doesn’t support passkeys
insecure_contextThe browser raised a security error, for example the passkey domain does not match the page. A page that isn’t HTTPS gives unsupported
invalid_stateThe browser refused the request, for example the passkey already exists
networkThe 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.

EventDetail
nahnls:passkey:login{ user_id, redirect, pending_2fa }
nahnls:passkey:registeredthe 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:

HelperWhat 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' })
});
Code
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>}
        </>
    );
}
Code
// 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() is false and passkeyLogin() rejects with unsupported.
  • passkeyLogin() and twoFactorPasskey() 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.NAHNLSAuth already exists, a second copy does nothing.
  • The CAPTCHA widget has its own object, NAHNLSWidget. See CAPTCHA widget in JavaScript forms.

Was this helpful?

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only