Documentation
¶
Overview ¶
Package session stores data for a visitor across HTTP requests.
The go.laravel.com/middleware.StartSession middleware loads a Session before your handler runs and persists changes afterward. Access the current visitor's session from the request:
r.Session().Put("locale", "fr")
locale, _ := r.Session().Value[string]("locale")
Session payloads are encoded as JSON, so values read back with Session.Get have their JSON types (numbers as float64, structs as maps). Use Session.Value to decode a value back into a concrete Go type.
Built-in Store implementations include MemoryStore, FileStore, and DatabaseStore.
Index ¶
- Constants
- func CreateTable(ctx context.Context) error
- func NewID() string
- func ValidID(id string) bool
- type DatabaseStore
- func (d *DatabaseStore) CollectGarbage(ctx context.Context) error
- func (d *DatabaseStore) Destroy(ctx context.Context, id string) error
- func (d *DatabaseStore) DestroyOthers(ctx context.Context, userID, except string) error
- func (d *DatabaseStore) Read(ctx context.Context, id string) ([]byte, error)
- func (d *DatabaseStore) Write(ctx context.Context, id string, payload []byte, write Write) error
- type FileStore
- type GarbageCollector
- type MemoryStore
- type Session
- func (s *Session) AgeFlash()
- func (s *Session) All() map[string]any
- func (s *Session) DestroyOtherSessions(userID string)
- func (s *Session) Destroyed() []string
- func (s *Session) Encode() []byte
- func (s *Session) ErrorBags() map[string]validation.Errors
- func (s *Session) Errors(bag string) validation.Errors
- func (s *Session) Exists(key string) bool
- func (s *Session) Flash(key string, value any)
- func (s *Session) FlashErrors(bag string, fields validation.Errors)
- func (s *Session) FlashInput(input map[string]any)
- func (s *Session) Flush()
- func (s *Session) Forget(keys ...string)
- func (s *Session) Get(key string) any
- func (s *Session) Has(key string) bool
- func (s *Session) ID() string
- func (s *Session) Invalidate()
- func (s *Session) Keep(keys ...string)
- func (s *Session) Now(key string, value any)
- func (s *Session) OldInput(key string) (any, bool)
- func (s *Session) OthersDestroyed() string
- func (s *Session) PreviousURL() string
- func (s *Session) Pull[T any](key string) (T, bool)
- func (s *Session) Put(key string, value any)
- func (s *Session) Reflash()
- func (s *Session) Regenerate()
- func (s *Session) RegenerateToken()
- func (s *Session) SetPreviousURL(url string)
- func (s *Session) Token() string
- func (s *Session) Value[T any](key string) (T, bool)
- type Store
- type UserSessions
- type Write
Constants ¶
const DefaultBag = "default"
DefaultBag is the error bag name used when a form does not specify one.
const UserIDKey = "_auth.web.id"
UserIDKey is the session key where package auth stores the signed-in user's ID as a string. DatabaseStore records this value in the user_id column.
Variables ¶
This section is empty.
Functions ¶
func CreateTable ¶
CreateTable creates the sessions table used by the database session driver. Register it directly in database/migrations/migrations.go:
{Name: "2026_01_01_000000_create_sessions_table", Run: session.CreateTable}
The table name follows SESSION_TABLE when configured, defaulting to "sessions".
Types ¶
type DatabaseStore ¶
type DatabaseStore struct {
// contains filtered or unexported fields
}
DatabaseStore persists sessions in a SQL database table with the columns id, user_id, ip_address, user_agent, payload, and last_activity (a timestamp). Each write records the signed-in user's ID, IP address, and user agent from the latest request so you can inspect or revoke active devices per user. DatabaseStore implements Store, UserSessions, and GarbageCollector.
func NewDatabaseStore ¶
NewDatabaseStore returns a DatabaseStore backed by table (such as "sessions") on conn. It uses the primary so the next request sees changes made to the session. Sessions expire after being idle for lifetime.
func (*DatabaseStore) CollectGarbage ¶
func (d *DatabaseStore) CollectGarbage(ctx context.Context) error
CollectGarbage deletes all session rows whose last_activity is older than the store's lifetime.
func (*DatabaseStore) Destroy ¶
func (d *DatabaseStore) Destroy(ctx context.Context, id string) error
Destroy deletes the session row for id.
func (*DatabaseStore) DestroyOthers ¶
func (d *DatabaseStore) DestroyOthers(ctx context.Context, userID, except string) error
DestroyOthers deletes every session row belonging to userID except the session with ID except.
func (*DatabaseStore) Read ¶
Read returns the payload for id, or nil, nil if no row exists or the session has expired.
type FileStore ¶
type FileStore struct {
// contains filtered or unexported fields
}
FileStore stores each session in a file named after its session ID. Locking is process-local, so each server process should use its own directory.
func NewFileStore ¶
NewFileStore returns a FileStore that writes session files in dir, creating dir on the first write. Sessions expire after being idle for lifetime.
func (*FileStore) CollectGarbage ¶
CollectGarbage deletes session files in the store's directory that have been idle longer than the configured lifetime.
func (*FileStore) Destroy ¶
Destroy deletes the session file for id. Missing files and invalid IDs return nil.
func (*FileStore) Read ¶
Read returns the payload stored in the file for id, or nil, nil if id is invalid, the file does not exist, or the session has expired.
type GarbageCollector ¶
GarbageCollector is an optional interface for a Store that requires periodic cleanup of expired sessions. go.laravel.com/middleware.StartSession invokes CollectGarbage on roughly one in fifty requests.
type MemoryStore ¶
type MemoryStore struct {
// contains filtered or unexported fields
}
MemoryStore keeps sessions in process memory. Sessions are lost when the process exits, making MemoryStore suitable for tests and local development.
func NewMemoryStore ¶
func NewMemoryStore(lifetime time.Duration) *MemoryStore
NewMemoryStore returns a MemoryStore whose sessions expire after being idle for lifetime.
func (*MemoryStore) CollectGarbage ¶
func (m *MemoryStore) CollectGarbage(ctx context.Context) error
CollectGarbage removes all sessions that have been idle longer than the store's lifetime.
func (*MemoryStore) Destroy ¶
func (m *MemoryStore) Destroy(_ context.Context, id string) error
Destroy removes the session stored under id.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session holds one visitor's session data, flash values, and CSRF token. Keys support dot notation, so "cart.items" addresses the "items" key inside a nested "cart" map. A Session is safe for concurrent use.
func New ¶
New constructs a Session with id and the encoded payload produced by Session.Encode. If id does not pass ValidID, New replaces it with a fresh ID from NewID so a visitor cannot supply an arbitrary session ID. If encoded is nil or cannot be decoded, New starts an empty session with a fresh CSRF token.
func (*Session) AgeFlash ¶
func (s *Session) AgeFlash()
AgeFlash removes flash data from the previous request and schedules the current request's flash data for removal on the next request. go.laravel.com/middleware.StartSession calls AgeFlash before saving the session.
func (*Session) DestroyOtherSessions ¶
DestroyOtherSessions schedules the Store to delete every other session belonging to userID when this request saves the session, such as after a password change. This takes effect only when the store implements UserSessions.
func (*Session) Destroyed ¶
Destroyed returns the previous session IDs replaced by Session.Regenerate or Session.Invalidate during this request. go.laravel.com/middleware.StartSession deletes them from the Store.
func (*Session) Encode ¶
Encode serializes the session's payload (everything except its ID) to JSON for storage in a Store.
func (*Session) ErrorBags ¶
func (s *Session) ErrorBags() map[string]validation.Errors
ErrorBags returns all flashed validation error bags keyed by bag name.
func (*Session) Errors ¶
func (s *Session) Errors(bag string) validation.Errors
Errors returns the validation errors flashed by the previous request for bag. Pass "" for DefaultBag.
func (*Session) Exists ¶
Exists reports whether key is present in the session, even if its value is nil.
func (*Session) Flash ¶
Flash stores a JSON-cloned copy of value at key for the next request only. It panics if value cannot be marshaled to JSON.
func (*Session) FlashErrors ¶
func (s *Session) FlashErrors(bag string, fields validation.Errors)
FlashErrors flashes validation errors for the next request while preserving field order. Pass bag to distinguish multiple forms on the same page, or "" to use DefaultBag. Other error bags flashed during the same request are preserved.
func (*Session) FlashInput ¶
FlashInput flashes form input for the next request so a form can repopulate what the visitor typed. Password fields (password, password_confirmation, current_password) at any nesting depth and top-level _form are excluded automatically.
func (*Session) Flush ¶
func (s *Session) Flush()
Flush removes all data, flash entries, and the previous URL from the session while keeping its CSRF token so open browser forms still submit.
func (*Session) Invalidate ¶
func (s *Session) Invalidate()
Invalidate clears all session data and assigns a new session ID and CSRF token. Call Invalidate when a user signs out.
func (*Session) Now ¶
Now stores a JSON-cloned copy of value at key for the current request only. It panics if value cannot be marshaled to JSON.
func (*Session) OldInput ¶
OldInput returns the value at key from the input flashed by the previous request, along with whether the key was present. An empty field submitted by the visitor is present with a nil value.
func (*Session) OthersDestroyed ¶
OthersDestroyed returns the user ID passed to Session.DestroyOtherSessions, or "" if none was set. go.laravel.com/middleware.StartSession reads this when saving the session.
func (*Session) PreviousURL ¶
PreviousURL returns the URL of the last page the visitor loaded, or "" if none has been recorded.
func (*Session) Pull ¶
Pull reads the value at key, removes it from the session, and decodes it into T. It returns the zero value of T and false if key is missing, nil, or cannot be decoded into T.
func (*Session) Put ¶
Put stores a JSON-cloned copy of value at key. It panics if value cannot be marshaled to JSON, such as a channel or function.
func (*Session) Reflash ¶
func (s *Session) Reflash()
Reflash preserves all flash data from the previous request for one more request.
func (*Session) Regenerate ¶
func (s *Session) Regenerate()
Regenerate assigns a new session ID and CSRF token while keeping the session's data. Call Regenerate when a user signs in to prevent session fixation attacks.
func (*Session) RegenerateToken ¶
func (s *Session) RegenerateToken()
RegenerateToken replaces the session's CSRF token with a new random token.
func (*Session) SetPreviousURL ¶
SetPreviousURL records url as the last page the visitor loaded.
type Store ¶
type Store interface {
Read(ctx context.Context, id string) ([]byte, error)
Write(ctx context.Context, id string, payload []byte, write Write) error
Destroy(ctx context.Context, id string) error
}
Store persists encoded session payloads between requests. Built-in stores include MemoryStore, FileStore, and DatabaseStore; package redis provides a Redis store, and cookie sessions store payloads directly in the browser cookie.
Read returns nil, nil when no session exists for id or when the session has expired.
Write stores payload under id. When write.Existing is true, Read found the session at the start of the request, and a concurrent request (such as a sign-out) may have destroyed it in the meantime. In that case, Write must update the payload only if the session still exists so a destroyed session is not resurrected. When write.Existing is false, Write creates the session or replaces an expired entry.
Destroy deletes the session for id. Destroying a missing session returns nil.
type UserSessions ¶
UserSessions is an optional interface for a Store that indexes sessions by user ID so it can terminate a user's other sessions, such as after a password change.
type Write ¶
type Write struct {
// Existing reports whether the store held the session at the start of the
// request. It is false for new sessions and after [Session.Regenerate].
Existing bool
// IP is the client's IP address as resolved by trusted proxies.
IP string
// UserAgent is the request's User-Agent header, truncated to 500
// characters.
UserAgent string
// UserID is the signed-in user's ID stored at [UserIDKey], or "" for a
// guest.
UserID string
}
Write carries request metadata passed to Store.Write when saving a session.