diff --git a/lib/setup.php b/lib/setup.php
index a49539753ff..52a8dc3cffe 100644
--- a/lib/setup.php
+++ b/lib/setup.php
@@ -826,6 +826,19 @@ if (empty($CFG->sessiontimeout)) {
 if (empty($CFG->sessiontimeoutwarning)) {
     $CFG->sessiontimeoutwarning = 20 * 60;
 }
+
+// Allow plugins to callback just before the session is started.
+$pluginswithfunction = get_plugins_with_function('before_session_start', 'lib.php');
+foreach ($pluginswithfunction as $plugins) {
+    foreach ($plugins as $function) {
+        try {
+            $function();
+        } catch (Throwable $e) {
+            debugging("Exception calling '$function'", DEBUG_DEVELOPER, $e->getTrace());
+        }
+    }
+}
+
 \core\session\manager::start();
 
 if (!empty($CFG->proxylogunsafe) || !empty($CFG->proxyfixunsafe)) {
diff --git a/lib/upgrade.txt b/lib/upgrade.txt
index 3f69a5e0cee..f76a31e7fc5 100644
--- a/lib/upgrade.txt
+++ b/lib/upgrade.txt
@@ -55,6 +55,7 @@ Declaration is as follow:
   return the class name.
 * The function get_module_metadata() has been finally deprecated and can not be used anymore.
 * New DML driver method `$DB->sql_order_by_null` for sorting nulls sort nulls first when ascending and last when descending.
+* Allow plugins to callback on all pages just prior to the session start.
 
 === 4.0 ===