Currently in Beta - View old docs

Kitura Session

HTTP is a stateless connection protocol, that is the server can't distinguish one request from another. Sessions and cookies provide HTTP with state, they allow the server to know who is making a specific request and respond accordingly.

This guide uses Kitura Session with Codable routing leveraging type-safe sessions.

Prerequisites

  • Kitura Server: Learn how to create one in our Getting Started guide.
  • Kitura Style Guide: Follow our guide to see how a production ready server should be structured.
  • Book Model: Define a Book model, as described in Step 5 of the Style Guide.
  • Update Dependencies: Kitura Session needs adding to the `Package.swift` file.
  • Step 1: Create a TypeSafeSessionRoutes.swift file

    Open your `Sources` > `Application` > `Application.swift`

    Inside the `postInit()` function add:

    initializeTypeSafeSessionRoutes(app: self)

    Create a new file called `TypeSafeSessionRoutes.swift` in `Sources` > `Application` > `Routes`

    Inside this file, add the framework for our routes code:

    import KituraContracts
        import KituraSession
    
        func initializeTypeSafeSessionRoutes(app: App) {
            app.router.post("/cart", handler: app.postSessionHandler)
            app.router.get("/cart", handler: app.getSessionHandler)
        }
        extension App {
            // Define handlers here
        }

    We will add our `postSessionHandler` and `getSessionHandler` later in this guide.

    Step 2: Define a Type-Safe Session

    Create a new file called `CheckoutSession.swift` in `Sources` > `Application` > `Middlewares`.

    You may need to create the `Middlewares` folder.

    We can use either a Class or a Struct for TypeSafeMiddleware here but we will use a Class.

    Inside this file, define your `CheckoutSession` class:

    import KituraSession
    
        final class CheckoutSession: TypeSafeSession {
    
            let sessionId: String                       // Requirement: every session must have an ID
            var books: [Book]                           // User-defined type, where Book conforms to Codable
    
            init(sessionId: String) {                   // Requirement: must be able to create a new (empty)
                self.sessionId = sessionId              // session containing just an ID. Assign a default or
                books = []                              // empty value for any non-optional properties.
            }
        }
        // Defines the configuration of the user's type: how the cookie is constructed, and how the session is
        // persisted.
        extension CheckoutSession {
            static let sessionCookie: SessionCookie = SessionCookie(name: "MySession", secret: "Top Secret")
            static var store: Store?
        }

    When using a Class you need to declare it as final.

    The minimum requirements for a type-safe session are:

    • sessionID:
    • Initiliser: Used to create a new sessionId
    • sessionCookie: Defines the name of the cookie and the secret data used to encrypt it
    • An optional store: Defines how sessions should be persisted

    If store isn't specified then a default in memory store is used.

    For an example of a persistent store for sessions see Kitura-Session-Redis

    Step 3: Add session POST route

    Inside the app extension in `TypeSafeSessionRoutes.swift`, we add our `postSessionHandler`:

    func postSessionHandler(session: CheckoutSession, book: Book, completion: (Book?, RequestError?) -> Void) {
    
        }

    We have registered our TypeSafeSession on our handler by adding it to the signature.

    When the handler is called the middleware is run and our session is created.

    Within postSessionHandler, we can then interact with our session:

    session.books.append(book)
        session.save()
        completion(book, nil)

    What we're doing here is storing the posted Book into the session.

    We use the `append` method as we know `books` is an Array as we defined it as an Array in the CheckoutSession class.

    Then we need to save the session.

    Now we can add a route for retrieving the data.

    Step 4: Add session GET route

    Below our `postSessionHandler` handler add:

    func getSessionHandler(session: CheckoutSession, completion: ([Book]?, RequestError?) -> Void) -> Void {
            completion(session.books, nil)
        }

    Add that's it! We've now enabled a Kitura Session on our server.

    Your completed `TypeSafeSessionRoutes.swift` should now look as follows:

    import KituraContracts
        import KituraSession
    
        func initializeTypeSafeSessionRoutes(app: App) {
            app.router.post("/cart", handler: app.postSessionHandler)
            app.router.get("/cart", handler: app.getSessionHandler)
        }
        extension App {
            func postSessionHandler(session: CheckoutSession, book: Book, completion: (Book?, RequestError?) -> Void) {
                session.books.append(book)
                session.save()
                completion(book, nil)
            }
            func getSessionHandler(session: CheckoutSession, completion: ([Book]?, RequestError?) -> Void) -> Void {
                completion(session.books, nil)
            }
        }

    The easiest way to test that this works is using Kitura OpenAPI.

    Step 5: Test our Session

    We will be using Kitura OpenAPI to test our sessions but any tool capable of testing APIs, such as Postman, would work.

    If you don't know how to test your Codable routes using Kiura OpenAPI then you can follow our Kitura OpenAPI Guide to learn how.

    To use OpenAPI we first need to start our server.

    Once the server has started open:

    http://localhost:8080/openapi/ui

    Use OpenAPI to post a books to "/cart"

    To test the GET, either use OpenAPI or go to http://localhost:8080/cart.

    You should see the book you posted. The server is using cookies to make a unique response for your session.

    You can test this by opening a private window and going to http://localhost:8080/cart. This will make a new session and the cart will be empty.

    Next steps

    Add Authentication: Get useful feedback from your server about startup and errors

Back to top