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