Modify and Read Global variable after session in R Shiny

I am trying to read a global variable which is declared before UI. In a scenario I am modifying the global variable during the session and in observer function. But when I want to print that modified variable after session kill, it prints old values itself. I want to keep this modified variable(in my requirement every time it changes on each session) for each session.


timeoutSeconds <- 5
varA <- 3 #Declaring Global variable    

#Trigger the function after the 5 seconds 
inactivity <- sprintf("
function idleTimer() {
var t = setTimeout(logout, %s);
window.onmousemove = resetTimer; // catches mouse movements
window.onmousedown = resetTimer; // catches mouse movements
window.onclick = resetTimer;     // catches mouse clicks
window.onscroll = resetTimer;    // catches scrolling
window.onkeypress = resetTimer;  //catches keyboard actions

function logout() {
   Shiny.setInputValue('timeOut', '%ss')

function resetTimer() {
   t = setTimeout(logout, %s);  // time is in milliseconds (1000 is 1 second)

ui <- fluidPage(


server <- shinyServer(function(input,output,session){

  observeEvent(input$timeOut, {
    varA <-varA + 1 #Modifing this global variable for each session

    print(paste0("Session (", session$token, ") timed out at: ", Sys.time()))
      title = "Timeout",
      paste("Session timeout due to", input$timeOut, "inactivity -", Sys.time()),
      footer = NULL

  session$onSessionEnded(function() {

    #Should print 4
    print(varA) #Printing the modified  variable  during sessions




I want to print 4 in the above code. I have tried multiple times, but may be it doesn't work like that. can you please help me anyone on this.


You have to make the variable a reactive Shiny variable:
Within your server function first declare it, then modify:

server <- shinyServer(function(input,output,session){
  VarB <- reactiveVal(VarA + 1)

VarB <- reactiveVal(VarA)
VarB(VarB() + 1) #you update a reactive val as if it were a function

session$onSessionEnded(function() {