From 31fff54e17747a88aabf1d0defefe6c089d148c2 Mon Sep 17 00:00:00 2001 From: Nils Goroll Date: Fri, 13 Feb 2026 14:26:17 +0100 Subject: [PATCH] Improvement: Do not set session cookie for empty session This is based on https://code.forgejo.org/go-chi/session/pulls/80. The remainder of this message is largely copied from there: For interoperability with reverse proxies and CDNs, setting a session cookie for no good reason (login is a good reason) is a PITA, because it makes caching of content for anonymous (not logged-in) users very hard, requiring all kinds of special casing and error prone workarounds. In particular in an age of exploitative AI bot crawling, being able to serve content for anonymous users from a fast, efficient page cache is an important option. This patch lays a foundation by using an option added to go-chi/session to not create session cookies always, but rather only when the respective session is non-empty. Test cases are included there and omitted here. --- modules/session/db.go | 5 +++++ modules/session/redis.go | 5 +++++ modules/session/virtual.go | 5 +++++ routers/common/middleware.go | 1 + 4 files changed, 16 insertions(+) diff --git a/modules/session/db.go b/modules/session/db.go index eea7e2136e..57f658dfd6 100644 --- a/modules/session/db.go +++ b/modules/session/db.go @@ -84,6 +84,11 @@ func (s *DBStore) Flush() error { return nil } +// True if no keys have been set +func (s *DBStore) Empty() bool { + return len(s.data) == 0 +} + // DBProvider represents a DB session provider implementation. type DBProvider struct { maxLifetime int64 diff --git a/modules/session/redis.go b/modules/session/redis.go index cf84ef21d9..1e8c61da8b 100644 --- a/modules/session/redis.go +++ b/modules/session/redis.go @@ -103,6 +103,11 @@ func (s *RedisStore) Flush() error { return nil } +// True if no keys have been set +func (s *RedisStore) Empty() bool { + return len(s.data) == 0 +} + // RedisProvider represents a redis session provider implementation. type RedisProvider struct { c nosql.RedisClient diff --git a/modules/session/virtual.go b/modules/session/virtual.go index 1986ba64ad..cde9e60c4d 100644 --- a/modules/session/virtual.go +++ b/modules/session/virtual.go @@ -195,3 +195,8 @@ func (s *VirtualStore) Flush() error { s.data = make(map[any]any) return nil } + +// True if no keys have been set +func (s *VirtualStore) Empty() bool { + return len(s.data) == 0 +} diff --git a/routers/common/middleware.go b/routers/common/middleware.go index 7bc4890a43..5c8283e247 100644 --- a/routers/common/middleware.go +++ b/routers/common/middleware.go @@ -118,5 +118,6 @@ func Sessioner() func(next http.Handler) http.Handler { Secure: setting.SessionConfig.Secure, SameSite: setting.SessionConfig.SameSite, Domain: setting.SessionConfig.Domain, + DeferSetCookie: true, }) }