gofiber/fiber · error
errInvalidField
errInvalidField
Error message
field must not contain CR or LF
What it means
Server-Sent Events are line-delimited; a CR or LF byte inside an Event field (Data, ID, Name) would prematurely terminate that field and corrupt the stream framing. The SSE encoder rejects such fields with errInvalidField rather than emitting a broken stream.
Source
Thrown at middleware/sse/event.go:15
package sse
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/gofiber/utils/v2"
)
var errInvalidField = errors.New("field must not contain CR or LF")
// Event defines a single Server-Sent Event frame.
type Event struct {
// Data is written as one or more data fields. Strings and byte slices are
// written as-is; other values are JSON encoded.
Data any
// ID sets the SSE id field.
ID string
// Name sets the SSE event field.
Name string
// Retry sets the SSE retry field for this event.
Retry time.Duration
}
func writeEvent(w *bufio.Writer, event Event, jsonMarshal ...utils.JSONMarshal) error {View on GitHub (pinned to a105acad6c)
Solutions
- Strip CR/LF from any user-controlled field before constructing the Event.
- For multi-line payloads, split the data into multiple data: lines (the encoder handles []byte / multi-line data correctly when used as designed).
- Validate upstream payloads at the trust boundary.
Example fix
// before
event := sse.Event{ID: record.ID, Name: "update", Data: record.Note}
// after
sanitize := func(s string) string {
s = strings.ReplaceAll(s, "\r", "")
return strings.ReplaceAll(s, "\n", "")
}
event := sse.Event{ID: sanitize(record.ID), Name: "update", Data: record.Note} Defensive patterns
Strategy: validation
Validate before calling
sanitize := func(s string) string {
s = strings.ReplaceAll(s, "\r", "")
return strings.ReplaceAll(s, "\n", "")
}
for _, f := range []*string{&ev.Name, &ev.ID} { *f = sanitize(*f) } Type guard
func isCRLFFree(s string) bool { return !strings.ContainsAny(s, "\r\n") } Prevention
- Treat any user-controlled field as tainted until stripped of CR/LF.
- Encode multi-line payloads the way the SSE encoder expects (multiple data: lines).
- Add a unit test asserting no field contains CR/LF after sanitization.
When it happens
Trigger: Constructing sse.Event{Name: userInput}, Event{ID: userInput}, or Event{Data: "..."} where the value contains '\r' or '\n'.
Common situations: Forwarding un-sanitized user input into Event.ID or Event.Name; multi-line strings in Event.Data; copying data from upstream systems that include CRLF line endings.
Related errors
- sse: invalid id: %w
- sse: invalid event: %w
- [CORS] Invalid origin format in configuration:
- [CSRF] Invalid origin format in configuration:
- client: HTTPS to HTTP redirect blocked
AI-assisted analysis of gofiber/fiber@a105acad6c (2026-08-11).
Data as JSON: /api/errors/da9fc46c36d3e74b.
Report an issue: GitHub.