Introduction

Sessions provide a means to retain information about the user across numerous requests because HTTP-based applications are stateless. This user data is usually saved in a permanent store Or backend, which may be accessible from later queries

0stroJS comes with a number of session backends that may be accessible via a single, expressive API. Popular backends like Memcached, Redis, and databases are all supported.

Configuration

The session configuration file for your application is located at config/session.html. Make sure you go through all of the choices in this file. OstroJS is set up to utilise the file session driver by default, which is suitable for a wide range of applications. If your application will be load balanced over several web servers, you should use Redis or a database as a centralised storage that all servers may access.

The session driver configuration option specifies where each request's session data will be saved. OstroJS comes with a number of excellent drivers out of the box:

Database

You'll need to construct a table to hold the session records if you're using the database session driver. The following is an example of a table Schema declaration:

await Schema.create('sessions', function ($table) {
    $table.string('id').primary();
    $table.foreignId('user_id').nullable().index();
    $table.string('ip_address', 45).nullable();
    $table.text('user_agent').nullable();
    $table.text('payload');
    $table.integer('last_activity').index();
});

To create this migration, use the session:table Artisan command. You may read the entire migration documentation to learn more about database migrations:

node assistant session:table

node assistant migrate

Redis

You must install  redis package via  NPM before utilising Redis sessions with OstroJS. Consult OstroJS's Redis guide for additional information on configuring Redis.

Interacting With The Session

The Global Session Helper

Route.get('cart',function({ request, session }){
	// use request object
	request.session.get('cartItems)
	// using context object
	return session.get('cartItem')
})

Regenerating The Session ID

In order to prevent hostile users from exploiting a session fixation attack on your application, it's common to regenerate the session ID. If you need to manually regenerate the session ID, you can use the regenerate method:

session.regenerate();

You may use the invalidate method to regenerate the session ID and delete all data from the session in a single statement:

session.invalidate();

Deleting Data

The forget function is used to delete a specific piece of data from a session. If you want to clear all data from a session, you may use the flush method:

// Forget a single key...
session.forget('name');

// Forget multiple keys...
session.forget(['name', 'status']);

session.flush();

Flash Data

You might want to save items in the session for a future request. You can use the flash technique to accomplish so. This technique saves data in the session and makes it available instantly and throughout subsequent HTTP requests. The flashing data will be erased after the next HTTP request. Flash data is best used for short-term status updates:

session.flash('status', 'Task was successful!');

If you need to preserve your flash data for several requests, you may use the reflash technique, which saves all of the flash data for a subsequent request. You can use the maintain technique if you simply need to preserve particular flash data:

session.reflash();

session.keep(['username', 'email']);

You may use the now method to persist your flash data only for the current request:

session.now('status', 'Task was successful!');

Incrementing & Decrementing Session Values

You can use the increment and decrement methods if your session data contains an integer that you want to increase or decrease:

session.increment('count');

session.increment('count', $incrementBy = 2);

session.decrement('count');

session.decrement('count', $decrementBy = 2);

Retrieving & Deleting An Item

In a single sentence, the pull method retrieves and deletes an object from the session:

let value = session.pull('key', 'default');

Pushing To Array Session Values

The push method may be used to add a new value to an array-based session value. If the user.teams key includes an array of team names, for example, you might add a new value to the array as follows:

session.push('user.teams', 'developers');

Storing Data

You'll usually use the request instance's put method or the session object to save data in the session:

// Via a request instance...
session.put('key', 'value');

Determining If An Item Exists In The Session

You may use the has function to see if an object is present in the session. If the item is present and not null, the has method returns true:

if (session.has('users')) {
    //
}

You may use the exists method to see if an item is present in the session, even if its value is null:

if (session.exists('users')) {
    //
}

You may use the missing function to see if an item is missing from the session. If the object is null or is not present, the missing method returns true:

if (session.missing('users')) {
    //
}

Retrieving All Session Data

If you want to get all of the data from a session, you may use the all method:

let data = session.all();

Adding Custom Session Drivers

Implementing The Driver

If none of the available session drivers meet your application's requirements, OstroJS allows you to create your own. NodeJS's built-in SessionHandlerInterface should be used in your own session driver. There are only a few simple methods in this interface. The following is an example of a stubbed MongoDB implementation:

class MongoSessionHandler extends SessionHandlerInterface {

    open($savePath, $sessionName) {}
    close() {}
    read($sessionId) {}
    write($sessionId, $data) {}
    destroy($sessionId) {}
    gc($lifetime) {}

}

Because the objective of these approaches isn't immediately apparent, let's go over what each of them does:

In file-based session storage systems, the open approach is frequently employed. You won't need to use this technique very often because OstroJS comes with a file session driver. This method can just be left empty.
The close technique, like the open method, is frequently overlooked. It is not required for the majority of drivers.
The string version of the session data associated with the provided $sessionId should be returned by the read function. When obtaining or saving session data in your driver, there is no need to do any serialisation or other encoding because OstroJS will do it for you.

Registering The Driver

You may now register your driver with OstroJS after it has been implemented. The extend function offered by the Session object may be used to add new drivers to OstroJS's session backend. The extend method should be called from a service provider's boot method. You may accomplish this using an existing app/providers/appServiceProvider or by creating a new one:

const ServiceProvider = require('@ostro/support/serviceProvider')

class SessionServiceProvider extends ServiceProvider {
    /**
     * Register any application services.
     *
     * @return void
     */
    register() {

        //
        
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    boot() {

        this.$app.session.extend('mongo', function ($app) {
            // Return an implementation of SessionHandlerInterface...
            return new MongoSessionHandler;
        });

    }
}

module.exports = SessionServiceProvider

You may utilise the mongo driver in your config/session.js configuration file once the session driver has been registered.