gofiber/fiber · error · ErrMissingOrMalformedAPIKey

missing or invalid API Key

Error message

missing or invalid API Key

What it means

Returned by keyauth middleware (keyauth.go:26) when the configured Extractor cannot find an API key in the request, or when the Validator function rejects the extracted key. The error replaces the generic extractors.ErrNotFound with this keyauth-specific message (keyauth.go:76-79). It is passed to the ErrorHandler which by default returns 401 Unauthorized with a WWW-Authenticate challenge.

Source

Thrown at middleware/keyauth/keyauth.go:26

	"github.com/gofiber/fiber/v3"
	"github.com/gofiber/fiber/v3/extractors"
	"github.com/gofiber/fiber/v3/internal/redact"
	"github.com/gofiber/fiber/v3/middleware/logger"
	"github.com/gofiber/utils/v2"
)

// The contextKey type is unexported to prevent collisions with context keys defined in
// other packages.
type contextKey int

// The keys for the values in context
const (
	tokenKey contextKey = iota
)

// ErrMissingOrMalformedAPIKey is returned when the API key is missing or invalid.
var ErrMissingOrMalformedAPIKey = errors.New("missing or invalid API Key")

var registerLogContextTagsOnce sync.Once

// New creates a new middleware handler
func New(config ...Config) fiber.Handler {
	registerLogContextTagsOnce.Do(registerLogContextTags)

	// Init config
	cfg := configDefault(config...)

	// Determine the auth schemes from the extractor chain.
	authSchemes := getAuthSchemes(cfg.Extractor)

	// The challenge value only depends on config, so build it once instead of
	// re-formatting it on every 401/407 response.
	challengeValue := cfg.Challenge
	if len(authSchemes) > 0 {
		challenges := make([]string, 0, len(authSchemes))

View on GitHub (pinned to 9a4c7e57fe)

Solutions

  1. Ensure the client sends the API key in the location and format the extractor expects (default: 'Authorization: Bearer <key>').
  2. If using a custom header, set Config.AuthHeader / configure the Extractor chain to read from it.
  3. Verify the Validator function logic — log the failure reason to distinguish missing vs invalid keys.
  4. Customize the ErrorHandler to return a helpful message guiding clients on the expected key format.

Example fix

// before — client sends key in wrong header
curl -H 'X-Token: abc123' https://app/api
// after — use the scheme the extractor is configured for
curl -H 'Authorization: Bearer abc123' https://app/api

// or configure keyauth to read the custom header
app.Use(keyauth.New(keyauth.Config{
  Validator: func(c fiber.Ctx, key string) (bool, error) { return key == validKey, nil },
  AuthHeader: "X-Token",
  AuthScheme: "",
}))
Defensive patterns

Strategy: validation

Validate before calling

// Client: verify the key and header before sending
if apiKey == "" {
    return errors.New("API key is required")
}
req.Header.Set("Authorization", "Bearer "+apiKey)

Try / catch

// Distinguish missing vs invalid in the error handler
cfg.ErrorHandler = func(c fiber.Ctx, err error) error {
    if errors.Is(err, keyauth.ErrMissingOrMalformedAPIKey) {
        return c.Status(401).JSON(fiber.Map{"error":"API key missing or invalid. Send it as 'Authorization: Bearer <key>'."})
    }
    return err
}

Prevention

When it happens

Trigger: A request to a protected route carries no API key in any of the configured extraction sources (default: Authorization header with Bearer scheme, then API-Key header, then query param 'key'); or the key is present but the Validator function returns false/an error. The extractor chain is tried in order and this fires only when all sources fail or validation fails.

Common situations: Client forgot to include the API key header; using the wrong header name (custom AuthHeader vs default); sending the key in the body instead of header/query; token expired or revoked (Validator rejects); mismatch between the scheme the client uses and what FromAuthHeader expects (e.g. 'Token' vs 'Bearer').

Related errors


AI-assisted analysis of gofiber/fiber@9a4c7e57fe (2026-08-04). Data as JSON: /data/errors/bf08cfdd964db909.json. Report an issue: GitHub.