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

rpmcmurphy's avatar

Standard way to store session data of a visitor on system built with Laravel API

I have built an API with Laravel + Sanctum consumed by a React Native app. I need to store the user's country, regardless they are logged-in or not. Will have to check the visitor's country on each request to send them country-specific products in response, need the user be identifiable like a web session.

How/where to store the info as session is not available or a viable option to store the data on the server with regard to API?

I know it's not a Laravel specific question but I could not find any standard answer online.

0 likes
4 replies
rpmcmurphy's avatar

@citricguy Ok. I am new to this specific issue. So basically I will have to identify the visitor's country from the IP, store it in the React Native app, and then attach it on each request to the server for preparing visitor's country-specific response. I guess that is the standard way to deal with a situation like this? It feels cumbersome to send the country info with each request. Was wondering if there is a session-like solution for when request is for API.

citricguy's avatar

@rpmcmurphy

If you're using Sanctum with API Auth (https://laravel.com/docs/9.x/sanctum#spa-authentication) you should have access to sessions by default.

Here is how you would store data in the session in this case: https://laravel.com/docs/9.x/session#storing-data

// Via a request instance...
$request->session()->put('key', 'value');
 
// Via the global "session" helper...
session(['key' => 'value']);

How are you getting the users country? By IP, using a form or some other way?

If you're getting the country in an automated way during each request, I would just skip the sessions/cookies/etc all together. If it's always available, there is no reason to store it. For example if you're using CloudFlare you could use this:

$country_code = $_SERVER["HTTP_CF_IPCOUNTRY"];

Obviously that might not work if you're getting the country data elsewhere or you're not using CF.

1 like
rpmcmurphy's avatar

@citricguy I went with storing the country in the client's phone and attaching it with the endpoints which will need the info. Made a custom endpoint to get the country while the app is loading.

I was more eager to a stateless/session-less solution since API isn't supposed to use session.

Please or to participate in this conversation.