Session

Session middleware for Fiber

Signatures

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

Examples

Import the middleware package that is part of the Fiber web framework

  1. import (
  2. "github.com/gofiber/fiber/v2"
  3. "github.com/gofiber/fiber/v2/middleware/session"
  4. )

After you initiate your Fiber app, you can use the following possibilities:

  1. // Default middleware config
  2. store := session.New()
  3. // This panic will be catch by the middleware
  4. app.Get("/", func(c *fiber.Ctx) error {
  5. // get session from storage
  6. sess, err := store.Get(c)
  7. if err != nil {
  8. panic(err)
  9. }
  10. // save session
  11. defer sess.Save()
  12. // Get value
  13. name := sess.Get("name")
  14. // Set key/value
  15. sess.Set("name", "john")
  16. // Delete key
  17. sess.Delete("name")
  18. // Destroy session
  19. if err := sess.Destroy(); err != nil {
  20. panic(err)
  21. }
  22. return c.SendString(fmt.Sprintf("Welcome %v", name))
  23. })

Config

  1. // Config defines the config for middleware.
  2. type Config struct {
  3. // Allowed session duration
  4. // Optional. Default value 24 * time.Hour
  5. Expiration time.Duration
  6. // Storage interface to store the session data
  7. // Optional. Default value memory.New()
  8. Storage fiber.Storage
  9. // Name of the session cookie. This cookie will store session key.
  10. // Optional. Default value "session_id".
  11. CookieName string
  12. // Domain of the CSRF cookie.
  13. // Optional. Default value "".
  14. CookieDomain string
  15. // Path of the CSRF cookie.
  16. // Optional. Default value "".
  17. CookiePath string
  18. // Indicates if CSRF cookie is secure.
  19. // Optional. Default value false.
  20. CookieSecure bool
  21. // Indicates if CSRF cookie is HTTP only.
  22. // Optional. Default value false.
  23. CookieHTTPOnly bool
  24. // Indicates if CSRF cookie is HTTP only.
  25. // Optional. Default value false.
  26. CookieSameSite string
  27. // KeyGenerator generates the session key.
  28. // Optional. Default value utils.UUID
  29. KeyGenerator func() string
  30. }

Default Config

  1. var ConfigDefault = Config{
  2. Expiration: 24 * time.Hour,
  3. CookieName: "session_id",
  4. KeyGenerator: utils.UUID,
  5. }