Setting "domain" in session cookie


I am using gin with gin-contrib/sessions for session management. With this session management package, session cookie is going in the response, but I am not able set “domain” in the cookie due to some bug in gin-contrib/sessions. Is there any other package that can be used for session management, but allows to set “domain” in the session cookie?


Setting the domain name via Options() seems to be working fine:

	store := cookie.NewStore([]byte("secret"))
	store.Options(sessions.Options{Domain: ""})

Modified example from GitHub - gin-contrib/sessions: Gin middleware for session management :

Setting the cookie domain to “” makes the cookie accessible from its subdomains like “” and “”. Setting it to a subdomain such as “” makes the cookie accessible only on that subdomain.

Thanks Rolan for the reply.

I am following the same approach, but instead of cookies package, I am using Redis for storing the session. At my end, it doesn’t work with Redis, Set-Cookie in HTTP response contains: Set-Cookie: mysession=; i.e. mysession is empty. It works fine for me if I use cookie store.

Please have a look at the following code, does it work for you?

package main

import (
GitHub - gin-contrib/sessions: Gin middleware for session management
GitHub - gin-gonic/gin: Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.

func main() {
r := gin.Default()
store, _ := redis.NewStore(10, “tcp”, “localhost:6379”, “”, byte(“secret”))
store.Options(sessions.Options{Domain: “”})

r.Use(sessions.Sessions(“mysession”, store))

r.GET(“/incr”, func(c *gin.Context) {
session := sessions.Default(c)
var count int
v := session.Get(“count”)
if v == nil {
count = 0
} else {
count = v.(int)
session.Set(“count”, count)
c.JSON(200, gin.H{“count”: count})

Since we are passing a new sessions.Options{} struct and the MaxAge was not set an explicit value, it uses a zero-value instead, overwriting the default that was set when the store was created, possibly causing the MaxAge to be set to zero and automatically expiring your session:

Try specifying a MaxAge for session expiration along with the domain. MaxAge default used by the lib was set to 30 days, so you can use that.

	store.Options(sessions.Options{Domain: "", MaxAge: 86400 * 30})

I haven’t dug deep to see if you also need to set the Path to “/”, but I think it uses “/” if the Path is empty.

Thanks Rolan, it worked. However, Path and Max Age had to be set explicitly in session options.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.