fn
useOtpCredentials
v0.0.14testeddemoReactive, 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
| Parameter | Type | Description |
|---|---|---|
options? | UseOtpCredentialsOptions | Options (transport, immediate, signal, onReceive, onError, custom window/navigator) |
Returns
UseOtpCredentialsReturn{ isSupported, code, isReceiving, error, receive, abort, onReceive, onError }| Property | Type | Description |
|---|---|---|
isSupported | ComputedRef<boolean> | Whether the WebOTP API is supported. |
code | ShallowRef<string | null> | The most recently received OTP code, or null before the first one
arrives. Writable so consumers can clear it. |
isReceiving | Readonly<ShallowRef<boolean>> | Whether a request is currently in flight (waiting for the user to deliver the OTP). |
error | Readonly<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 | () => void | Abort the in-flight request, if any. |
onReceive | EventHookOn<string> | Register a listener fired with the code each time an OTP is received. |
onError | EventHookOn<unknown> | Register a listener fired with the error when a request fails (non-abort). |