My understanding is that Shiny handles this automatically and I think this app demonstrates that this is the case. It displays the contents of the tempdir()every 0.1 seconds and shows that the temporary files are never visible. In this example it's probably because the downloadhandler blocks the process, but regardless it shows that nothing is left behind afterwards. I also asked deepwiki about it: Search | DeepWiki and it shows the lines in the Shiny source code that are responsible for deleting files once the request is complete.
library(shiny)
library(bslib)
ui <- page_sidebar(
title = "Temp Directory Monitor",
sidebar = sidebar(
actionButton("make_temp", "Make temp file"),
downloadButton("download", "Download data")
),
verbatimTextOutput("temp_dir")
)
server <- function(input, output, session) {
# Display temp directory contents
output$temp_dir <- renderText({
invalidateLater(100) # Refresh 0.1 second
temp_dir <- tempdir()
files <- list.files(temp_dir, full.names = FALSE)
file_info <- file.info(file.path(temp_dir, files))
paste0(
"Temporary directory: ", temp_dir, "\n\n",
"Files:\n",
paste(files, " (", round(file_info$size / 1024, 2), " KB)",
collapse = "\n")
)
})
df <- reactive(data.frame(rep(1, 10), rep(2, 10)))
observeEvent(input$make_temp, {
write.csv(df(), tempfile())
})
# Download handler
output$download <- downloadHandler(
filename = function() {
"data.csv"
},
content = function(file) {
write.csv(df(), file)
}
)
}
shinyApp(ui = ui, server = server)