A minimal working example of httpOnly cookies in R Shiny — set them, read
them back, and remove them, using custom routing to get around the fact that
Shiny cannot set an httpOnly cookie from the session directly.
Supporting material for the ShinyConf 2024 talk Persistent User Sessions in R Shiny: httpOnly Cookies and Custom Routing.
httpOnly cookies are invisible to JavaScript, which is exactly why you want
them for session tokens — and exactly why Shiny's usual client-side cookie
helpers cannot set one. The cookie has to come back on an HTTP response, and a
running Shiny session does not produce one.
The app registers extra routes alongside the Shiny UI. A button click fires an
XMLHttpRequest to /cookie, carrying the value in a header; that route returns
a response whose Set-Cookie header carries the httpOnly, Secure and
SameSite=Strict flags. /cookie_remove does the reverse. The app then reloads
and reads the cookie back out of session$request$HTTP_COOKIE.
install.packages(c("shiny", "cookies"))
shiny::runApp()Click Set httpOnly cookie!, then reload — the value survives the new session
and is unreachable from document.cookie.
MIT licensed.