Skip to content

🐛 [Bug]: Adaptor middleware duplicates cookies #3089

@DreamwareDevelopment

Description

@DreamwareDevelopment

Bug Description

I proved that the middleware is duplicating cookies in the cookie header, I have a fix that worked for me.

How to Reproduce

Steps to reproduce the behavior:

  1. Use cookies (I used supertokens.Middleware as the argument to adaptor.HTTPMiddleware() which sets cookies)

Expected Behavior

Cookies should not be duplicated within the header.

Fiber Version

v2.52.4

Code Snippet (optional)

Here is the fix:

func HTTPMiddleware(mw func(http.Handler) http.Handler) fiber.Handler {
	return func(c fiber.Ctx) error {
		var next bool
		nextHandler := http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
			// Convert again in case request may modify by middleware
			next = true
			c.Request().Header.SetMethod(r.Method)
			c.Request().SetRequestURI(r.RequestURI)
			c.Request().SetHost(r.Host)
			c.Request().Header.SetHost(r.Host)

			for key, val := range r.Header {
				if key == "Cookie" {
					// Handle Cookie header separately to avoid duplicates
					c.Request().Header.Del(key)
					c.Request().Header.Set(key, strings.Join(val, "; "))
				} else {
					for _, v := range val {
						c.Request().Header.Set(key, v)
					}
				}
			}
			CopyContextToFiberContext(r.Context(), c.Context())
		})

		if err := HTTPHandler(mw(nextHandler))(c); err != nil {
			return err
		}

		if next {
			return c.Next()
		}
		return nil
	}
}

Checklist:

  • I agree to follow Fiber's Code of Conduct.
  • I have checked for existing issues that describe my problem prior to opening this one.
  • I understand that improperly formatted bug reports may be closed without explanation.

Metadata

Metadata

Assignees

Type

No type

Projects

Status

Done

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions