Displaying captcha upon backend request
-
Install VK Капча SDK.
-
Add the import of the
checkCaptchaErrorfunction to the frontend:import { checkCaptchaError } from '@vkid/captcha'; -
Send a request to the backend for the target user action.
-
Pass the response to the
checkCaptchaError()function. The function will parse the response and return a link to launch the captcha widget if a captcha was required. -
Display the captcha to the user. Use the SDK method captchaWidget.show().
The method will return a promise object with the captcha completion result: a successful captcha completion token if the user passed the captcha, or an error if the user closed the captcha.
-
Process the captcha completion result:
- If the promise object contains a successful captcha completion token, repeat the original request for the target user action, adding the token to it.
- If the user closed the captcha, nothing is sent to the backend. Determine what will happen in the frontend in this case.
TypeScript code example:
import { checkCaptchaError } from '@vkid/captcha';async function onSubmit(credentials: Credentials) {// Request for the user action. The frontend doesn't know anything about the captcha yetconst response = await fetch('/api/legacy/login', {method: 'POST',body: JSON.stringify({ ...credentials, client }),});const data = await response.json();// There is no need to manually specify the captcha launch link, it is returned by the checkCaptchaError() function.const { captchaType, captchaWidget } = checkCaptchaError({responseHeaders: response.headers,url: response.url,responseError: data.error,withWidget: true, // Without this parameter, only the address will be returned, without the widget});if (captchaType === null) {return finish(data); // Captcha was not required}if (!captchaWidget) {// Captcha is needed, but the widget could not be built: the response has no captcha addressreturn handleUnknownCaptcha(data);}const captchaToken = await captchaWidget.show({container: document.body,view: 'popup',lang: 'ru',});// The same request for the user action, but with the captcha completion tokenawait fetch('/api/legacy/login', {method: 'POST',body: JSON.stringify({ ...credentials, client, captchaToken }),});}
Was this article helpful?