Session

Sessions persist user-specific data across requests. Nimbus provides four session stores — Memory, Cookie (AES-256-GCM encrypted), Database (GORM), and Redis — all behind a unified Store interface. Sessions are required for authentication.

Store Interface

type Store interface {
    Get(ctx context.Context, id string) (map[string]any, error)
    Set(ctx context.Context, id string, data map[string]any, maxAge time.Duration) (string, error)
    Destroy(ctx context.Context, id string) error
}

Available Stores

StoreConstructorBest For
MemoryNewMemoryStore()Development, single instance (lost on restart)
CookieNewCookieStore(key)Small payloads, no server storage needed
DatabaseNewDatabaseStore(db, table)Persistent sessions, multi-instance
RedisNewRedisStore(client)Fast, distributed, multi-instance production

Memory Store

In-process, auto-cleans expired sessions every minute. Sessions lost on restart.

store := session.NewMemoryStore()

Cookie Store (Encrypted)

Data encrypted with AES-256-GCM in the cookie itself. No server-side storage. Use KeyFromString to derive a 32-byte key from your APP_KEY:

key := session.KeyFromString(os.Getenv("APP_KEY"))
store := session.NewCookieStore(key)

If the key isn't exactly 32 bytes, it's hashed with SHA-256 automatically.

Database Store

Persists sessions to a sessions table. Call EnsureTable() to auto-migrate:

store := session.NewDatabaseStore(database.Get(), "sessions")
store.EnsureTable() // CREATE TABLE IF NOT EXISTS sessions (id, payload, expires_at)

// Schema:
// id         VARCHAR(64) PRIMARY KEY
// payload    TEXT (JSON-encoded session data)
// expires_at DATETIME (indexed, auto-cleaned)

Redis Store

Fast, distributed sessions using Redis with automatic TTL expiration:

import "github.com/CodeSyncr/nimbus/redis"

rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})

// Default prefix: "nimbus:session:"
store := session.NewRedisStore(rdb)

// Custom prefix
store := session.NewRedisStoreWithPrefix(rdb, "myapp:sess:")

Middleware

app.Router.Use(session.Middleware(session.Config{
    Store:       store,
    CookieName:  "nimbus_session",
    MaxAge:      7 * 24 * time.Hour,
    HttpOnly:    true,
    Secure:      true,   // true in production (HTTPS)
    SameSite:    session.SameSiteLax,
}))

Session API

sess := session.FromContext(c.Request.Context())
if sess != nil {
    // Set values
    sess.Set("user_id", "42")
    sess.Set("role", "admin")
    sess.Set("cart", []string{"item-1", "item-2"})

    // Get values
    userID := sess.Get("user_id")    // returns any
    role := sess.Get("role")

    // Delete a key
    sess.Delete("cart")

    // Regenerate session ID (call after login to prevent fixation)
    sess.Regenerate()
}

Config Options

FieldTypeDefaultDescription
StoreStoreSession backend (required)
CookieNamestringnimbus_sessionCookie name in browser
MaxAgetime.Duration7 daysSession lifetime
HttpOnlybooltruePrevent JavaScript access
SecureboolfalseHTTPS only (set true in production)
SameSiteSameSiteLaxLax, Strict, or None