Index: client/src/contexts/AuthContext.jsx
===================================================================
--- client/src/contexts/AuthContext.jsx	(revision 547b5ed29cc465c87c136d82d3b090dc3a6f52c3)
+++ client/src/contexts/AuthContext.jsx	(revision 280e995a180ab83674cb114a6e5d0ba9c753ede8)
@@ -1,6 +1,12 @@
-import { createContext, useContext, useState, useEffect, useRef } from 'react';
+import {
+  createContext,
+  useContext,
+  useState,
+  useEffect,
+  useRef,
+  useCallback,
+} from 'react';
 import { useNavigate } from 'react-router-dom';
 import { createClient } from '@supabase/supabase-js';
-import { useCallback } from 'react';
 
 const supabaseUrl = import.meta.env.VITE_SUPABASE_URL;
@@ -12,62 +18,129 @@
     storageKey: 'supabase-auth-token',
     storage: localStorage,
+    autoRefreshToken: true,
   },
 });
 
-// Create the context
 export const AuthContext = createContext();
 
-// Custom hook to use the auth context
 export const useAuth = () => useContext(AuthContext);
 
-// Provider component
 export const AuthProvider = ({ children }) => {
   const [user, setUser] = useState(null);
   const [loading, setLoading] = useState(true);
-  const inactivityTimeoutRef = useRef(null); // Use ref instead of state
+  const [isLoggingOut, setIsLoggingOut] = useState(false);
+  // Use refs for mutable values that shouldn't trigger re-renders
+  const inactivityTimeoutRef = useRef(null);
+  const isActiveRef = useRef(false);
+  const userRef = useRef(null); // Store user ID in ref to avoid dependency cycle
   const navigate = useNavigate();
 
-  // Inactivity duration in milliseconds (30 minutes)
-  const INACTIVITY_TIMEOUT = 20 * 60 * 1000;
-
-  // Function to handle logout - use useCallback to prevent recreation on every render
+  // 2 minutes timeout (in milliseconds)
+  const INACTIVITY_TIMEOUT = 2 * 60 * 1000;
+
+  // Update userRef when user changes
+  useEffect(() => {
+    userRef.current = user?.id || null;
+
+    // Debug log only once when user changes
+    if (import.meta.env.DEV && user) {
+      console.log(
+        `Inactivity timeout set for ${INACTIVITY_TIMEOUT / 1000} seconds`
+      );
+    }
+  }, [user, INACTIVITY_TIMEOUT]);
+
+  // Function to logout - using userRef instead of user state
   const logout = useCallback(async () => {
     try {
-      await supabase.auth.signOut();
+      console.log(
+        'Logging out user due to:',
+        isActiveRef.current ? 'manual logout' : 'inactivity'
+      );
+      setIsLoggingOut(true);
+
+      // Clear the timeout to prevent duplicate logouts
+      if (inactivityTimeoutRef.current) {
+        clearTimeout(inactivityTimeoutRef.current);
+        inactivityTimeoutRef.current = null;
+      }
+
+      // Remove data first to prevent race conditions
+      localStorage.removeItem('jwt');
       localStorage.removeItem('user');
       localStorage.removeItem('lastActivityTimestamp');
-      localStorage.removeItem('jwt');
-      sessionStorage.clear();
+
+      // Call signOut only once
+      await supabase.auth.signOut();
+
+      // Update state
       setUser(null);
-      navigate('/login?reason=inactivity');
+      userRef.current = null;
+
+      // Navigate to home page
+      navigate('/');
+
+      // Reset logout flag after navigation
+      setTimeout(() => {
+        setIsLoggingOut(false);
+      }, 1000);
     } catch (error) {
       console.error('Error during logout:', error);
-    }
-  }, [navigate]);
-
+      setIsLoggingOut(false);
+    }
+  }, [navigate]); // Remove user dependency
+
+  // Function to reset inactivity timer - using userRef instead of user state
+  const resetInactivityTimer = useCallback(() => {
+    isActiveRef.current = true;
+
+    // Clear existing timeout
+    if (inactivityTimeoutRef.current) {
+      clearTimeout(inactivityTimeoutRef.current);
+      inactivityTimeoutRef.current = null;
+    }
+
+    // Only set new timeout if we have a user (using ref)
+    if (userRef.current) {
+      // Update timestamp in localStorage, but limit frequency to avoid excessive writes
+      const now = Date.now();
+      const lastStoredTime = parseInt(
+        localStorage.getItem('lastActivityTimestamp') || '0'
+      );
+      if (now - lastStoredTime > 10000) {
+        // Only update every 10 seconds
+        localStorage.setItem('lastActivityTimestamp', now.toString());
+
+        // Debug log with reduced frequency
+        if (import.meta.env.DEV) {
+          const currentTime = new Date().toLocaleTimeString();
+          console.debug(
+            `[${currentTime}] Activity detected, resetting timeout`
+          );
+        }
+      }
+
+      inactivityTimeoutRef.current = setTimeout(() => {
+        isActiveRef.current = false;
+        console.warn('User inactive for 2 minutes, logging out...');
+        logout();
+      }, INACTIVITY_TIMEOUT);
+    }
+  }, [logout, INACTIVITY_TIMEOUT]); // Remove user dependency
+
+  // Initial session check
   useEffect(() => {
     const checkStaleSession = () => {
-      // Check for user in localStorage
       const storedUser = localStorage.getItem('user');
       const lastActivity = localStorage.getItem('lastActivityTimestamp');
 
-      console.log('Initial session check:', {
-        hasStoredUser: !!storedUser,
-        lastActivity: lastActivity
-          ? new Date(parseInt(lastActivity)).toLocaleString()
-          : null,
-      });
-
       if (storedUser && lastActivity) {
-        // If we have both user and timestamp, check if session is stale
         const inactiveTime = Date.now() - parseInt(lastActivity);
+
         if (inactiveTime > INACTIVITY_TIMEOUT) {
           console.log('Found stale session - logging out');
-          // Clear everything without setting user state (will happen in initializeAuth)
           localStorage.removeItem('user');
           localStorage.removeItem('lastActivityTimestamp');
-          supabase.auth
-            .signOut()
-            .catch((err) => console.error('Error signing out:', err));
+          supabase.auth.signOut();
           navigate('/');
         }
@@ -75,25 +148,17 @@
     };
 
-    // Run this check immediately
     checkStaleSession();
-  }, []);
-
-  // Function to reset the inactivity timer - use useCallback
-  const resetInactivityTimer = useCallback(() => {
-    if (inactivityTimeoutRef.current) {
-      clearTimeout(inactivityTimeoutRef.current);
-    }
-
-    // Only set timer if user is logged in
-    if (user) {
-      inactivityTimeoutRef.current = setTimeout(() => {
-        console.log('User inactive for too long, logging out...');
-        logout();
-      }, INACTIVITY_TIMEOUT);
-    }
-  }, [logout, INACTIVITY_TIMEOUT, user]);
-
-  // Set up event listeners for user activity
-  useEffect(() => {
+  }, [navigate, INACTIVITY_TIMEOUT]);
+
+  // Set up activity listeners - use a stable reference to avoid recreation
+  useEffect(() => {
+    // Only set up listeners if we have a user
+    if (!userRef.current) return;
+
+    // Debug log only once when setting up listeners
+    if (import.meta.env.DEV) {
+      console.log('Setting up activity listeners for inactivity timeout');
+    }
+
     const activityEvents = [
       'mousedown',
@@ -102,11 +167,17 @@
       'scroll',
       'touchstart',
+      'click',
     ];
 
+    // Make sure to debounce the activity handler to prevent excessive timer resets
+    let debounceTimeout;
+    const DEBOUNCE_DELAY = 1000; // 1 second
+
     const handleActivity = () => {
-      if (user) {
-        localStorage.setItem('lastActivityTimestamp', Date.now().toString());
+      if (debounceTimeout) clearTimeout(debounceTimeout);
+
+      debounceTimeout = setTimeout(() => {
         resetInactivityTimer();
-      }
+      }, DEBOUNCE_DELAY);
     };
 
@@ -116,41 +187,42 @@
     });
 
-    // Initial timer setup if user exists
-    if (user) {
-      resetInactivityTimer();
-    }
+    // Set initial timer when mounting
+    resetInactivityTimer();
+
+    // Visibility change detection (tab switching)
+    const handleVisibilityChange = () => {
+      if (document.visibilityState === 'visible') {
+        resetInactivityTimer();
+      }
+    };
+
+    document.addEventListener('visibilitychange', handleVisibilityChange);
 
     // Cleanup
     return () => {
-      if (inactivityTimeoutRef.current) {
-        clearTimeout(inactivityTimeoutRef.current);
-      }
+      if (debounceTimeout) clearTimeout(debounceTimeout);
 
       activityEvents.forEach((event) => {
         document.removeEventListener(event, handleActivity);
       });
-    };
-  }, [resetInactivityTimer, user]); // Depend on both resetInactivityTimer and user
-
-  // Initialize user state from Supabase session
+
+      document.removeEventListener('visibilitychange', handleVisibilityChange);
+
+      if (inactivityTimeoutRef.current) {
+        clearTimeout(inactivityTimeoutRef.current);
+        inactivityTimeoutRef.current = null;
+      }
+    };
+  }, [resetInactivityTimer]); // Only depend on the stable resetInactivityTimer
+
+  // Initial auth and auth listener setup
   useEffect(() => {
     const initializeAuth = async () => {
       try {
         const { data } = await supabase.auth.getSession();
-
         if (data?.session?.user) {
           setUser(data.session.user);
-
-          localStorage.setItem('lastActivityTimestamp', Date.now().toString());
-        } else {
-          // If no Supabase session, check localStorage
-          const storedUser = localStorage.getItem('user');
-          if (storedUser) {
-            setUser(JSON.parse(storedUser));
-            localStorage.setItem(
-              'lastActivityTimestamp',
-              Date.now().toString()
-            );
-          }
+          localStorage.setItem('jwt', data.session.access_token);
+          // userRef will be updated via the user effect
         }
       } catch (error) {
@@ -163,15 +235,28 @@
     initializeAuth();
 
-    // Listen for auth changes
+    // Set up auth state listener
     const { data: authListener } = supabase.auth.onAuthStateChange(
       (event, session) => {
-        if (session?.user) {
+        if (import.meta.env.DEV && event !== 'TOKEN_REFRESHED') {
+          console.log('Auth state changed:', event);
+        }
+
+        if (event === 'SIGNED_IN' && session?.user) {
           setUser(session.user);
+          localStorage.setItem('jwt', session.access_token);
+          // userRef will be updated via the user effect
         } else if (event === 'SIGNED_OUT') {
           setUser(null);
+          localStorage.removeItem('jwt');
           if (inactivityTimeoutRef.current) {
             clearTimeout(inactivityTimeoutRef.current);
             inactivityTimeoutRef.current = null;
           }
+        } else if (event === 'TOKEN_REFRESHED' && session) {
+          localStorage.setItem('jwt', session.access_token);
+          // Only reset timer if not logged out
+          if (userRef.current) {
+            resetInactivityTimer();
+          }
         }
       }
@@ -183,5 +268,5 @@
       }
     };
-  }, []);
+  }, [resetInactivityTimer]);
 
   const value = {
@@ -190,4 +275,5 @@
     logout,
     resetInactivityTimer,
+    isLoggingOut,
   };
 
Index: client/src/routes/ProtectedRoute.jsx
===================================================================
--- client/src/routes/ProtectedRoute.jsx	(revision 547b5ed29cc465c87c136d82d3b090dc3a6f52c3)
+++ client/src/routes/ProtectedRoute.jsx	(revision 280e995a180ab83674cb114a6e5d0ba9c753ede8)
@@ -1,28 +1,11 @@
 import { Navigate, useLocation } from 'react-router-dom';
 import { useAuth } from '../contexts/AuthContext';
-import React, { useState, useEffect } from 'react';
+import React from 'react';
 
-//Vidi dali tuka treba jwt da se implementira
 const ProtectedRoute = ({ children }) => {
-  const { user, loading } = useAuth();
-  const [localUser, setLocalUser] = useState(null);
-  const [isChecking, setIsChecking] = useState(true);
+  const { user, loading, isLoggingOut } = useAuth();
   const location = useLocation();
 
-  useEffect(() => {
-    try {
-      const userFromStorage = localStorage.getItem('user');
-      if (userFromStorage) {
-        setLocalUser(JSON.parse(userFromStorage));
-      }
-    } catch (err) {
-      console.error('Error reading from localStorage:', err);
-    } finally {
-      setIsChecking(false);
-    }
-  }, []);
-
-  // Show loading spinner while checking auth
-  if (loading || isChecking) {
+  if (loading) {
     return (
       <div className="flex h-screen items-center justify-center">
@@ -31,9 +14,6 @@
     );
   }
-  console.log('User from context:', user);
-  console.log('User from localStorage:', localUser);
 
-  if (!user && !localUser) {
-    console.log('Not authenticated, redirecting to login');
+  if (!user && !isLoggingOut) {
     return (
       <Navigate
@@ -44,5 +24,4 @@
   }
 
-  // If we get here, we're authenticated
   return children;
 };
