Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rpmcmurphy's avatar

Managing user's stateful (session) data when site is accessed through API from mobile app

I have a web app with both web and api routes configured, for mobile application and the website. For API auth, using Sanctum.

The issue is, I need access to the user's location from each request to serve localized data, local products basically. For web, I am using GeoIP package, getting the country and storing it in the user's session. But for the API, I don't have access to the session. What can I do to store the user's IP + Country and then access these info on subsequent requests to serve him/her with the contents I want? Not going to use session as using session in API defeats the whole purpose of Sanctum.

This is how I am managing the web part, with a custom middleware-

public function handle(Request $request, Closure $next)
    {
        $userIp = $request->ip();
        $geo = GeoIP::getLocation($userIp);
        $userCountry = $geo['country'];
        $supported_countries = Country::pluck('country_name')->toArray();

        if (in_array($userCountry, $supported_countries)) {
            session()->put('user_country', $userCountry);
            session()->save();
        } else {
            session()->put('user_country', 'UK');
            session()->save();
        }

        return $next($request);
    }
Would like to store similar info for the API too and access them globally through an identifier or something. The possible solutions I am wondering about are-
  1. Make a custom table in the database and track the user requests generating random code as unique identifier, which is not easy I would guess.

  2. Send the user his/her location data parsing from IP and storing it on the client side, attaching it with each request.

  3. Asking the user provide his location at the beginning of the app loading screens, and then sending it back to the server fro local storage.

The main issue are the guest users. I am already collecting country of the user when registering them. What is the standard way to deal with this situation. Some help would be much appreciated. Thanks in advance.

0 likes
0 replies

Please or to participate in this conversation.