# Sessions

# Already installed? Jump to Usage

At version 1.0.0, xpresser will STOP shipping with session support out of the box because It benefits the framework more as a standalone plugin.
However, this plugin re-enables the old session system and is simply Plug & Play.

Migrating does not affect code usage. Sessions data still exists in http.session.

# Setup

Install session plugin

npm i @xpresser/session
// OR
yarn add @xpresser/session

# Register Plugin

Add plugin to your plugins.json file. if you don't have one, create one at backend/plugins.json.

Note: Plugin should come before other plugins that requires session

# Configuration

Note: Session is enabled and sqlite store is used by default without any configuration.
Import default configuration file using the command below

xjs import session configs

Check imported config file for more settings @ configs/session(.js|.ts)

# Required Declarations (Typescript)

Add the code below to your xpresser.d.ts file.

import "@xpresser/session/xpresser";

# Usage

Session data is an object stored in http.session which is a shortHand for http.req.session.


http.session is a type of XSessionCustomData, declared in @xpresser/session/xpresser.d.ts (opens new window).

# Set/Update session

route.post('/login', http => {
  // Add to Session
  http.session.user = http.body('username');
  return 'Login Successful!'

# Get session

route.post('/account', http => {
  // Asign session.user to const user.
  const user = http.session.user;
  return {user}

# Delete Session

route.post('/logout', http => {
  // Delete session with key `user`
  delete http.session.user;
  return 'User Deleted successfully.'

# Advanced

# Using Custom Store.

To use a custom session store, you need to set useDefault to false and set your custom store function

# Custom Store Example.

The example below is a mongodb custom store using connect-mongodb-session (opens new window)

# Defining Types For Session Values (Typescript)

In order to prevent errors when compiling you have to extend XSessionCustomData interface. let's assume we have a variable user that references a User database model;

// Assuming class user is:
class User {
    public name: string;
    public email: string;
    public password: string;

http.session.user = new User();

The last line above may throw an error depending on your strict settings because typescript knows user is not defined in http.session OR in type XSessionCustomData. You are just about to define it, so you have to tell typescript about this and what type user is.

Add to xpresser.d.ts

declare module "@xpresser/session/custom-types" {
    interface XSessionCustomData {
        user: User

With the declaration above http.session.user.email should be accessible.