npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@eusilvio/cep-lookup

v2.1.2

Published

A modern, flexible, and agnostic CEP lookup library written in TypeScript.

Downloads

57

Readme

@eusilvio/cep-lookup

NPM Version NPM Unpacked Size Build Status License: MIT

A modern, flexible, and agnostic CEP (Brazilian postal code) lookup library written in TypeScript.

About

@eusilvio/cep-lookup was created to solve address lookup from a CEP in a different way. Instead of relying on a single data source, it queries multiple services simultaneously and returns the response from the fastest one.

Its agnostic design allows it to be used in any JavaScript environment with any HTTP client, and its powerful "mapper" system allows you to format the data output exactly as you need.

Key Features

  • Multiple Providers (Race Strategy): Queries multiple CEP APIs at the same time and uses the first valid response.
  • Class-Based API: Create a reusable instance with your settings.
  • Bulk Lookups: Efficiently look up multiple CEPs with a single method call.
  • Customizable Return Format: Provide a mapper function to transform the address data into any format your application needs.
  • HTTP Client Agnostic: You provide the fetch function, giving you full control over the requests. Defaults to global fetch if not provided.
  • Modular and Extensible Architecture: Adding a new CEP data source is trivial.
  • Fully Typed: Developed with TypeScript to ensure type safety and a great developer experience.
  • Caching: Built-in support for caching to avoid repeated requests for the same CEP.

Installation

npm install @eusilvio/cep-lookup

How to Use

@eusilvio/cep-lookup is designed to be straightforward. You create a reusable instance of the CepLookup class with your desired settings and use its methods to look up single or multiple CEPs. The library also includes a simple in-memory cache to avoid repeated requests, which you can use or replace with your own implementation.

Example 1: Basic Usage

import { CepLookup, Address } from "@eusilvio/cep-lookup";
import {
  viaCepProvider,
  brasilApiProvider,
} from "@eusilvio/cep-lookup/providers";

// 1. Create an instance of CepLookup
const cepLookup = new CepLookup({
  providers: [viaCepProvider, brasilApiProvider],
});

// 2. Look up a CEP
cepLookup.lookup("01001-000").then((address: Address) => {
  console.log("Address found:", address);
  // Output:
  // {
  //   cep: '01001-000',
  //   state: 'SP',
  //   city: 'São Paulo',
  //   neighborhood: 'Sé',
  //   street: 'Praça da Sé',
  //   service: 'ViaCEP'
  // }
});

Example 2: Custom Return with mapper

import { CepLookup, Address } from "@eusilvio/cep-lookup";
import { viaCepProvider } from "@eusilvio/cep-lookup/providers";

const cepLookup = new CepLookup({
  providers: [viaCepProvider],
});

// 1. Define your "mapper" function
interface CustomAddress {
  postalCode: string;
  fullAddress: string;
  source: string;
}

const myMapper = (address: Address): CustomAddress => {
  return {
    postalCode: address.cep,
    fullAddress: `${address.street}, ${address.neighborhood} - ${address.city}/${address.state}`,
    source: address.service,
  };
};

// 2. Look up a CEP with the mapper
cepLookup.lookup("01001-000", myMapper).then((customAddress: CustomAddress) => {
  console.log("Address found (custom format):", customAddress);
  // Output:
  // {
  //   postalCode: '01001-000',
  //   fullAddress: 'Praça da Sé, Sé - São Paulo/SP',
  //   source: 'ViaCEP'
  // }
});

Example 3: Bulk CEP Lookup

For scenarios where you need to query multiple CEPs at once, you can use the lookupCeps method. It processes the CEPs in parallel with a configurable concurrency limit to avoid overwhelming the providers.

import { CepLookup, BulkCepResult } from "@eusilvio/cep-lookup";
import {
  viaCepProvider,
  brasilApiProvider,
} from "@eusilvio/cep-lookup/providers";

const cepsToLookup = ["01001-000", "99999-999", "04538-132"];

// 1. Create an instance with your settings
const cepLookup = new CepLookup({
  providers: [viaCepProvider, brasilApiProvider],
});

// 2. Look up multiple CEPs
cepLookup.lookupCeps(cepsToLookup, { concurrency: 2 }).then((results: BulkCepResult[]) => {
  console.log("Bulk lookup results:", results);
  // Output:
  // [
  //   {
  //     cep: '01001-000',
  //     data: { cep: '01001-000', state: 'SP', city: 'São Paulo', ... },
  //     provider: 'ViaCEP'
  //   },
  //   {
  //     cep: '99999-999',
  //     data: null,
  //     error: [Error: All providers failed to find the CEP]
  //   },
  //   {
  //     cep: '04538-132',
  //     data: { cep: '04538-132', state: 'SP', city: 'São Paulo', ... },
  //     provider: 'BrasilAPI'
  //   }
  // ]
});

API

new CepLookup(options)

Creates a new CepLookup instance.

  • options: A configuration object.
    • providers (Provider[], required): An array of providers that will be queried.
    • fetcher (Fetcher, optional): Your asynchronous function that fetches data from a URL. Defaults to global fetch if not provided.
    • cache (Cache, optional): An instance of a cache that implements the Cache interface. Use InMemoryCache for a simple in-memory cache.
    • rateLimit ({ requests: number, per: number }, optional): Configures an in-memory rate limiter (e.g., { requests: 10, per: 1000 } for 10 requests per second).

cepLookup.lookup<T = Address>(cep, mapper?): Promise<T>

Returns a Promise that resolves to the address in the default format (Address) or in the custom format T if a mapper is provided.

  • cep (string, required): The CEP to be queried.
  • mapper ((address: Address) => T, optional): A function that receives the default Address object and transforms it into a new format T.

cepLookup.lookupCeps(ceps, options?): Promise<BulkCepResult[]>

Looks up multiple CEPs in bulk. Returns a Promise that resolves to an array of BulkCepResult objects, one for each queried CEP.

  • ceps (string[], required): An array of CEP strings to be queried.
  • options (object, optional): An options object.
    • concurrency (number): The number of parallel requests to make. Defaults to 5.

Note on Deprecated Functions: Standalone lookupCep and lookupCeps functions are deprecated and will be removed in a future version. Please use the methods on a CepLookup instance instead.

Observability Events API

Version 2.0.0 introduced an event-based API to monitor the library's behavior. You can listen to events to gather metrics on provider performance, latency, and errors.

const cepLookup = new CepLookup({ providers: [...] });

// Fired for each successful provider response
cepLookup.on('success', ({ provider, cep, duration }) => {
  console.log(`[${provider}] Success for CEP ${cep} in ${duration}ms`);
  // myMetrics.timing('cep.latency', duration, { provider });
});

// Fired for each failed provider response
cepLookup.on('failure', ({ provider, cep, error }) => {
  console.error(`[${provider}] Failure for CEP ${cep}: ${error.message}`);
  // myMetrics.increment('cep.failure', { provider });
});

// Fired when a CEP is resolved from the cache
cepLookup.on('cache:hit', ({ cep }) => {
  console.log(`[Cache] CEP ${cep} found in cache.`);
  // myMetrics.increment('cep.cache_hit');
});

// The lookup call remains the same
cepLookup.lookup("01001-000");

Examples

You can find more detailed examples in the examples/ directory:

  • Basic Usage: examples/example.ts
  • Bulk Lookup: examples/bulk-example.ts
  • Custom Provider: examples/custom-provider-example.ts
  • Node.js Usage: examples/node-example.ts
  • React Component: examples/react-example.tsx
  • React Hook: examples/react-hook-example.ts
  • Angular Component/Service: examples/angular-example.ts
  • Cache Usage: examples/cache-example.ts

Creating a Custom Provider

Your custom provider must always transform the API response to the library's default Address interface. The user's mapper will handle the final customization.

import { Provider, Address } from "@eusilvio/cep-lookup";

const myCustomProvider: Provider = {
  name: "MyCustomAPI",
  buildUrl: (cep: string) => `https://myapi.com/cep/${cep}`,
  transform: (response: any): Address => {
    // Transforms the response from "MyCustomAPI" to the "Address" format
    return {
      cep: response.postal_code,
      state: response.data.state_short,
      city: response.data.city_name,
      neighborhood: response.data.neighborhood,
      street: response.data.street_name,
      service: "MyCustomAPI",
    };
  },
};

Running Tests

npm test

License

Distributed under the MIT License.