Session

public class Session : RouterMiddleware

A pluggable middleware for managing user sessions.

In order to use the Session middleware, an instance of Session has to be created. In the example below an instance of Session is created, then it is connected to the desired path. Two route to are then registered that save and retrieve a User from the session.

Usage Example:

let session = Session(secret: "Something very secret")
router.all(middleware: session)
public struct User: Codable {
    let name: String
}
router.post("/user") { request, response, next in
    let user = User(name: "Kitura")
    request.session?["User"] = user
    next()
}
router.get("/user") { request, response, next in
    let user: User? = request.session?["Kitura"]
    next()
}
  • Initialize a new Session management middleware.

    Declaration

    Swift

    public init(secret: String, cookie: [CookieParameter]? = nil, store: Store? = nil)

    Parameters

    secret

    The string used to encrypt the session ID cookie.

    cookie

    An array of the cookie’s parameters and attributes.

    store

    The Store plugin to be used to store the session state.

  • Handle an incoming request.

    Declaration

    Swift

    public func handle(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void)

    Parameters

    request

    The RouterRequest object used to get information about the request.

    response

    The RouterResponse object used to respond to the request.

    next

    The closure to invoke to enable the Router to check for other handlers or middleware to work with this request.