Middleware

middleware/session

import "github.com/gofiber/fiber/v3/middleware/session"

Package session provides session management middleware for Fiber. This middleware handles user sessions, including storing session data in the store.

Variables

ErrEmptySessionID is an error that occurs when the session ID is empty.

Source: middleware/session/store.go:27

var (
	ErrEmptySessionID                   = errors.New("session ID cannot be empty")
	ErrSessionAlreadyLoadedByMiddleware = errors.New("session already loaded by middleware")
	ErrSessionIDNotFoundInStore         = errors.New("session ID not found in session store")
	// ErrKeyNotFound is returned by GetInto when the session holds nothing under the key.
	ErrKeyNotFound = errors.New("session key not found")
)

ConfigDefault provides the default configuration.

Source: middleware/session/config.go:171

var ConfigDefault = Config{
	IdleTimeout:    30 * time.Minute,
	KeyGenerator:   utils.SecureToken,
	Extractor:      extractors.FromCookie("session_id"),
	CookieSameSite: fiber.CookieSameSiteLaxMode,
}

Source: middleware/session/middleware.go:106

var (
	// ErrTypeAssertionFailed occurs when a type assertion fails.
	ErrTypeAssertionFailed = errors.New("failed to type-assert to *Middleware")
)

Functions

func DefaultErrorHandler(c fiber.Ctx, err error)

Source: middleware/session/config.go:187

DefaultErrorHandler logs the error and sends a 500 status code.

Parameters:

  • c: The Fiber context.
  • err: The error to handle.

Usage:

DefaultErrorHandler(c, err)

func FromContext(ctx any) *Middleware

Source: middleware/session/middleware.go:488

FromContext returns the Middleware from the Fiber context. It accepts fiber.CustomCtx, fiber.Ctx, *fasthttp.RequestCtx, and context.Context.

A context kept from c.Context() (with PassLocalsToContext enabled) stops resolving when the request ends: FromContext returns nil for it afterwards, never another request's session.

When several session middleware are registered, FromContext returns the innermost one, the last to run. Use Store.FromContext to reach the middleware of a particular store.

The Middleware belongs to its request, as the type documents. A handler that the timeout middleware gave up on keeps its own: the middleware neither saves the session nor recycles it, and the handler goes on using it, never another request's; both let go of the request, whose context is reused once the handler is done. A request abandoned any other way, as the sse middleware does, one whose response is written from a stream (SendStreamWriter, a net/http handler that flushed) and one whose connection was hijacked are saved as usual when the handlers return, and FromContext returns nil for them from then on; a Middleware that the code still running got before stays finished: it is never recycled for another request, but its session is gone, so the methods that use it panic. A middleware that a panic unwound is not saved or recycled either, and stays the current one for whatever recovers the panic, with its session and the one it runs inside, until the request ends: a Destroy, Reset or Regenerate from there changes the storage and sets the cookies as before the panic, and a Save saves the session and sets its cookie, which it does not do while the middleware is in charge of the session. From the unwinding on its session writes to its own request only, while the handlers of that request still run, and to nothing once the request has ended; it learns of both without waiting for a call that holds the session across the storage, so a goroutine of the handler that still holds the session writes to no other request; a Go context kept past the request does not find the middleware. A goroutine of your own that outlives a handler which returned has no such guarantee: give it the session ID, not the Middleware.

Parameters:

  • c: The Fiber context.

Returns:

  • *Middleware: The middleware object if found and its request is still being handled; otherwise, nil.

Usage:

m := session.FromContext(c)

func GetAs[V any, S *Session | *Middleware](src S, key any) (V, bool)

Source: middleware/session/session.go:1057

GetAs returns the value stored under key as a V, and whether it is one: ok is false when the key is absent or holds a value of another type, and the zero value is returned with it. It spares the type assertion, and with it the panic of an unchecked one.

src is a *Session or a *Middleware. A nil one finds nothing, so the result of FromContext can be passed as it is.

Without a Codec the value is the one that was stored, and like Get, GetAs gives up the saved snapshot when it could share memory with the session (a map, slice, array, pointer or struct). With a Codec the value is decoded into a new V, ok is false when that fails, and nothing is shared: V is what the stored value decodes into, not a check that this is what it was stored as.

Parameters:

  • src: The session or middleware to read from.
  • key: The key to retrieve.

Returns:

  • V: The value, or the zero value of V.
  • bool: True if the key holds a V; otherwise, false.

Usage:

name, ok := session.GetAs[string](session.FromContext(c), "name")

func New(config ...Config) fiber.Handler

Source: middleware/session/middleware.go:131

New initializes session middleware with optional configuration.

Parameters:

  • config: Variadic parameter to override default config.

Returns:

  • fiber.Handler: The Fiber handler for the session middleware.

Usage:

app.Use(session.New())

Usage:

app.Use(session.New())

func NewCodec(name string, marshal func(v any) ([]byte, error), unmarshal func(data []byte, v any) error) Codec

Source: middleware/session/codec.go:114

NewCodec makes a Codec of a name and the two functions of an encoding library, for example msgpack or CBOR, which this package does not import itself:

codec := session.NewCodec("msgpack", msgpack.Marshal, msgpack.Unmarshal)

It panics if the name is empty or longer than 255 bytes, or a function is nil.

Parameters:

  • name: The name written into every record.
  • marshal: Encodes a value.
  • unmarshal: Decodes into a non-nil pointer.

Returns:

  • Codec: The codec.

Usage:

session.New(session.Config{Codec: session.NewCodec("cbor", cbor.Marshal, cbor.Unmarshal)})

func NewStore(config ...Config) *Store

Source: middleware/session/store.go:171

NewStore creates a new session store with the provided configuration.

Parameters:

  • config: Variadic parameter to override default config.

Returns:

  • *Store: The session store.

Usage:

store := session.NewStore()

func NewWithStore(config ...Config) (fiber.Handler, *Store)

Source: middleware/session/middleware.go:152

NewWithStore creates session middleware with an optional custom store.

Parameters:

  • config: Variadic parameter to override default config.

Returns:

  • fiber.Handler: The Fiber handler for the session middleware.
  • *Store: The session store.

Usage:

handler, store := session.NewWithStore()

Types

type Codec

Source: middleware/session/codec.go:43

Codec converts the values of a session to bytes and back. A store with a Codec keeps each value encoded on its own, so a request decodes only the values it reads, and a save encodes only the values that were set. Config.Codec turns it on.

A Codec is called from many requests at once and must be safe for that.

type Codec interface {
	// Name identifies the format, and the options it is used with: change it when
	// you change them. It is written into every record, and a store reads only the
	// records of the codec of that name, so that a session is never decoded by a
	// codec that did not encode it. It is asked once, when the store is made, and must
	// be between 1 and 255 bytes long.
	Name() string

	// Marshal encodes v. The session keeps a copy of what it returns. It runs while
	// Middleware.Set holds the lock of the middleware, so it must not use the session
	// or the middleware it encodes for.
	Marshal(v any) ([]byte, error)

	// Unmarshal decodes data into v, a non-nil pointer. It is handed a copy of the
	// encoded value, which it may keep, and runs without a lock of the session.
	Unmarshal(data []byte, v any) error
}
Methods
  • Name func() string

    Name identifies the format, and the options it is used with: change it when you change them. It is written into every record, and a store reads only the records of the codec of that name, so that a session is never decoded by a codec that did not encode it. It is asked once, when the store is made, and must be between 1 and 255 bytes long.

  • Marshal func(v any) ([]byte, error)

    Marshal encodes v. The session keeps a copy of what it returns. It runs while Middleware.Set holds the lock of the middleware, so it must not use the session or the middleware it encodes for.

  • Unmarshal func(data []byte, v any) error

    Unmarshal decodes data into v, a non-nil pointer. It is handed a copy of the encoded value, which it may keep, and runs without a lock of the session.

type Config

Source: middleware/session/config.go:16

Config defines the configuration for the session middleware.

type Config struct {
	// Storage interface for storing session data.
	//
	// Optional. Default: memory.New()
	Storage fiber.Storage

	// Codec encodes the values of a session, each on its own, in place of gob, which
	// encodes the whole session as one stream. A request then decodes only the
	// values it reads, with GetInto or GetAs, straight into your own types, a save
	// encodes only the values that were set, and your types need no RegisterType.
	// JSONCodec is one, and NewCodec makes one of the functions of another library.
	//
	// With a Codec, the keys of a session are strings, and Get returns what the
	// codec decodes into an interface{} (for JSON, a float64 for every number),
	// not the type that was stored: read typed values with GetInto or GetAs.
	// A value is encoded when it is set, so changing it afterwards is not stored.
	//
	// A session that a store without a Codec stored is read as before, and stays
	// gob until it ends or is reset: nothing is converted. A store that cannot read
	// a record, because it has no Codec or another one, treats it as a session that
	// does not exist, so turn the option on, after every instance runs a release
	// that has it, for all of them at once. See the documentation for the details.
	//
	// Optional. Default: nil, which stores sessions as gob.
	Codec Codec

	// Store defines a pre-built session store, for example one shared with
	// other handlers or one that has custom types registered.
	//
	// With a Store, the options that shape how sessions are stored and sent are
	// the store's own (Storage, Extractor, KeyGenerator, the timeouts, the cookie
	// options, StorageKeyPrefix, HashStorageKeys and Codec), and the ones set for
	// them here are not used: a warning is logged for each that the store does not
	// have. The Config of the middleware supplies Next, ErrorHandler and
	// SkipEmptySessions.
	//
	// Optional. Default: nil, which creates a store from this Config.
	Store *Store

	// Next defines a function to skip this middleware when it returns true.
	// Optional. Default: nil
	Next func(c fiber.Ctx) bool

	// ErrorHandler defines a function to handle errors.
	//
	// Optional. Default: nil
	ErrorHandler func(fiber.Ctx, error)

	// KeyGenerator generates the session key.
	//
	// Optional. Default: utils.SecureToken
	KeyGenerator func() string

	// CookieDomain defines the domain of the session cookie.
	//
	// Optional. Default: ""
	CookieDomain string

	// CookiePath defines the path of the session cookie.
	//
	// Optional. Default: ""
	CookiePath string

	// CookieSameSite specifies the SameSite attribute of the cookie.
	// Accepted values are "Disabled", "Lax", "Strict", and "None", case-insensitively.
	//
	// Optional. Default: "Lax"
	CookieSameSite string

	// StorageKeyPrefix is put in front of the "session:" namespace of the key every
	// session is stored under ("<prefix>session:<ID>"), so that several
	// applications, environments or stores can share one storage without their
	// sessions meeting. End it with a separator such as ":", and choose prefixes so
	// that none, followed by "session:", is the start of another: a store whose
	// prefix starts with "session:" meets a store without one. The ID the client
	// holds is unchanged.
	//
	// Store.Reset clears the whole storage, not only the keys under the prefix.
	//
	// Optional. Default: ""
	StorageKeyPrefix string

	// Extractor is used to extract the session ID from the request.
	// See: https://docs.gofiber.io/guide/extractors
	//
	// Optional. Default: extractors.FromCookie("session_id")
	Extractor extractors.Extractor

	// IdleTimeout defines the maximum duration of inactivity before the session expires.
	//
	// Note: The idle timeout is updated on each `Save()` call. If a middleware handler is used, `Save()` is called automatically.
	//
	// Optional. Default: 30 * time.Minute
	IdleTimeout time.Duration

	// AbsoluteTimeout defines the maximum duration of the session before it expires.
	//
	// If set to 0, the session will not have an absolute timeout, and will expire after the idle timeout.
	//
	// A session that was stored before the timeout was set has no deadline: it ends
	// with the idle timeout alone, until it is reset.
	//
	// Optional. Default: 0
	AbsoluteTimeout time.Duration

	// CookieSecure specifies if the session cookie should be secure.
	//
	// Optional. Default: false
	CookieSecure bool

	// CookieHTTPOnly specifies if the session cookie should be HTTP-only.
	//
	// Optional. Default: false
	CookieHTTPOnly bool

	// CookieSessionOnly determines if the cookie should expire when the browser session ends.
	//
	// If true, the cookie will be deleted when the browser is closed.
	// Note: This will not delete the session data from the store.
	//
	// Optional. Default: false
	CookieSessionOnly bool

	// SkipEmptySessions keeps a session that is new and holds nothing a handler
	// put there out of the storage and out of the response: no record is written
	// and no cookie is set for a visitor whose handlers never use the session.
	//
	// Without it, every request that carries no valid session creates a record
	// that lives until the idle timeout, so a client that sends no cookies, such
	// as a health check or a crawler, fills the storage as fast as it sends
	// requests. A Reset that leaves nothing behind, such as a logout, expires
	// the cookie and stores no new session either.
	//
	// A handler that wants a session to exist must store something in it, if only
	// a flag. The option applies to the session middleware; a session from
	// Store.Get is saved when the handler calls Save.
	//
	// Optional. Default: false
	SkipEmptySessions bool

	// HashStorageKeys stores each session under the SHA-256 digest of its ID,
	// base64url-encoded, instead of under the ID itself (after the prefix and
	// the "session:" namespace, which stay). Whoever can read the
	// storage, through a backup, a replica or a leaked dump, then holds digests
	// that cannot be sent as a session cookie. The ID the client holds is
	// unchanged. It does not make a guessable ID from a custom KeyGenerator safe.
	//
	// Turning it on or off changes the key of every session, so sessions stored
	// before the change are not found afterwards.
	//
	// Optional. Default: false
	HashStorageKeys bool
}
Fields
  • Storage fiber.Storage

    Storage interface for storing session data.

    Optional. Default: memory.New()

  • Codec Codec

    Codec encodes the values of a session, each on its own, in place of gob, which encodes the whole session as one stream. A request then decodes only the values it reads, with GetInto or GetAs, straight into your own types, a save encodes only the values that were set, and your types need no RegisterType. JSONCodec is one, and NewCodec makes one of the functions of another library.

    With a Codec, the keys of a session are strings, and Get returns what the codec decodes into an interface{} (for JSON, a float64 for every number), not the type that was stored: read typed values with GetInto or GetAs. A value is encoded when it is set, so changing it afterwards is not stored.

    A session that a store without a Codec stored is read as before, and stays gob until it ends or is reset: nothing is converted. A store that cannot read a record, because it has no Codec or another one, treats it as a session that does not exist, so turn the option on, after every instance runs a release that has it, for all of them at once. See the documentation for the details.

    Optional. Default: nil, which stores sessions as gob.

  • Store *Store

    Store defines a pre-built session store, for example one shared with other handlers or one that has custom types registered.

    With a Store, the options that shape how sessions are stored and sent are the store's own (Storage, Extractor, KeyGenerator, the timeouts, the cookie options, StorageKeyPrefix, HashStorageKeys and Codec), and the ones set for them here are not used: a warning is logged for each that the store does not have. The Config of the middleware supplies Next, ErrorHandler and SkipEmptySessions.

    Optional. Default: nil, which creates a store from this Config.

  • Next func(c fiber.Ctx) bool

    Next defines a function to skip this middleware when it returns true. Optional. Default: nil

  • ErrorHandler func(fiber.Ctx, error)

    ErrorHandler defines a function to handle errors.

    Optional. Default: nil

  • KeyGenerator func() string

    KeyGenerator generates the session key.

    Optional. Default: utils.SecureToken

  • CookieDomain string

    CookieDomain defines the domain of the session cookie.

    Optional. Default: ""

  • CookiePath string

    CookiePath defines the path of the session cookie.

    Optional. Default: ""

  • CookieSameSite string

    CookieSameSite specifies the SameSite attribute of the cookie. Accepted values are "Disabled", "Lax", "Strict", and "None", case-insensitively.

    Optional. Default: "Lax"

  • StorageKeyPrefix string

    StorageKeyPrefix is put in front of the "session:" namespace of the key every session is stored under ("<prefix>session:<ID>"), so that several applications, environments or stores can share one storage without their sessions meeting. End it with a separator such as ":", and choose prefixes so that none, followed by "session:", is the start of another: a store whose prefix starts with "session:" meets a store without one. The ID the client holds is unchanged.

    Store.Reset clears the whole storage, not only the keys under the prefix.

    Optional. Default: ""

  • Extractor extractors.Extractor

    Extractor is used to extract the session ID from the request. See: https://docs.gofiber.io/guide/extractors

    Optional. Default: extractors.FromCookie("session_id")

  • IdleTimeout time.Duration

    IdleTimeout defines the maximum duration of inactivity before the session expires.

    Note: The idle timeout is updated on each Save() call. If a middleware handler is used, Save() is called automatically.

    Optional. Default: 30 * time.Minute

  • AbsoluteTimeout time.Duration

    AbsoluteTimeout defines the maximum duration of the session before it expires.

    If set to 0, the session will not have an absolute timeout, and will expire after the idle timeout.

    A session that was stored before the timeout was set has no deadline: it ends with the idle timeout alone, until it is reset.

    Optional. Default: 0

  • CookieSecure bool

    CookieSecure specifies if the session cookie should be secure.

    Optional. Default: false

  • CookieHTTPOnly bool

    CookieHTTPOnly specifies if the session cookie should be HTTP-only.

    Optional. Default: false

  • CookieSessionOnly bool

    CookieSessionOnly determines if the cookie should expire when the browser session ends.

    If true, the cookie will be deleted when the browser is closed. Note: This will not delete the session data from the store.

    Optional. Default: false

  • SkipEmptySessions bool

    SkipEmptySessions keeps a session that is new and holds nothing a handler put there out of the storage and out of the response: no record is written and no cookie is set for a visitor whose handlers never use the session.

    Without it, every request that carries no valid session creates a record that lives until the idle timeout, so a client that sends no cookies, such as a health check or a crawler, fills the storage as fast as it sends requests. A Reset that leaves nothing behind, such as a logout, expires the cookie and stores no new session either.

    A handler that wants a session to exist must store something in it, if only a flag. The option applies to the session middleware; a session from Store.Get is saved when the handler calls Save.

    Optional. Default: false

  • HashStorageKeys bool

    HashStorageKeys stores each session under the SHA-256 digest of its ID, base64url-encoded, instead of under the ID itself (after the prefix and the "session:" namespace, which stay). Whoever can read the storage, through a backup, a replica or a leaked dump, then holds digests that cannot be sent as a session cookie. The ID the client holds is unchanged. It does not make a guessable ID from a custom KeyGenerator safe.

    Turning it on or off changes the key of every session, so sessions stored before the change are not found afterwards.

    Optional. Default: false

type JSONCodec

Source: middleware/session/codec.go:74

JSONCodec is the Codec of encoding/json. A value is read back as the type it is decoded into: GetInto and GetAs decode into your own types, while Get returns what encoding/json makes of an interface{}: float64 for every number, string, bool, []any and map[string]any.

type JSONCodec struct{}

func (JSONCodec) Marshal(v any) ([]byte, error)

Source: middleware/session/codec.go:80

Marshal encodes v with encoding/json.

func (JSONCodec) Name() string

Source: middleware/session/codec.go:77

Name returns "json".

func (JSONCodec) Unmarshal(data []byte, v any) error

Source: middleware/session/codec.go:83

Unmarshal decodes data into v with encoding/json.

type Middleware

Source: middleware/session/middleware.go:22

Middleware holds session data and configuration. Middleware serializes access to its internal state with a mutex, but it is request-scoped and must not be used after the request lifecycle ends.

type Middleware struct {
	Session *Session
	// contains filtered or unexported fields
}
Fields
  • Session *Session

func (m *Middleware) AbsoluteExpiry() (time.Time, bool)

Source: middleware/session/middleware.go:802

AbsoluteExpiry returns the time at which the session ends however active it is, and whether it has one. See Session.AbsoluteExpiry.

Returns:

  • time.Time: The absolute expiration time, or the zero time.
  • bool: True if the session has an absolute expiration time; otherwise, false.

Usage:

expiry, ok := m.AbsoluteExpiry()

func (m *Middleware) Delete(key any)

Source: middleware/session/middleware.go:526

Delete removes a key-value pair from the session.

Parameters:

  • key: The key to delete.

Usage:

m.Delete("key")

func (m *Middleware) Destroy() error

Source: middleware/session/middleware.go:557

Destroy destroys the session.

Returns:

  • error: An error if the destruction fails.

Usage:

err := m.Destroy()

func (m *Middleware) DestroyWithContext(ctx context.Context) error

Source: middleware/session/middleware.go:572

DestroyWithContext destroys the session using the provided context for cancellation and timeout control.

Parameters:

  • ctx: The context to use for the storage operation.

Returns:

  • error: An error if the destruction fails.

Usage:

err := m.DestroyWithContext(ctx)

func (m *Middleware) Fresh() bool

Source: middleware/session/middleware.go:594

Fresh checks if the session is fresh.

It reads the session under the middleware's read lock, as every other method does: the end of the request forgets the session under the write lock, and a goroutine that outlives the request must see either the session or none, never the session of the request that takes the object next.

Returns:

  • bool: True if the session is fresh; otherwise, false.

Usage:

isFresh := m.Fresh()

func (m *Middleware) Get(key any) (value any)

Source: middleware/session/middleware.go:736

Get retrieves a value from the session by key.

Parameters:

  • key: The key to retrieve.

Returns:

  • any: The value associated with the key.

Usage:

value := m.Get("key")

func (m *Middleware) GetInto(key, target any) error

Source: middleware/session/middleware.go:770

GetInto stores the value under key into target, a non-nil pointer. See Session.GetInto.

Parameters:

  • key: The key to retrieve.
  • target: A pointer to the variable to fill.

Returns:

  • error: ErrKeyNotFound, or why the value could not be decoded or assigned.

Usage:

var user User
err := m.GetInto("user", &user)

func (m *Middleware) ID() string

Source: middleware/session/middleware.go:610

ID returns the session ID. It reads the session under the middleware's read lock, see Fresh.

Returns:

  • string: The session ID.

Usage:

id := m.ID()

func (m *Middleware) IdleTimeout() time.Duration

Source: middleware/session/middleware.go:785

IdleTimeout returns the idle timeout of the session. See Session.IdleTimeout.

Like the other methods of the middleware it takes a lock of the session, which a save holds while it calls the storage: do not call it from a Storage.

Returns:

  • time.Duration: The idle timeout of the session.

Usage:

timeout := m.IdleTimeout()

func (m *Middleware) Keys() []any

Source: middleware/session/middleware.go:542

Keys returns all keys in the current session.

Returns:

  • []any: A slice of all keys in the session. The internal key that holds the absolute expiration is left out.

Usage:

keys := m.Keys()

func (m *Middleware) Regenerate() error

Source: middleware/session/middleware.go:658

Regenerate generates a new session ID while preserving session data.

This method is commonly used after authentication to prevent session fixation attacks. Unlike Reset(), this method preserves all existing session data.

Returns:

  • error: An error if the regeneration fails.

Usage:

err := m.Regenerate()

func (m *Middleware) RegenerateWithContext(ctx context.Context) error

Source: middleware/session/middleware.go:677

RegenerateWithContext generates a new session ID while preserving session data, using the provided context for cancellation and timeout control.

This method is commonly used after authentication to prevent session fixation attacks. Unlike ResetWithContext(), this method preserves all existing session data.

Parameters:

  • ctx: The context to use for the storage operation.

Returns:

  • error: An error if the regeneration fails.

Usage:

err := m.RegenerateWithContext(ctx)

func (m *Middleware) Reset() error

Source: middleware/session/middleware.go:625

Reset resets the session.

Returns:

  • error: An error if the reset fails.

Usage:

err := m.Reset()

func (m *Middleware) ResetWithContext(ctx context.Context) error

Source: middleware/session/middleware.go:640

ResetWithContext resets the session using the provided context for cancellation and timeout control.

Parameters:

  • ctx: The context to use for the storage operation.

Returns:

  • error: An error if the reset fails.

Usage:

err := m.ResetWithContext(ctx)

func (m *Middleware) Set(key, value any)

Source: middleware/session/middleware.go:511

Set sets a key-value pair in the session.

Parameters:

  • key: The key to set.
  • value: The value to set.

Usage:

m.Set("key", "value")

func (m *Middleware) Store() *Store

Source: middleware/session/middleware.go:692

Store returns the session store.

Returns:

  • *Store: The session store.

Usage:

store := m.Store()

type Session

Source: middleware/session/session.go:22

Session represents a user session. Session serializes access to its internal state with mutexes, but it is request-scoped and must not be used after the request lifecycle ends.

type Session struct {
	// contains filtered or unexported fields
}

func (s *Session) AbsoluteExpiry() (time.Time, bool)

Source: middleware/session/session.go:1182

AbsoluteExpiry returns the time at which the session ends however active it is, and whether it has such a time at all: a store without an AbsoluteTimeout hands out sessions that only the idle timeout ends.

Returns:

  • time.Time: The absolute expiration time, or the zero time.
  • bool: True if the session has an absolute expiration time; otherwise, false.

Usage:

if expiry, ok := s.AbsoluteExpiry(); ok {
    // warn the user when time.Until(expiry) is short
}

func (s *Session) Delete(key any)

Source: middleware/session/session.go:196

Delete removes the key-value pair from the session.

Parameters:

  • key: The key to delete.

Usage:

s.Delete("key")

func (s *Session) Destroy() error

Source: middleware/session/session.go:211

Destroy deletes the session from storage and expires the session cookie.

Returns:

  • error: An error if the destruction fails.

Usage:

err := s.Destroy()

func (s *Session) DestroyWithContext(ctx context.Context) error

Source: middleware/session/session.go:227

DestroyWithContext deletes the session from storage and expires the session cookie, using the provided context for cancellation and timeout control.

Parameters:

  • ctx: The context to use for the storage operation.

Returns:

  • error: An error if the destruction fails.

Usage:

err := s.DestroyWithContext(ctx)

func (s *Session) Fresh() bool

Source: middleware/session/session.go:138

Fresh returns whether the session is new

Returns:

  • bool: True if the session is fresh; otherwise, false.

Usage:

isFresh := s.Fresh()

func (s *Session) Get(key any) any

Source: middleware/session/session.go:1016

Get returns the value associated with the given key.

Parameters:

  • key: The key to retrieve.

Returns:

  • any: The value associated with the key.

Note: returning a value that can alias the session (map, slice, array, pointer, struct) makes every later Save re-encode, since the caller may mutate it in place without calling Set. Such an edit counts as the request's own change, as a Set does, so its save stands over a change another request stored meanwhile; a read alone yields to it.

Usage:

value := s.Get("key")

func (s *Session) GetInto(key, target any) error

Source: middleware/session/session.go:1101

GetInto stores the value under key into target, a non-nil pointer, and reports why it could not: ErrKeyNotFound when there is no such key, in which case target is left as it is.

With a Codec, only that value is decoded, and nothing is shared with the session: the other values are not touched. A target that holds its zero value, as a fresh variable does, is decoded into directly, so nothing is copied. One that holds something is replaced by a new value, so that nothing of the old value is merged into the result. Either way a failure leaves target as it was. Without a Codec, the stored value is assigned to target, which has to be able to hold it, and like Get, GetInto gives up the saved snapshot when the value could share memory with the session.

Parameters:

  • key: The key to retrieve.
  • target: A pointer to the variable to fill.

Returns:

  • error: ErrKeyNotFound, or why the value could not be decoded or assigned.

Usage:

var user User
err := s.GetInto("user", &user)

func (s *Session) ID() string

Source: middleware/session/session.go:152

ID returns the session ID

Returns:

  • string: The session ID.

Usage:

id := s.ID()

func (s *Session) IdleTimeout() time.Duration

Source: middleware/session/session.go:1160

IdleTimeout returns the idle timeout of the session: the one set with SetIdleTimeout, or else the store's. A save applies it, cut down to the time left until the absolute deadline. A timeout set with SetIdleTimeout holds for every later save of this session in the request, unless the session is reset, but is not kept between requests, so the next request has to set it again.

Returns:

  • time.Duration: The idle timeout of this session.

Usage:

timeout := s.IdleTimeout()

func (s *Session) Keys() []any

Source: middleware/session/session.go:679

Keys retrieves all keys in the current session.

Returns:

  • []any: A slice of all keys in the session. The internal key that holds the absolute expiration is left out.

Note: a key that can alias the session has the same effect as in Get.

Usage:

keys := s.Keys()

func (s *Session) Regenerate() error

Source: middleware/session/session.go:267

Regenerate generates a new session id and deletes the old one from storage.

Returns:

  • error: An error if the regeneration fails.

Usage:

err := s.Regenerate()

func (s *Session) RegenerateWithContext(ctx context.Context) error

Source: middleware/session/session.go:286

RegenerateWithContext generates a new session id and deletes the old one from storage, using the provided context for cancellation and timeout control.

Like Save, it tells the request of the session about the new ID, so a store that is asked again finds the session under it: call it from the goroutine that serves the request.

Parameters:

  • ctx: The context to use for the storage operation.

Returns:

  • error: An error if the regeneration fails.

Usage:

err := s.RegenerateWithContext(ctx)

func (s *Session) Release()

Source: middleware/session/session.go:99

Release releases the session back to the pool.

This function should be called after the session is no longer needed. This function is used to reduce the number of allocations and to improve the performance of the session store.

The session should not be used after calling this function.

Important: The Release function should only be used when accessing the session directly, for example, when you have called func (s *Session) Get(ctx) to get the session. It should not be used when using the session with a *Middleware handler in the request call stack, as the middleware will still need to access the session.

Usage:

sess := session.Get(ctx)
defer sess.Release()

func (s *Session) Reset() error

Source: middleware/session/session.go:367

Reset generates a new session id, deletes the old one from storage, and resets the associated data.

Returns:

  • error: An error if the reset fails.

Usage:

err := s.Reset()

func (s *Session) ResetWithContext(ctx context.Context) error

Source: middleware/session/session.go:386

ResetWithContext generates a new session id, deletes the old one from storage, and resets the associated data, using the provided context for cancellation and timeout control.

Like Save, it tells the request of the session about the new ID, so a store that is asked again finds the session under it: call it from the goroutine that serves the request.

Parameters:

  • ctx: The context to use for the storage operation.

Returns:

  • error: An error if the reset fails.

Usage:

err := s.ResetWithContext(ctx)

func (s *Session) Save() error

Source: middleware/session/session.go:518

Save saves the session data and updates the cookie

Note: If the session is being used in the handler, calling Save will have no effect and the session will automatically be saved when the handler returns.

Returns:

  • error: An error if the save operation fails.

Usage:

err := s.Save()

func (s *Session) SaveWithContext(ctx context.Context) error

Source: middleware/session/session.go:542

SaveWithContext saves the session data and updates the cookie, using the provided context for cancellation and timeout control.

Note: If the session is being used in the handler, calling SaveWithContext will have no effect and the session will automatically be saved when the handler returns. To tell, it takes the read lock of the session middleware, which is held while that middleware destroys, resets or regenerates its session, and the lock of the session, to read its context, which is held while it saves: do not call it from a Storage then.

Parameters:

  • ctx: The context to use for the storage operation.

Returns:

  • error: An error if the save operation fails.

Usage:

err := s.SaveWithContext(ctx)

func (s *Session) Set(key, val any)

Source: middleware/session/session.go:181

Set updates or creates a new key-value pair in the session.

Parameters:

  • key: The key to set.
  • val: The value to set.

Usage:

s.Set("key", "value")

func (s *Session) SetIdleTimeout(idleTimeout time.Duration)

Source: middleware/session/session.go:694

SetIdleTimeout used when saving the session on the next call to Save().

Parameters:

  • idleTimeout: The duration for the idle timeout.

Usage:

s.SetIdleTimeout(time.Hour)

type Store

Source: middleware/session/store.go:74

Store manages session data using the configured storage backend. It holds atomic fields, so it is made by NewStore and used through the pointer it returns: copying a Store is flagged by go vet.

type Store struct {
	Config
	// contains filtered or unexported fields
}
Fields
  • Config

func (s *Store) Delete(ctx context.Context, id string) error

Source: middleware/session/store.go:690

Delete deletes a session by its ID.

Parameters:

  • id: The unique identifier of the session.

Returns:

  • error: An error if the deletion fails or if the session ID is empty.

Usage:

err := store.Delete(id)
if err != nil {
    // handle error
}

func (s *Store) FromContext(ctx any) *Middleware

Source: middleware/session/store.go:291

FromContext returns the Middleware that this store's session middleware installed for the request, or nil when the store has none there. It accepts the same contexts as the package-level FromContext and ends the same way: a context kept past the request returns nil.

Register one session middleware per store, each over its own cookie or header, and a handler reaches every session of the request:

loginHandler, loginStore := session.NewWithStore(session.Config{
    Extractor: extractors.FromCookie("login_sid"),
})
appHandler, appStore := session.NewWithStore(session.Config{
    Extractor: extractors.FromCookie("app_sid"),
})
app.Use(loginHandler, appHandler)

login := loginStore.FromContext(c)
appSession := appStore.FromContext(c)

Like the methods of Middleware it takes the read lock of the middleware it visits, so call it from handlers, not from a Storage while that middleware is destroying, resetting or regenerating its session, which hold the lock.

Parameters:

  • ctx: The Fiber context, a *fasthttp.RequestCtx, or a context.Context.

Returns:

  • *Middleware: The store's middleware if it is running for the request; otherwise, nil.

func (s *Store) Get(c fiber.Ctx) (*Session, error)

Source: middleware/session/store.go:244

Get will get/create a session.

This function will return an ErrSessionAlreadyLoadedByMiddleware if the session is already loaded by the middleware.

For a visitor who has no cookie yet, the ID that Get issues is remembered for the request by the store and by the stores that share a cookie or header with it, and by no others: asked again after a Save, a store returns the session it saved, whatever other stores were asked in between, and under the new ID if Regenerate or Reset gave the session one. An ID that was not saved is not a session, and asking again before a Save issues another.

Parameters:

  • c: The Fiber context.

Returns:

  • *Session: The session object.
  • error: An error if the session retrieval fails or if the session is already loaded by the middleware.

Usage:

sess, err := store.Get(c)
if err != nil {
    // handle error
}

func (s *Store) GetByID(ctx context.Context, id string) (*Session, error)

Source: middleware/session/store.go:769

GetByID retrieves a session by its ID from the storage. If the session is not found, it returns nil and an error.

Unlike session middleware methods, this function does not automatically:

  • Load the session into the request context.

  • Save the session data to the storage or update the client cookie.

Important Notes:

  • The session object returned by GetByID does not have a context associated with it.

  • When using this method alongside session middleware, there is a potential for collisions, so be mindful of interactions between manually retrieved sessions and middleware-managed sessions.

  • If you modify a session returned by GetByID, you must call session.Save() to persist the changes.

  • When you are done with the session, you should call session.Release() to release the session back to the pool.

Parameters:

  • id: The unique identifier of the session.

Returns:

  • *Session: The session object if found; otherwise, nil.
  • error: An error if the session retrieval fails or if the session ID is empty.

Usage:

sess, err := store.GetByID(id)
if err != nil {
    // handle error
}

func (*Store) RegisterType(i any)

Source: middleware/session/store.go:215

RegisterType registers a custom type for encoding/decoding into any storage provider.

Parameters:

  • i: The custom type to register.

Usage:

store.RegisterType(MyCustomType{})

func (s *Store) Reset(ctx context.Context) error

Source: middleware/session/store.go:663

Reset deletes all sessions from the storage.

Returns:

  • error: An error if the reset operation fails.

Usage:

err := store.Reset()
if err != nil {
    // handle error
}