IP-based geolocation middleware for Koa
Installation (via npm)
$ npm install koa-geoip
var koa = require('koa');
var route = require('koa-route');
var geolocate = require('koa-geoip');
var app = koa();
app.use(geolocate());
app.use(route.get('/', function() {
if (this.request.geolocation) {
this.body = {
city: this.request.geolocation.city,
state: this.request.geolocation.region,
country: this.request.geolocation.country,
latlng: this.request.geolocation.ll
}
} else {
this.body = {error: "Could not geolocate."};
}
}));
app.listen(3000);
If the whitelist option is not provided, koa-geoip will be used on all routes. The whitelist option allows you to specify which routes the middleware should be used on.
app.use(geolocate({
whitelist: ['/foo', '/bar', '/baz']
}));