libphonenumber-js
libphonenumber-js is a JavaScript and TypeScript library designed for parsing, formatting, and validating international phone numbers. It serves as a significantly smaller and simpler rewrite of Google's original `libphonenumber` library. Currently at version 1.12.41, this package prioritizes a reduced bundle size (approximately 145 kB vs. 550 kB for the Google port) by focusing solely on personal phone numbers. It deliberately omits support for less common categories such as emergency numbers, short codes, numbers prefixed with `*`, Australian `13`-smart numbers, and alphabetic phone numbers like `1-800-GOT-MILK`. The library ships with comprehensive TypeScript definitions and uniquely offers functionality to search for phone numbers within text, a feature absent in Google's official JavaScript port. While a specific release cadence isn't detailed, the version history suggests active and ongoing development.
Common errors
-
TypeError: Cannot read properties of undefined (reading 'country')
cause `parsePhoneNumber` returned `undefined` because the input string was not a valid or recognizable phone number.fixAlways check if the result of `parsePhoneNumber(string)` is not `undefined` before attempting to access its properties. For example: `const num = parsePhoneNumber(str); if (num) { console.log(num.country); }`. -
TS2307: Cannot find module 'libphonenumber-js' or its corresponding type declarations.
cause TypeScript compiler cannot locate the package or its declaration files (`.d.ts`).fixEnsure `libphonenumber-js` is installed (`npm install libphonenumber-js`) and that your `tsconfig.json` includes `node_modules/@types` or has `"moduleResolution": "node"` set correctly. -
ReferenceError: require is not defined
cause Attempting to use `require()` in an ES Module context (e.g., a modern Node.js project or browser module) without proper transpilation or configuration.fixUse ESM `import` statements instead: `import { parsePhoneNumber } from 'libphonenumber-js';`. If using CommonJS, ensure your file is a `.js` file or configured as such, and `require()` is appropriate for your environment.
Warnings
- gotcha libphonenumber-js deliberately omits support for several 'special' phone number categories, including emergency numbers (e.g., 911), short codes, numbers starting with `*`, Australian `13`-smart numbers, and alphabetic numbers (e.g., 1-800-GOT-MILK). It focuses exclusively on personal phone numbers to achieve a smaller bundle size. If your application requires handling these specific types, this library might not be suitable, and you may need Google's full `libphonenumber` port.
- gotcha The `parsePhoneNumber` function returns `undefined` if the input string cannot be parsed into a valid `PhoneNumber` object. Always check the return value before attempting to access properties like `country`, `nationalNumber`, or `format()`, otherwise, it may lead to runtime errors.
- gotcha When formatting numbers, ensure you provide a valid format string (e.g., 'E.164', 'INTERNATIONAL', 'NATIONAL'). Using an unsupported format string will result in an error or unexpected output. Refer to the documentation for supported formats.
Install
-
npm install libphonenumber-js -
yarn add libphonenumber-js -
pnpm add libphonenumber-js
Imports
- parsePhoneNumber
const parsePhoneNumber = require('libphonenumber-js');import { parsePhoneNumber } from 'libphonenumber-js'; - formatPhoneNumber
import formatPhoneNumber from 'libphonenumber-js/formatPhoneNumber';
import { formatPhoneNumber } from 'libphonenumber-js'; - isValidPhoneNumber
import { validatePhoneNumber } from 'libphonenumber-js';import { isValidPhoneNumber } from 'libphonenumber-js'; - getCountryCallingCode
import { getCallingCode } from 'libphonenumber-js';import { getCountryCallingCode } from 'libphonenumber-js';
Quickstart
import { parsePhoneNumber, formatPhoneNumber, isValidPhoneNumber, getCountryCallingCode } from 'libphonenumber-js';
const phoneNumberString = '+12133734253';
const countryCode = 'US';
// Parse a phone number
const phoneNumber = parsePhoneNumber(phoneNumberString);
if (phoneNumber) {
console.log(`Original number: ${phoneNumberString}`);
console.log(`Country: ${phoneNumber.country}`);
console.log(`National number: ${phoneNumber.nationalNumber}`);
// Format the number in various ways
console.log(`Formatted E.164: ${phoneNumber.format('E.164')}`);
console.log(`Formatted International: ${phoneNumber.format('INTERNATIONAL')}`);
console.log(`Formatted National: ${phoneNumber.format('NATIONAL')}`);
// Check validity
const valid = isValidPhoneNumber(phoneNumberString, countryCode);
console.log(`Is valid for ${countryCode}? ${valid}`);
// Get country calling code
const callingCode = getCountryCallingCode(countryCode);
console.log(`Calling code for ${countryCode}: +${callingCode}`);
} else {
console.log(`Could not parse phone number: ${phoneNumberString}`);
}
// Example of an invalid number
const invalidNumber = '555-123-INVALID';
const isValid = isValidPhoneNumber(invalidNumber, countryCode);
console.log(`Is '${invalidNumber}' valid for ${countryCode}? ${isValid}`);