
Validate Phone Numbers With Firebase and Vonage Identity Insights
Temps de lecture : 5 minutes
Introduction
This tutorial shows how to build a demonstration serverless solution using Firebase Callable Functions and the Vonage Identity Insights API, which automatically attempts to cleanse user input. You don't have to worry if your users submit numbers mixed with dashes, spaces, or alphanumeric characters. The API will do its best to parse and validate the phone number.
Validating phone numbers and making sure they're cleaned and correctly formatted is a must. In the demonstration we will build, you can input a phone number and use the Vonage Identity Insights API to return the format validity, international format, country code, current and original carrier name, and network type.
Phone Number Validation
Prerequisites
Make sure you have:
A Google account with Firebase with Blaze billing enabled (required for Node.js functions).
The Firebase CLI installed:
npm install -g firebase-toolsOuvrez votre Page des paramètres de l'API pour accéder à votre clé et à votre secret API de Vonage, qui sont tous deux affichés comme indiqué dans la capture d'écran ci-dessous. La clé API se trouve en haut de la page, et pour accéder à votre secret API, veuillez vous référer à la sous-section "Secret du compte".
Remarque : si vous ne vous souvenez plus de votre secret API précédemment créé, cliquez sur "+ Créer un nouveau secret" et sauvegardez-le en toute sécurité.

File Structure
The sample code for this project follows the structure below.
my-firebase-project/
├── firebase.json
├── functions/
│ ├── index.js
│ └── package.json
└── public/
└── index.htmlLet's associate this project directory with a Firebase project. You can create multiple project aliases by running firebase use --add.
Initialize the Firebase Function
Initialize Firebase Functions in your project directory:
firebase init functionsSelect JavaScript when prompted. There's also the option to choose TypeScript and Python. Next, navigate into your functions folder and install the Vonage Server SDK:
cd functions
npm install @vonage/server-sdkPour créer une application, allez à la page Créer une application sur le tableau de bord de Vonage, et définissez un nom pour votre application.
Si vous avez l'intention d'utiliser une API qui utilise des Webhooks, vous aurez besoin d'une clé privée. Cliquez sur "Générer une clé publique et privée", votre téléchargement devrait démarrer automatiquement. Conservez-la en lieu sûr ; cette clé ne peut pas être retéléchargée si elle est perdue. Elle suivra la convention de nommage suivante private_<votre identifiant d'application>.key. Cette clé peut maintenant être utilisée pour authentifier les appels à l'API. Remarque : votre clé ne fonctionnera pas tant que votre application n'aura pas été sauvegardée.
Choisissez les fonctionnalités dont vous avez besoin (par exemple, Voice, Messages, RTC, etc.) et fournissez les webhooks requis (par exemple, URL d'événement, URL de réponse ou URL de message entrant). Ces éléments seront décrits dans le tutoriel.
Pour sauvegarder et déployer, cliquez sur "Générer une nouvelle application" pour finaliser la configuration. Votre application est maintenant prête à être utilisée avec les API de Vonage.
The Vonage Identity Insights API uses JWTs, so we need to securely store our Application ID and Private Key. We'll use Firebase's built-in Secret Manager so these values never live in our source code:
firebase functions:secrets:set VONAGE_APPLICATION_ID
It will then prompt you to add the Vonage Application ID.
firebase functions:secrets:set VONAGE_PRIVATE_KEYIt will then prompt you to add the Vonage Private Key associated with your application ID.
Understand the Backend Logic
We'll use the Vonage Identity Insights API. Firebase Callable Functions handle CORS and authentication automatically, allowing your frontend to call them. You can follow along with the full index.js file in the sample repository.
We initialize the Vonage client. Identity Insights requires JWT authentication. We're initializing the client using the secrets we stored earlier.
const vonage = new Vonage({
applicationId: process.env.VONAGE_APPLICATION_ID,
privateKey: process.env.VONAGE_PRIVATE_KEY.replace(/\n/g, '
')
});
exports.validatePhone = onCall(async (request) => {
const phoneNumber = request.data.phone;Note: The
.replace(/\n/g, '\n')is a fix for handling newline formatting issues when using Firebase Secret Manager.
We request both the format and current_carrier Identity Insights API insights to know not just if the phone number is technically valid, but also whether it's a mobile line we can actually send an SMS to.
if (!phoneNumber) {
throw new HttpsError('invalid-argument', 'Phone number is required.');
}
try {
// Call the Vonage Identity Insights API
// We request both the 'format' and 'current_carrier' datasets
const response = await vonage.identityInsights.getInsights({
phone_number: phoneNumber,
insights: {
format: {},
current_carrier: {}
}
});
const formatData = response.format || {};
const carrierData = response.current_carrier || {};We package everything up and send a response object back to our frontend, so it doesn't have to parse raw API responses.
return {
valid: formatData.is_format_valid === true,
country: formatData.country_code || 'Unknown',
formattedNumber: formatData.number_international || phoneNumber,
carrier: carrierData.name || 'Unknown',
networkType: carrierData.network_type || 'Unknown'
};
} catch (error) {
console.error('Validation error:', error);
throw new HttpsError('internal', 'Failed to validate phone number.');
}
});
Deploy Your Function to the Cloud
Run the following command in your terminal from the root directory of your project to deploy your function to Firebase:
firebase deploy --only functionsDuring the deployment process, the Firebase CLI will package your function source code, upload it to Cloud Functions, and set up the necessary Cloud Secret Manager permissions for your configured secrets. You will see progress logs in your terminal detailing each step, ending with a success message and the URL endpoint for your deployed function.
To verify that the deployment was successful, open the Firebase Console, select your project, and navigate to the Functions section. You should see validatePhone listed under the dashboard along with its status, runtime, and trigger type.
Connect the Frontend
Because we used a Callable Function, invoking this from your web app is clean. You don't need to mess with fetch requests, HTTP headers, or parsing JSON.
Create an index.html file and paste the code, remembering to swap in your Firebase project configuration.
// TODO: Replace with your Firebase project configuration
const firebaseConfig = {
projectId: "YOUR_PROJECT_ID",
apiKey: "YOUR_WEB_API_KEY"
};
Test It Out
Open the HTML file in your browser, type a phone number in the input field including the country code, and hit Validate Number. You'll get information about the phone number, just as shown in the image at the beginning of this tutorial.
Conclusion
The Identity Insights API helps your application accept only real, routable phone numbers while gathering valuable carrier intelligence. To learn more about what data you can extract from phone numbers, check out the Vonage Identity Insights API documentation.
Vous souhaitez en savoir plus, rester en contact ou partager ce que vous êtes en train de créer ?
Continuez à apprendre
Découvrez des cas d'utilisation et des parcours d'apprentissage structurés dans le Centre de formation Vonage
Regardez les tutoriels sur notre chaîne YouTube Vonage Developer
Restez connecté
Abonnez-vous à la newsletter des développeurs Vonage
Suivez-nous sur X pour rester informé
Retrouvez-nous sur LinkedIn
Aidez-nous à améliorer l'expérience des développeurs en remplissant notre formulaire de commentaires « Voice of the Developer »