Session

Since the HTTP protocol is stateless, you cannot simply share data between requests using it. Fortunately, there is a mechanism of session.

In Entropy you are able to store user information that we can access and share with multiple requests using session client.

Configuration

The configuration for things like session lifetime is stored in the .env file variables:

      

.env

SESSION_LIFETIME=30 # days

Storing Data

To save a variable to the session, use the set method. You only have to provide name for your piece of data and its value:

      

src/users/user.controller.ts

import { Controller, Route } from '@entropy/router'; import { HttpRequest } from '@entropy/http'; export class UserController extends Controller { @Route.Get('/users/:id?') public async show([id]: [string?], request: HttpRequest) { await request.session.set('username', 'John Doe'); // ... } }

Retrieving Data

In order to retrieve saved session data, use the get method:

      

src/users/user.controller.ts

const username = await request.session.get('username') ?? 'Unknown';

Deleting Data

Use the delete method in order to remove a session value by its key:

      

src/users/user.controller.ts

await request.session.delete('username');

Destroying Session

Sometimes you need to clear all session entries and completely unset the session, for example for logging out the user. In order to do that, use the destroy method:

      

src/users/user.controller.ts

await request.session.destroy();
Validation Middleware