fn

useOtpCredentials

v0.0.14testeddemo

Reactive, SSR-safe wrapper around the WebOTP API (navigator.credentials.get({ otp })) for auto-reading one-time passwords delivered by SMS. Exposes the received code, in-flight/error state, receive()/abort() controls, and onReceive/onError hooks. Pairs with an <input autocomplete="one-time-code">.

Examples

ts
const { isSupported, code, receive } = useOtpCredentials();
if (isSupported.value) {
  const otp = await receive();
  if (otp)
    form.code = otp;
}
ts
// Start listening on mount and react via the hook
const { onReceive } = useOtpCredentials({ immediate: true });
onReceive((code) => { form.code = code; });
ts
// Give up after 30 seconds via an external signal
const { receive } = useOtpCredentials();
receive({ signal: AbortSignal.timeout(30_000) });

Demo

Loading demo…

Signature

ts
export function useOtpCredentials(options: UseOtpCredentialsOptions ={ ... }

Parameters

ParameterTypeDescription
options?UseOtpCredentialsOptionsOptions (transport, immediate, signal, onReceive, onError, custom window/navigator)

Returns

UseOtpCredentialsReturn{ isSupported, code, isReceiving, error, receive, abort, onReceive, onError }
PropertyTypeDescription
isSupportedComputedRef<boolean>Whether the WebOTP API is supported.
codeShallowRef<string | null>The most recently received OTP code, or null before the first one arrives. Writable so consumers can clear it.
isReceivingReadonly<ShallowRef<boolean>>Whether a request is currently in flight (waiting for the user to deliver the OTP).
errorReadonly<ShallowRef<unknown>>The last non-abort error, or null. Aborts are part of normal lifecycle and are never surfaced here.
receive(overrideOptions?: OtpCredentialsRequestOptions) => Promise<string | undefined>Start listening for an OTP. Resolves with the received code, or undefined when the request is aborted, errors, or the API is unsupported. Only one request can be active at a time — calling receive again aborts the previous one. Never rejects; failures surface via error / onError.
abort() => voidAbort the in-flight request, if any.
onReceiveEventHookOn<string>Register a listener fired with the code each time an OTP is received.
onErrorEventHookOn<unknown>Register a listener fired with the error when a request fails (non-abort).