Session Middleware

const sessionMiddleware = require('@arangodb/foxx/sessions');

The session middleware adds the session and sessionStorage properties tothe request object and deals with serializing anddeserializing the session as well as extracting session identifiers fromincoming requests and injecting them into outgoing responses.

Examples

  1. // Create a session middleware
  2. const sessions = sessionsMiddleware({
  3. storage: module.context.collection('sessions'),
  4. transport: ['header', 'cookie']
  5. });
  6. // First enable the middleware for this service
  7. module.context.use(sessions);
  8. // Now mount the routers that use the session
  9. const router = createRouter();
  10. module.context.use(router);
  11. router.get('/', function (req, res) {
  12. res.send(`Hello ${req.session.uid || 'anonymous'}!`);
  13. }, 'hello');
  14. router.post('/login', function (req, res) {
  15. req.session.uid = req.body;
  16. req.sessionStorage.save(req.session);
  17. res.redirect(req.reverse('hello'));
  18. });
  19. .body(['text/plain'], 'Username');

Creating a session middleware

sessionMiddleware(options): Middleware

Creates a session middleware.

Arguments

  • options: Object

An object with the following properties:

  • storage: Storage

Storage that will be used to persist the sessions.

The storage is also exposed as the sessionStorage on all request objectsand as the storage property of the middleware.

If a string or collection is passed instead of a Storage, it will be usedto create a Collection Storage.

  • transport: Transport | Array<Transport>

Transport or array of transports that will be used to extract the sessionidentifiers from incoming requests and inject them into outgoing responses.When attempting to extract a session identifier, the transports will beused in the order specified until a match is found. When injecting(or clearing) session identifiers, all transports will be invoked.

The transports are also exposed as the transport property of the middleware.

If the string "cookie" is passed instead of a Transport, theCookie Transport will be used with the defaultsettings instead.

If the string "header" is passed instead of a Transport, theHeader Transport will be used with the defaultsettings instead.

  • autoCreate: boolean (Default: true)

If enabled the session storage’s new method will be invoked to create anempty session whenever the transport failed to return a session for theincoming request. Otherwise the session will be initialized as null.

Returns the session middleware.