Skip to main content

Middleware

fiberauth ships middleware that loads sessions, enforces authentication, and supports role-based access — similar to Express middleware chains.

SessionLoader (optional)

Loads a session when present; does not block unauthenticated requests.

app.Use(fiberauth.SessionLoader(auth))

app.Get("/api/feed", func(c fiber.Ctx) error {
s := fiberauth.SessionFrom(c)
if s == nil {
return c.JSON(fiber.Map{"items": publicFeed()})
}
return c.JSON(fiber.Map{"items": personalizedFeed(s.User.ID)})
})

Protect — require login

Shorthand for Guard(auth) with no extra authorizers. Returns 401 if no session.

app.Get("/api/me", fiberauth.Protect(auth), func(c fiber.Ctx) error {
s := fiberauth.SessionFrom(c)
return c.JSON(fiber.Map{
"id": s.User.ID,
"email": s.User.Email,
"name": s.User.Name,
})
})

JSON 401 for SPAs

If the client sends Accept: application/json (or X-Requested-With: XMLHttpRequest), fiberauth returns:

{ "error": "unauthorized", "code": 401 }

Avoids JSON.parse failures on HTML error pages.

Guard — login + authorization

Requires a session and every Authorizer to pass. Failure → 403 (or custom handler).

app.Get("/api/admin",
fiberauth.Guard(auth, fiberauth.HasRole("admin")),
adminHandler,
)

Multiple roles (any match)

fiberauth.Guard(auth, fiberauth.HasRole("admin", "billing"))

Claim check

fiberauth.Guard(auth, fiberauth.HasClaim("plan", "pro"))

Custom condition

fiberauth.Guard(auth,
fiberauth.Condition(func(c fiber.Ctx, s *goauth.Session) bool {
return c.Params("userId") == s.User.ID
}),
)

Custom redirect on 401 / 403

app.Get("/dashboard",
fiberauth.GuardWithConfig(auth, fiberauth.GuardConfig{
Authorizers: []fiberauth.Authorizer{fiberauth.HasRole("user")},
Unauthorized: func(c fiber.Ctx) error {
return c.Redirect().To("/login?next=" + c.Path())
},
Forbidden: func(c fiber.Ctx) error {
return c.Redirect().To("/upgrade")
},
}),
dashboardHandler,
)

Route groups

api := app.Group("/api")
api.Get("/public", publicHandler)

priv := api.Group("", fiberauth.Protect(auth))
priv.Get("/me", meHandler)
priv.Get("/settings", settingsHandler)

admin := api.Group("/admin", fiberauth.Guard(auth, fiberauth.HasRole("admin")))
admin.Get("/users", listUsersHandler)

Middleware order

app := fiber.New()
app.Use(logger.New())
app.Use(recover.New())
// app.Use(cors) — only if SPA is on another origin; prefer Vite proxy in dev

app.All("/auth/*", fiberauth.Handler(auth))

app.Use(fiberauth.SessionLoader(auth)) // after auth mount

app.Get("/api/...", ...)

Mount /auth/* before API routes so sign-in callbacks are not blocked by Protect.

Typed claims helper

roles, ok := fiberauth.Claim[[]string](sess, "roles")
plan := fiberauth.ClaimOr(sess, "plan", "free")

See Sessions, user & roles.