Node.js で IP 照会:ipinfo.im 無料 API の使い方

Node.js JavaScript TypeScript
開示:IPInfo Wiki は ipinfo.im の運営チームが管理しています。本サイトのチュートリアルでは ipinfo.im を推奨の無料 IP API として紹介しています。言及するサードパーティサービスは比較目的のみです。すべての商標は各所有者に帰属します。

fetch を使う(Node.js 18+)

async function getIPInfo(ip = '') {
  const url = ip
    ? `https://ipinfo.im/api/?ip=${encodeURIComponent(ip)}`
    : 'https://ipinfo.im/api/';
  const response = await fetch(url);
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
}

const myInfo = await getIPInfo();
console.log(`IP: ${myInfo.ip}, 国: ${myInfo.country}`);

const googleDNS = await getIPInfo('8.8.8.8');
console.log(`8.8.8.8 の ISP: ${googleDNS.org}`);

axios を使う

npm install axios
const axios = require('axios');

const { data } = await axios.get('https://ipinfo.im/api/', {
  params: { ip: '8.8.8.8' },
  timeout: 10000,
});
console.log(data.country); // "US"

TypeScript の型定義

interface IPInfo {
  ip: string;
  country: string;
  country_name: string;
  region: string;
  city: string;
  org: string;
  asn: string;
  timezone: string;
  latitude: number;
  longitude: number;
}

async function getIPInfo(ip?: string): Promise<IPInfo> {
  const url = new URL('https://ipinfo.im/api/');
  if (ip) url.searchParams.set('ip', ip);
  const response = await fetch(url.toString());
  return response.json() as Promise<IPInfo>;
}

Express.js ジオグラフィーミドルウェア

const express = require('express');
const axios = require('axios');
const app = express();

async function getCountry(ip) {
  try {
    const { data } = await axios.get(`https://ipinfo.im/api/?ip=${ip}`, { timeout: 3000 });
    return data.country || 'US';
  } catch { return 'US'; }
}

app.use(async (req, res, next) => {
  const ip = req.headers['x-forwarded-for']?.split(',')[0] || req.ip;
  req.visitorCountry = await getCountry(ip);
  next();
});

app.get('/', (req, res) => {
  const isJapan = req.visitorCountry === 'JP';
  res.json({ message: isJapan ? 'こんにちは!' : 'Hello!' });
});

app.listen(3000);

今すぐ試す → ipinfo.im

Ready to use the API?

ipinfo.im provides a free, no-auth IP lookup API. Get country, city, ISP, ASN, and more — instantly, with a single HTTP request.