We want to add an API call when we load a page to get an external value, which will be added to our session variables. However, after we do that, logged-in users find that they have been logged out. It seems like adding the new field wipes out the user name.
Here’s the code:
<?php
$session = JFactory::getSession();
if (!$session->get('test_value'))
{
$session->set('test_value', "something");
}?>
I’ve tried loading the code in different places, but it doesn’t seem to make a difference.
Your users are getting logged out because you’re accessing or modifying the session before Joomla fully initializes it, or you’re creating a second session unintentionally.
Why This Happens:
If your code runs before Joomla finishes user authentication, modifying the session can wipe out user session data, including login info.
This often happens if you run session code in a template, a system plugin at the wrong event, or before onAfterInitialise.
Solution:
Only modify the session after Joomla finishes initializing.
Best practice: Use a System Plugin and place your logic in the onAfterRoute or onAfterInitialise event:
Example Plugin Code (System Plugin):
public function onAfterRoute()
{
$session = \Joomla\CMS\Factory::getSession();
if (!$session->get('test_value')) {
// Call your external API here if needed
$session->set('test_value', 'something');
}
}
This ensures the session is already tied to the logged-in user.
Never modify session data in a layout/template or too early in Joomla’s boot sequence.
Summary:
Use onAfterRoute or later events.
Don’t touch session in templates or too early in Joomla’s loading.
Use Joomla\CMS\Factory::getSession() in Joomla 4+ for best compatibility.
Let me know where you’re placing this code and I can tell you if it’s too early.