Encrypt Cookie
Encrypt middleware for Fiber which encrypts cookie values. Note: this middleware does not encrypt cookie names.

Table of Contents

Signatures

1
// Intitializes the middleware
2
func New(config ...Config) fiber.Handler
3
​
4
// Returns a random 32 character long string
5
func GenerateKey() string
Copied!

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/encryptcookie"
4
)
Copied!
After you initiate your Fiber app, you can use the following possibilities:
1
// Default middleware config
2
app.Use(encryptcookie.New(encryptcookie.Config{
3
Key: "secret-thirty-2-character-string",
4
}))
5
​
6
// Get / reading out the encrypted cookie
7
app.Get("/", func(c *fiber.Ctx) error {
8
return c.SendString("value=" + c.Cookies("test"))
9
})
10
​
11
// Post / create the encrypted cookie
12
app.Post("/", func(c *fiber.Ctx) error {
13
c.Cookie(&fiber.Cookie{
14
Name: "test",
15
Value: "SomeThing",
16
})
17
return nil
18
})
Copied!

Config

1
type Config struct {
2
// Next defines a function to skip this middleware when returned true.
3
//
4
// Optional. Default: nil
5
Next func(c *fiber.Ctx) bool
6
​
7
// Array of cookie keys that should not be encrypted.
8
//
9
// Optional. Default: []
10
Except []string
11
​
12
// Base64 encoded unique key to encode & decode cookies.
13
//
14
// Required. Key length should be 32 characters.
15
// You may use `encryptcookie.GenerateKey()` to generate a new key.
16
Key string
17
​
18
// Custom function to encrypt cookies.
19
//
20
// Optional. Default: EncryptCookie
21
Encryptor func(decryptedString, key string) (string, error)
22
​
23
// Custom function to decrypt cookies.
24
//
25
// Optional. Default: DecryptCookie
26
Decryptor func(encryptedString, key string) (string, error)
27
}
Copied!

Default Config

1
// `Key` must be a 32 character string. It's used to encrpyt the values, so make sure it is random and keep it secret.
2
// You can call `encryptcookie.GenerateKey()` to create a random key for you.
3
// Make sure not to set `Key` to `encryptcookie.GenerateKey()` because that will create a new key every run.
4
app.Use(encryptcookie.New(encryptcookie.Config{
5
Key: "secret-thirty-2-character-string",
6
}))
Copied!
Last modified 1mo ago