core/api

πŸ”„ Redirect

Fiber's built-in redirect package

Redirect helpers send the client to another URL or route.

Redirect Methods

To

Redirects to a URL built from the given path. Optionally set an HTTP status.

Info

If unspecified, status defaults to 303 See Other.

Signature
func (r *Redirect) To(location string) error
Example
app.Get("/coffee", func(c fiber.Ctx) error {
  // => HTTP - GET 301 /teapot
  return c.Redirect().Status(fiber.StatusMovedPermanently).To("/teapot")
})

app.Get("/teapot", func(c fiber.Ctx) error {
  return c.Status(fiber.StatusTeapot).SendString("🍡 short and stout 🍡")
})
More examples
app.Get("/", func(c fiber.Ctx) error {
  // => HTTP - GET 303 /foo/bar
  return c.Redirect().To("/foo/bar")
  // => HTTP - GET 303 ../login
  return c.Redirect().To("../login")
  // => HTTP - GET 303 http://example.com
  return c.Redirect().To("http://example.com")
  // => HTTP - GET 301 http://example.com
  return c.Redirect().Status(301).To("http://example.com")
})

Route

Redirects to a named route with parameters and queries.

Info

To send params and queries to a route, use the RedirectConfig struct.

Signature
func (r *Redirect) Route(name string, config ...RedirectConfig) error
Example
app.Get("/", func(c fiber.Ctx) error {
  // /user/fiber
  return c.Redirect().Route("user", fiber.RedirectConfig{
    Params: fiber.Map{
      "name": "fiber",
    },
  })
})

app.Get("/with-queries", func(c fiber.Ctx) error {
  // /user/fiber?data[0][name]=john&data[0][age]=10&test=doe
  return c.Redirect().Route("user", fiber.RedirectConfig{
    Params: fiber.Map{
      "name": "fiber",
    },
    Queries: map[string]string{
      "data[0][name]": "john",
      "data[0][age]":  "10",
      "test":          "doe",
    },
  })
})

app.Get("/user/:name", func(c fiber.Ctx) error {
  return c.SendString(c.Params("name"))
}).Name("user")

Route returns fiber.ErrNotFound when no route has the given name. Values in Queries are percent-encoded and keys are written as given. The order of the query parameters is not specified.

Note

Each Params value is automatically percent-encoded with URL path-segment rules. Greedy parameters (* and +) preserve / inside the matched path tail; delimiters such as ? and # remain parameter data instead of adding a query or fragment, and cannot absorb or discard Queries. Route.URL and GetRouteURL apply the same encoding.

These take the value as data, not as URL text. Representable values use the same encoding under any configuration. With UnescapePath off (the default) c.Params returns the value still percent-encoded, so forwarding it straight back encodes the % a second time. Turn UnescapePath on, or decode with url.PathUnescape first. An app with UnescapePath enabled decodes %2F before route matching, so an ordinary single-segment parameter holding a / cannot round-trip and returns ErrRouteNotRepresentable. Greedy (* or +), adjacent single-byte parameters and required parameters with a single-byte non-slash terminator retain their existing slash-matching rules. An optional parameter with such a terminator does not match a /, so a decoded / in its value returns ErrRouteNotRepresentable. Dot-containing values are also rejected when the composed path has a . or .. segment that would be removed during normalization. Surrounding route constants are considered: :name.txt with name="." remains representable. Pass a different value or use a route that can represent it; do not pre-encode it.

Back

Redirects to the referer. If it's missing, fall back to the provided URL. You can also set the status code.

Info

If unspecified, status defaults to 303 See Other.

Note

The referer is only used when it is same-origin with the current request, and the value sent in Location is a normalized form of it, not the raw header. The check reads the referer the way a browser does β€” folding backslashes, dropping ASCII tab, CR and LF, and collapsing a leading run of slashes β€” so a value like /\evil.com, which a browser resolves to //evil.com, is not mistaken for a local path. A referer that is missing, cross-origin, or unparsable falls back to the provided URL. If there is no fallback either, Back returns fiber.ErrRedirectBackNoFallback, an error with status 500. With a 300, 301 or 308 status, which a cache may store by default, Back adds Referer to Vary on the redirect, so the cache keys it by the referer it was built from. A 302, 303 or 307 that you make storable with Cache-Control or Expires gets no Vary from Back; call c.Vary(fiber.HeaderReferer) along with them.

This browser-style normalization applies to the referer checked by Back, not to every redirect API or the fallback URL. The HTTP client instead rejects upstream Location values containing control bytes rather than removing them and following a changed target.

Signature
func (r *Redirect) Back(fallback ...string) error
Example
app.Get("/", func(c fiber.Ctx) error {
  return c.SendString("Home page")
})

app.Get("/test", func(c fiber.Ctx) error {
  c.Set("Content-Type", "text/html")
  return c.SendString(`<a href="/back">Back</a>`)
})

app.Get("/back", func(c fiber.Ctx) error {
  return c.Redirect().Back("/")
})

Controls

Info

Methods are chainable.

Status

Sets the HTTP status code for the redirect.

Info

It is used in conjunction with To, Route, and Back methods.

Signature
func (r *Redirect) Status(status int) *Redirect
Example
app.Get("/coffee", func(c fiber.Ctx) error {
  // => HTTP - GET 301 /teapot
  return c.Redirect().Status(fiber.StatusMovedPermanently).To("/teapot")
})

RedirectConfig

Sets the configuration for the redirect.

Info

It is used in conjunction with the Route method.

Definition
// RedirectConfig is a config to use with Redirect().Route()
type RedirectConfig struct {
  Params  fiber.Map         // Route parameters
  Queries map[string]string // Query map
}

Flash Message

Similar to Laravel, we can flash a message and retrieve it in the next request.

Note

Flash messages travel in the fiber_flash cookie (fiber.FlashCookieName), so only a client that keeps cookies across the redirect (a browser, typically) receives them, and every request is scanned for the cookie. Deployments whose clients keep no cookies can turn the feature off with fiber.Config{DisableFlashMessages: true}: With and WithInput then set no cookie, Messages and OldInput report nothing, and the scan is skipped.

The next request that carries the cookie can read the data, and Fiber expires the cookie on that request, so it is delivered once. The accessors return these types:

Definition
// FlashMessage is returned by Messages and Message.
type FlashMessage struct {
  Key   string
  Value string
  Level uint8
}

// OldInputData is returned by OldInputs and OldInput.
type OldInputData struct {
  Key   string
  Value string
}

Messages

Retrieve all flash messages. Reading removes them from the request, so a second call returns none. See With for details.

Signature
func (r *Redirect) Messages() []FlashMessage
Example
app.Get("/", func(c fiber.Ctx) error {
  messages := c.Redirect().Messages()
  return c.JSON(messages)
})

Message

Get a flash message by key; see With. It returns an empty FlashMessage when the key is not found and, like Messages, removes the message it returns.

Signature
func (r *Redirect) Message(key string) FlashMessage
Example
app.Get("/", func(c fiber.Ctx) error {
  message := c.Redirect().Message("status")
  return c.SendString(message.Value)
})

OldInputs

Retrieve stored input data. See WithInput.

Signature
func (r *Redirect) OldInputs() []OldInputData
Example
app.Get("/", func(c fiber.Ctx) error {
  oldInputs := c.Redirect().OldInputs()
  return c.JSON(oldInputs)
})

OldInput

Get stored input data by key; see WithInput. It returns an empty OldInputData when the key is not found.

Signature
func (r *Redirect) OldInput(key string) OldInputData
Example
app.Get("/name", func(c fiber.Ctx) error {
  oldInput := c.Redirect().OldInput("name")
  return c.SendString(oldInput.Value)
})

With

Send flash messages with With. The optional level sets the message's Level and defaults to 0. Calling With again with the same key replaces the earlier message.

Signature
func (r *Redirect) With(key, value string, level ...uint8) *Redirect
Example
app.Get("/login", func(c fiber.Ctx) error {
  return c.Redirect().With("status", "Logged in successfully").To("/")
})

app.Get("/", func(c fiber.Ctx) error {
  // => Logged in successfully
  return c.SendString(c.Redirect().Message("status").Value)
})

WithInput

Send input data with WithInput, which stores them in a cookie.

It captures form, multipart, or query data depending on the request content type.

Caution

WithInput copies the whole submitted body into the fiber_flash cookie β€” a rejected login carries the password the user just typed. The payload is hex-encoded, not encrypted or signed, so anything sensitive in the request goes back to the browser as a cookie value. Prefer With for the specific fields you need to carry across the redirect.

The cookie is HttpOnly, and Secure when the request that produced it arrived over TLS β€” so script cannot read it and it is not replayed in the clear. Neither attribute protects the payload from whoever is at the browser.

Browsers typically drop a cookie larger than about 4 KB, and Fiber sets no flash cookie at all when a redirect carries more than 256 entries (messages plus input fields), so a large form does not make the round trip.

Signature
func (r *Redirect) WithInput() *Redirect
Example
// curl -X POST http://localhost:3000/login -d "name=John"
app.Post("/login", func(c fiber.Ctx) error {
  return c.Redirect().WithInput().Route("name")
})

app.Get("/name", func(c fiber.Ctx) error {
  // => John
  return c.SendString(c.Redirect().OldInput("name").Value)
}).Name("name")