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 🙏

© 2024 – Pkg Stats / Ryan Hefner

geoip-web-api

v3.0.3

Published

An AMP-GEO compatible location web API

Downloads

140

Readme

geoip-web-api

npm NPM

A web API for IP-based geolocation. Both IPv4 and IPv6 are supported. Suitable for use as an amp-geo fallback when self-hosting the AMP framework.

GeoIP database and reader

Option 1: MaxMind

Setup MaxMind's GeoIP Update program to fetch and maintain a GeoIP database. Select a free or paid database in MaxMind DB file format. A sample cron job to let geoipupdate check for database updates each day at midnight looks like:

0 0 * * * geoipupdate -f /path/to/GeoIP.conf

This module uses node-maxmind for the database reader. When the database is updated on the filesystem, the reader should automatically reload without needing to restart this module.

Option 2: IP2Location

Setup IP2Location's Download Client script to fetch and maintain a GeoIP database. Select a free or paid database in BIN file format.

Optionally, if you need subdivision support, also download the ISO 3166-2 Subdivision Code database in CSV file format.

This module uses ip2ldb-reader for the database reader. When the database is updated on the filesystem, the reader should automatically reload without needing to restart this module.

Requirements

  • Minimum supported Node.js version: 18.19.0

Installation

This module has been tested with Node.js LTS 18 and 20. Feel free to test newer versions of Node.js and let me know if you encounter compatibility issues.

Local installation

npm install geoip-web-api

Global installation

npm install -g geoip-web-api

Options

All properties are optional, provided the defaults are suitable.

{
  // {number} Log level (0:Off, 1:Error, 2:Warn, 3:Info, 4:Debug)
  "logLevel": 3,

  // {number} Port where HTTP server should listen
  "port": 3000,

  // {Object.<string, boolean>} Enabled output values (see HTTP response section)
  "enabledOutputs": {
    "country": true,
    "subdivision": true,
    "ip": false,
    "ip_version": false,
    "data": false
  },

  // {boolean} Pretty JSON output
  "prettyOutput": false,

  // {Object.<string, string|null>} Dictionary of HTTP response headers for GET requests
  "getHeaders": {},

  // {Array<string>} Array of GET paths to which HTTP server should respond
  "getPaths": ['/', '/*'],

  // {Object} Allowed cross-origin requests (CORS)
  "cors": {
    // {Array<string>} Array of allowed CORS origins (exact match)
    "origins": null,

    // {RegEx|string} RegEx test for allowed CORS origins
    "originRegEx": null
  },

  // {Object.<string, string>} MaxMind database and reader options
  "maxmind": {
    // {string} Filesystem path to MaxMind database (in MMDB format)
    "dbPath": "./GeoLite2-Country.mmdb"
  },

  // {Object.<string, string>} IP2Location database and reader options
  "ip2location": {
    // {string} Filesystem path to IP2Location database (in BIN format)
    "dbPath": "",

    // {string} Filesystem path to IP2Location ISO 3166-2 Subdivision Code database (in CSV format)
    "subdivisionCsvPath": ""
  }
}

Additional information

  • enabledOutputs - If an output is enabled but is not supported by the database, it will not be output in the final response.

  • getHeaders - Headers can be removed from the response by setting their values to null. The Content-Type and Content-Length headers are generated automatically and cannot be removed; it is possible to change the Content-Type header to another valid MIME type, but it is not possible to alter Content-Length. The ETag header additionally supports special values "strong" and "weak" to specify strong or weak ETag generation, respectively (weak by default).

  • getPaths - See Express Route paths documentation for allowed route patterns. Notice that the default configuration matches requests to any path.

  • cors.origins and cors.originRegEx - If the incoming request has an Origin HTTP header that satisfies one of these tests (is in cors.origins array or satisfies cors.originRegEx RegEx test), then an Access-Control-Allow-Origin header will be appended to the response with value equal to the Origin header. Note that if cors.originRegEx is available as a string, the RegExp object will be built with new RegExp(cors.originRegEx, 'i').

  • maxmind and ip2location - Only one of these properties should be provided. If both have valid dbPath properties, then MaxMind takes precedence.

When running this module as a command line application, these options should be saved in a JSON configuration file whose path is passed to the application with argument --config. When using this module in your own Node.js application, these options should be passed to the GeoIpWebApi constructor. See Usage section below.

Example options

{
  "logLevel": 1,
  "port": 8080,
  "enabledOutputs": {
    "ip": true,
    "data": true
  },
  "getHeaders": {
    "cache-control": "private, max-age=3600",
    "X-Content-Type-Options": "nosniff"
  },
  "getPaths": ["/geoip/?"],
  "cors": {
    "origins": ["http://example.com", "http://example.net"],
    "originRegEx": "^https://[a-z0-9\\-]+\\.example\\.(com|net)$"
  },
  "maxmind": {
    "dbPath": "/path/to/GeoLite2-City.mmdb"
  }
}

Usage

Command line interface

If installed globally:

geoip-web-api --config="/path/to/config.json"

If installed locally:

npx geoip-web-api --config="/path/to/config.json"

Node.js module

import GeoIpWebApi from 'geoip-web-api';
const options = {...};
const geoIpWebApi = new GeoIpWebApi(options);

// Start HTTP server
await geoIpWebApi.start();

// Stop HTTP server
await geoIpWebApi.stop();

// Check whether HTTP server is running
let isRunning = geoIpWebApi.isRunning();

HTTP response

The response body is application/json and contains the following data:

{
  "country": {string},      // ISO 3166-1 alpha-2 country code
  "subdivision": {string},  // Subdivision part of ISO 3166-2 country-subdivision code
  "ip": {string},           // Request IP
  "ip_version": {number}    // Request IP version (4 or 6, or 0 if IP is not valid)
  "data": {object}          // Complete database result
}

The schema for data depends on the database used.

Response conforms to AMP-GEO fallback API schema 0.2

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "country": {
      "type": "string",
      "title": "ISO 3166-1 alpha-2 (case insensitive) country code of client request",
      "default": "",
      "pattern": "^[a-zA-Z]{2}$"
    },
    "subdivision": {
      "type": "string",
      "title": "Subdivision part of ISO 3166-2 (case insensitive) country-subdivision code of client request",
      "default": "",
      "pattern": "^[a-zA-Z0-9]{1,3}$"
    }
  },
  "required": ["country"]
}

Sample response

{
  "country": "US",
  "subdivision": "CA"
}

Reverse proxy

The HTTP server (Express) in this module is designed to run behind a reverse proxy. It has been configured to trust the leftmost IP in the X-Forwarded-For request header (see documentation for trust proxy = true).

Sample Nginx location block

Listen for requests to /geoip/ and forward to localhost port 8080:

location ~ ^/geoip/ {
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_pass http://127.0.0.1:8080;
    proxy_redirect off;
}

License

MIT