DEV Community

Leonidas Costas
Leonidas Costas

Posted on • Edited on • Originally published at fast-modular-project.com

User's location by browser's permission or IP address

This module allows you to locate your user either by navigator permission, either by IP address.

What does it bring?

  • (For the browser solution) Navigator permission ask
  • (For the browser solution) Navigator coordinate ask
  • (For the IP solution) Retrieving of IP address in the backend
  • (For the IP solution) Calls to ip-api.com service in order to get the location of a specific IP
  • 3 hours of work saved

Prerequisites

To make this module work, a 13€/month subscription to ip-api service is needed.

Retrieving user’s location with it’s IP address and IP-API

Step 1

We’ll store user’s IP address present in the « x-forwarded-for » field from the HTTP header of its request.

request.ipAddress = request?.headers['x-forwarded-for']?.split(',')[0] || request.connection.remoteAddress
Enter fullscreen mode Exit fullscreen mode

This ip address is now accessible through request.ipAddress, but we’ll create a custom decorator to ease the retrieve of it.

Step 2

Create a custom decorator to get the ipAdress using a decorator instead of accessing directly request.ipAddress:

import { createParamDecorator, ExecutionContext } from '@nestjs/common';

export const IpAddress = createParamDecorator(
    (data: unknown, ctx: ExecutionContext) => {
        const request = ctx.switchToHttp().getRequest();
        return request.ipAddress;
    },
);
Enter fullscreen mode Exit fullscreen mode

Step 3

Create a Controller that uses this custom decorator

Step 4

In your controller, use your service that gets users latitude and longitude from it’s IP (using ip-api service).

        const headers = {
            Accept: "application/json",
            "Content-Type": "application/json"
        };
        const res = await fetch(`https://pro.ip-api.com/json/${ip}?key=[ENTER YOUR KEY HERE]`, {
            method: "get",
            headers
        });
        const json = await res.json();
        return {
            latitude: json.lat,
            longitude: json.lon
        }
Enter fullscreen mode Exit fullscreen mode

Retrieving user’s location with navigator permissions

Step 1

You can use the navigator web api standards to tell the browser to ask for the user to authorize thee usage of it’s location.

export const getGeolocationPermission = async () => {
    const permission = await navigator.permissions.query({
        name: "geolocation"
    });
    return permission.state;
};
Enter fullscreen mode Exit fullscreen mode

Step 2

If the user accepted the prompt, you’ll be able to ask the navigator for its latitude and longitude with the navigator.geolocation.getCurrentPosition() function.

The entire source code and a distance computation between two locations are available here.

You are now free to use those two methods as a way to retrieve user’s location:

  • either thanks to it’s IP address
  • either through it’s browser

Conclusion

I hope this module will help you saving some time while trying to implement a system to retrieve the location of your users.
If you have any question, I'll be present as usual in the comment section !

Links:

  • The platform sharing the starter and it's modules : Fast Modular Project
  • User's location module open source code here. Do not hesitate to pin and like if you appreciated the article ❤️

Top comments (0)