The Sinch Node.js SDK allows you to quickly interact with the Verification API from inside your Node.js applications. When using the Node.js SDK, the code representing requests and queries sent to and responses received from the Verification API are structured similarly to those that are sent and received using the Verification API.
The fastest way to get started with the SDK is to check out our getting started guides. There you'll find all the instructions necessary to download, install, set up, and start using the SDK.
This guide describes the syntactical structure of the Node.js SDK for the Verification API, including any differences that may exist between the API itself and the SDK. For a full reference on Verification API calls and responses, see the Verification API Reference.
The code sample below is an example of how to use the Node.js SDK to initiate an Verification SMS PIN request. We've also provided an example that accomplishes the same task using the REST API.
// eslint-disable-next-line no-unused-vars
import { Verification, VerificationService, VerificationsApi } from '@sinch/sdk-core';
import inquirer from 'inquirer';
/**
* Class to handle a phone number verification using SMS.
*/
export class VerificationSample {
/**
* @param { VerificationService } verificationService - the VerificationService instance from the Sinch SDK containing the API methods.
*/
constructor(verificationService) {
this.verificationService = verificationService;
}
/**
* Starts the verification process by prompting the user for a phone number,
* sending a verification request, asking for the verification code, and reporting it.
* @return {Promise<void>}
*/
async start() {
// Step 1: Ask the phone number to verify
const e164Number = await this.promptPhoneNumber();
try {
// Step 2: Start the phone number verification
const verificationId = await this.startSmsVerification(this.verificationService.verifications, e164Number);
// Step 3: Ask the user for the received verification code
const code = await this.promptSmsCode();
// Step 4: Report the verification code and complete the process
await this.reportSmsVerification(this.verificationService.verifications, code, verificationId);
console.log('Verification successfully completed.');
} catch (error) {
console.error('An error occurred during the verification process:', error);
}
}
/**
* Prompts the user to enter their phone number.
* @return {Promise<string>} The phone number entered by the user.
*/
async promptPhoneNumber() {
const userInput = await inquirer.prompt([
{
type: 'input',
name: 'phoneNumber',
message: 'Enter the phone number you want to verify (E.164 format):',
validate: (input) => input ? true : 'Phone number cannot be empty.',
},
]);
return userInput.phoneNumber;
}
/**
* Sends a request to start SMS verification for a phone number.
* @param {VerificationsApi} verificationStarter - The VerificationsApi instance.
* @param {string} phoneNumber - The phone number to verify.
* @return {Promise<string>} The verification ID if the request is successful.
*/
async startSmsVerification(verificationStarter, phoneNumber) {
console.log(`Sending a verification request to ${phoneNumber}`);
const requestData = Verification.startVerificationHelper.buildSmsRequest(phoneNumber);
try {
const response = await verificationStarter.startSms(requestData);
if (!response.id) {
throw new Error('Verification ID is undefined.');
}
console.log(`Verification started successfully. Verification ID: ${response.id}`);
return response.id;
} catch (error) {
console.error('Failed to start SMS verification:', error);
throw error;
}
}
/**
* Prompts the user to enter the verification code they received.
* @return {Promise<string>} The verification code entered by the user.
*/
async promptSmsCode() {
const answers = await inquirer.prompt([
{
type: 'input',
name: 'code',
message: 'Enter the verification code you received:',
validate: (input) => input ? true : 'Verification code cannot be empty.',
},
]);
return answers.code;
}
/**
* Sends a request to report the verification code for a specific verification ID.
* @param { VerificationsApi } verificationReporter - The VerificationsApi instance.
* @param {string} code - The verification code to report.
* @param {string} id - The verification ID corresponding to the process.
* @return {Promise<void>}
*/
async reportSmsVerification(verificationReporter, code, id) {
const requestData = Verification.reportVerificationByIdHelper.buildSmsRequest(id, code);
try {
const response = await verificationReporter.reportSmsById(requestData);
console.log(`Verification reported successfully. Response status: ${response.status}`);
} catch (error) {
console.error('Failed to report SMS verification:', error);
throw error;
}
}
}This example highlights the following required to successfully make a Verification API call using the Sinch Node.js SDK:
When using the Sinch Node.js SDK, you initialize communication with the Sinch backend by initializing the Node.js SDK's main client class. This client allows you to access the functionality of the Sinch Node.js SDK.
To start using the SDK, you need to initialize the main client class with your credentials from your Sinch dashboard.
const {SinchClient} = require('@sinch/sdk-core');
const sinchClient = new SinchClient({
applicationKey: "YOUR_application_key",
applicationSecret: "YOUR_application_secret"
});For testing purposes on your local environment it's fine to use hardcoded values, but before deploying to production we strongly recommend using environment variables to store the credentials, as in the following example:
.env File
APPKEY="YOUR_application_key"
APPSECRET="YOUR_application_secret" app.js File
const {SinchClient} = require('@sinch/sdk-core');
const sinchClient = new SinchClient({
applicationKey: process.env.APPKEY,
applicationSecret: process.env.APPSECRET
});If you are using the Node.js SDK for multiple products that use different sets of authentication credentials, you can include all of the relevant credentials in the same configuration object, as in the following example:
const {SinchClient} = require('@sinch/sdk-core');
const sinchClient = new SinchClient({
projectId: "YOUR_project_id",
keyId: "YOUR_access_key",
keySecret: "YOUR_access_secret",
applicationKey: "YOUR_application_key",
applicationSecret: "YOUR_application_secret"
});The Sinch Node.js SDK organizes different functionalities in the Sinch product suite into domains. These domains are accessible through the client. For example, sinch.verification.[endpoint_category].[method()].
In the Sinch Node.js SDK, Verification API endpoints are accessible through the client. The naming convention of the endpoint's representation in the SDK matches the API:
verification.verificationsverification.verificationStatus
For example:
const startRequestData = verificationsHelper.buildStartSmsVerificationRequest(
"YOUR_phone_number");
const smsVerification = await sinchClient.verification.verifications.startSms(
startRequestData);
The verification.verifications category of the Node.js SDK corresponds to the verifications start endpoint. The mapping between the API operations and corresponding Node.js methods are described below:
| API operation | SDK method |
|---|---|
| Start an SMS PIN verification request | startSms() |
| Start a FlashCall verification request | startFlashCall() |
| Start a Phone Call verification request | startCallout() |
| Start a Data verification request | startSeamless() |
| Report an SMS verification PIN code by the identity of the recipient | reportSmsByIdentity() |
| Report a FlashCall verification code (CLI) by the identity of the recipient | reportFlashCallByIdentity() |
| Report a Phone Call verification code by the identity of the recipient | reportByCalloutIdentity() |
| Report an SMS verification PIN code by the ID of the verification request | reportSmsById() |
| Report a FlashCall verification code (CLI) by the ID of the verification request | reportFlashCallById() |
| Report a Phone Call verification code by the ID of the verification request | reportCalloutById() |
The verification.verificationStatus category of the Node.js SDK corresponds to the verifications endpoint. The mapping between the API operations and corresponding Node.js methods are described below:
| API operation | SDK method |
|---|---|
| Get the status of a verification by the ID of the verification request | getById() |
| Get the status of a verification by the identity of the recipient | getByIdentity() |
| Get the status of a verification by a reference value | getByReference() |
The Node.js SDK has a number of helper methods designed to aid in quickly constructing the correct request bodies for the various methods. The helper methods available and their parameters are described in the example and table below.
const requestData = verificationHelper.buildStartSmsVerificationRequest(
"YOUR_phone_number");| Request body | Helper method name | Parameters |
|---|---|---|
| Start SMS Verification | buildStartSmsVerificationRequest() |
|
| Start FlashCall Verification | buildStartFlashCallVerificationRequest() |
|
| Start Callout Verification | buildStartCalloutVerificationRequest() |
|
| Start Data Verification | buildStartSeamlessVerificationRequest() |
|
| Report SMS Verification by ID | buildReportSmsVerificationByIdRequest() |
|
| Report FlashCall Verification by ID | buildReportFlashCallVerificationByIdRequest() |
|
| Report Phone Call Verification by ID | buildReportCalloutVerificationByIdRequest() |
|
| Report SMS Verification by Identity | buildReportSmsVerificationByIdentityRequest() |
|
| Report FlashCall Verification by Identity | buildReportFlashCallVerificationByIdentityRequest() |
|
| Report Phone Call Verification by Identity | buildReportCalloutVerificationByIdentityRequest() |
|
Requests and queries made using the Node.js SDK are similar to those made using the Verification API. Path parameters, request body parameters, and query parameters that are used in the API are all passed as arguments to the corresponding Node.js method.
For example, consider this example in which the getByIdentity() method of the verification.verificationStatus class is invoked:
const response = await sinchClient.verification.verificationStatus.getByIdentity({
endpoint: 'PHONE_NUMBER',
method: 'sms'
});
url = "https://verification.api.sinch.com/verification/v1/verifications/" + method + "/number/" + endpoint
When using the Verification API, method and endpoint would be included as path parameters in the request. With the Node.js SDK, the method and endpoint parameters are used in an object passed as an argument in the getByIdentity() method.
Response fields match the API responses. They are delivered as JavaScript objects.