Docs / The Basics / HTTP Session
HTTP Session
Introduction
Since HTTP driven applications are stateless, sessions provide a way to store information about the user across multiple requests. That user information is typically placed in a persistent store / backend that can be accessed from subsequent requests.
Laraflare ships with a variety of session backends that are accessed through an expressive, unified API. Support for databases and cookies is included, as well as an in-memory driver for testing.
Configuration
Your application's session configuration file is stored at config/session.ts. Be sure to review the options available to you in this file. By default, Laraflare is configured to use the database session driver.
The session driver configuration option defines where session data will be stored for each request. Laraflare includes a variety of drivers:
file- sessions are stored instorage/framework/sessions(Node only).cookie- sessions are stored in secure, encrypted cookies.database- sessions are stored in a relational database.array- sessions are stored in an in-memory object and will not be persisted.null- sessions are never stored.
Note
The array driver is primarily used during testing and prevents the data stored in the session from being persisted.
Note
Workers have no filesystem, so the
filedriver is only available when your application runs on Node. Use thedatabaseorcookiedriver on a Worker. Laraflare has no Memcached, Redis or DynamoDB session drivers; you may add your own, as described in Adding Custom Session Drivers.
Driver Prerequisites
Database
When using the database session driver, you will need to ensure that you have a database table to contain the session data. Typically, this is included in the starter app's 0001_01_01_000000_create_users_table.ts database migration; however, if for any reason you do not have a sessions table, you may use the make:session-table Artisan command to generate this migration:
npx artisan make:session-table
npx artisan migrate
The SESSION_CONNECTION environment variable, or the connection option in the config/session.ts configuration file, may be used to specify which database connection is used for session storage, and SESSION_TABLE which table.
Interacting With the Session
Retrieving Data
There are two primary ways of working with session data in Laraflare: the global session helper and via a Request instance. First, let's look at accessing the session via a Request instance, which is passed to a route closure or controller method:
import { Request } from '@laraflare/framework';
export class UserController {
/**
* Show the profile for the given user.
*/
async show(request: Request, id: string) {
const value = request.session().get('key');
// ...
}
}
When you retrieve an item from the session, you may also pass a default value as the second argument to the get method. This default value will be returned if the specified key does not exist in the session:
const value = request.session().get('key', 'default');
The Global Session Helper
You may also use the global session function to retrieve and store data in the session. When the session helper is called with a single, string argument, it will return the value of that session key. When the helper is called with an object of key / value pairs, those values will be stored in the session:
import { Route, session } from '@laraflare/framework';
Route.get('/home', () => {
// Retrieve a piece of data from the session...
const value = session('key');
// Specifying a default value...
const other = session('key', 'default');
// Store a piece of data in the session...
session({ key: 'value' });
});
Note
There is little practical difference between using the session via an HTTP request instance versus using the global
sessionhelper. Both methods are testable via theassertSessionHasmethod which is available in all of your test cases.
Retrieving All Session Data
If you would like to retrieve all the data in the session, you may use the all method:
const data = request.session().all();
Retrieving a Portion of the Session Data
The only and except methods may be used to retrieve a subset of the session data:
const data = request.session().only(['username', 'email']);
const rest = request.session().except(['username', 'email']);
Determining if an Item Exists in the Session
To determine if an item is present in the session, you may use the has method. The has method returns true if the item is present and is not null:
if (request.session().has('users')) {
// ...
}
To determine if an item is present in the session, even if its value is null, you may use the exists method:
if (request.session().exists('users')) {
// ...
}
To determine if an item is not present in the session, you may use the missing method. The missing method returns true if the item is not present:
if (request.session().missing('users')) {
// ...
}
Storing Data
To store data in the session, you will typically use the session's put method or the global session helper:
// Via a request instance...
request.session().put('key', 'value');
// Via the global "session" helper...
session({ key: 'value' });
Pushing to Array Session Values
The push method may be used to push a new value onto a session value that is an array. For example, if the user.teams key contains an array of team names, you may push a new value onto the array like so:
request.session().push('user.teams', 'developers');
Retrieving and Deleting an Item
The pull method will retrieve and delete an item from the session in a single statement:
const value = request.session().pull('key', 'default');
Incrementing and Decrementing Session Values
If your session data contains an integer you wish to increment or decrement, you may use the increment and decrement methods:
request.session().increment('count');
request.session().increment('count', 2);
request.session().decrement('count');
request.session().decrement('count', 2);
Flash Data
Sometimes you may wish to store items in the session for the next request. You may do so using the flash method. Data stored in the session using this method will be available immediately and during the subsequent HTTP request. After the subsequent HTTP request, the flashed data will be deleted. Flash data is primarily useful for short-lived status messages:
request.session().flash('status', 'Task was successful!');
If you need to persist your flash data for several requests, you may use the reflash method, which will keep all of the flash data for an additional request. If you only need to keep specific flash data, you may use the keep method:
request.session().reflash();
request.session().keep(['username', 'email']);
To persist your flash data only for the current request, you may use the now method:
request.session().now('status', 'Task was successful!');
Deleting Data
The forget method will remove a piece of data from the session. If you would like to remove all data from the session, you may use the flush method:
// Forget a single key...
request.session().forget('name');
// Forget multiple keys...
request.session().forget(['name', 'status']);
request.session().flush();
Regenerating the Session ID
Regenerating the session ID is often done in order to prevent malicious users from exploiting a session fixation attack on your application.
Laraflare automatically regenerates the session ID during authentication if you are using one of the Laraflare application starter kits; however, if you need to manually regenerate the session ID, you may use the regenerate method:
await request.session().regenerate();
If you need to regenerate the session ID and remove all data from the session in a single statement, you may use the invalidate method:
await request.session().invalidate();
Session Cache
Laraflare's session cache provides a convenient way to cache data that is scoped to an individual user session. Unlike the global application cache, session cache data is automatically isolated per session and is cleaned up when the session expires or is destroyed. The session cache supports all the familiar Laraflare cache methods like get, put, remember, forget, and more, but scoped to the current session.
The session cache is perfect for storing temporary, user-specific data that you want to persist across multiple requests within the same session, but don't need to store permanently. This includes things like form data, temporary calculations, API responses, or any other ephemeral data that should be tied to a specific user's session.
You can access the session cache through the cache method on the session. Cache calls are asynchronous, and a number of seconds is the time to live:
const discount = await request.session().cache().get('discount');
await request.session().cache().put('discount', 10, 300);
For more information on Laraflare's cache methods, consult the cache documentation.
Session Blocking
Warning
To utilize session blocking, your application must be using a cache driver that supports atomic locks. In addition, you may not use the
cookiesession driver.
By default, Laraflare allows requests using the same session to execute concurrently. So, for example, if you use a JavaScript HTTP library to make two HTTP requests to your application, they will both execute at the same time. For many applications, this is not a problem; however, session data loss can occur in a small subset of applications that make concurrent requests to two different application endpoints which both write data to the session.
To mitigate this, Laraflare provides functionality that allows you to limit concurrent requests for a given session. To get started, you may simply chain the block method onto your route definition. In this example, an incoming request to the /profile endpoint would acquire a session lock. While this lock is being held, any incoming requests to the /profile or /order endpoints which share the same session ID will wait for the first request to finish executing before continuing their execution:
Route.post('/profile', () => {
// ...
}).block(10, 10);
Route.post('/order', () => {
// ...
}).block(10, 10);
The block method accepts two optional arguments. The first argument accepted by the block method is the maximum number of seconds the session lock should be held for before it is released. Of course, if the request finishes executing before this time the lock will be released earlier.
The second argument accepted by the block method is the number of seconds a request should wait while attempting to obtain a session lock. A LockTimeoutException will be thrown if the request is unable to obtain a session lock within the given number of seconds.
If neither of these arguments is passed, the lock will be obtained for a maximum of 10 seconds and requests will wait a maximum of 10 seconds while attempting to obtain a lock:
Route.post('/profile', () => {
// ...
}).block();
Adding Custom Session Drivers
Implementing the Driver
If none of the existing session drivers fit your application's needs, Laraflare makes it possible to write your own session handler. Your custom session driver should implement the SessionHandler interface. This interface contains just a few simple methods, each of which may return its result directly or as a promise. A stubbed MongoDB implementation looks like the following:
import type { SessionHandler } from '@laraflare/framework';
export class MongoSessionHandler implements SessionHandler {
open(savePath: string, sessionName: string): boolean { return true; }
close(): boolean { return true; }
async read(sessionId: string): Promise<string | false> { return false; }
async write(sessionId: string, data: string): Promise<boolean> { return true; }
async destroy(sessionId: string): Promise<boolean> { return true; }
async gc(lifetime: number): Promise<number | false> { return 0; }
}
Laraflare does not include a default directory to house your extensions. You are free to place them anywhere you like. In this example, we have created an app/Extensions directory to house the MongoSessionHandler.
Since the purpose of these methods is not readily understandable, here is an overview of the purpose of each method:
- The
openmethod would typically be used in file based session store systems. Since Laraflare ships with afilesession driver, you will rarely need to put anything in this method. You can simply leave this method empty. - The
closemethod, like theopenmethod, can also usually be disregarded. For most drivers, it is not needed. - The
readmethod should return the string version of the session data associated with the givensessionId, orfalsewhen there is none. There is no need to do any serialization or other encoding when retrieving or storing session data in your driver, as Laraflare will perform the serialization for you. - The
writemethod should write the givendatastring associated with thesessionIdto some persistent storage system, such as MongoDB or another storage system of your choice. Again, you should not perform any serialization - Laraflare will have already handled that for you. - The
destroymethod should remove the data associated with thesessionIdfrom persistent storage. - The
gcmethod should destroy all session data that is older than the givenlifetime, which is a number of seconds. For self-expiring systems, this method may be left empty.
Registering the Driver
Once your driver has been implemented, you are ready to register it with Laraflare. To add additional drivers to Laraflare's session backend, you may use the extend method provided by the Session facade. You should call the extend method from the boot method of a service provider. You may do this from the existing AppServiceProvider or create an entirely new provider:
import { ServiceProvider, Session } from '@laraflare/framework';
import { MongoSessionHandler } from '../Extensions/MongoSessionHandler';
export class SessionServiceProvider extends ServiceProvider {
/**
* Register any application services.
*/
override register(): void {
// ...
}
/**
* Bootstrap any application services.
*/
override boot(): void {
Session.extend('mongo', () => {
// Return an implementation of SessionHandler...
return new MongoSessionHandler();
});
}
}
Once the session driver has been registered, you may specify the mongo driver as your application's session driver using the SESSION_DRIVER environment variable or within the application's config/session.ts configuration file.