AdonisJS API
    Preparing search index...

    The session class exposes the API to read and write values to the session store.

    A session instance is isolated between requests but uses a centralized persistence store.

    // Creating and using a session
    const session = new Session(config, storeFactory, emitter, ctx)
    await session.initiate(false)

    session.put('username', 'john')
    const username = session.get('username')

    await session.commit()

    Hierarchy

    • default
      • Session
    Index
    responseFlashMessages: ValuesStore = ...

    Store of flash messages that will be written during the HTTP request

    flashMessages: ValuesStore = ...

    Store of flash messages for the current HTTP request

    flashKey: string = '__flash__'

    The key used for storing flash messages inside the session store

    Session configuration

    • get sessionId(): string

      Gets the session id for the current HTTP request

      Returns string

    • get fresh(): boolean

      Returns true if a fresh session was created during the request

      Returns boolean

    • get readonly(): boolean

      Returns true if the session is in readonly state

      Returns boolean

    • get initiated(): boolean

      Returns true if the session store has been initiated

      Returns boolean

    • get hasRegeneratedSession(): boolean

      Returns true if the session id has been re-generated during the current request

      Returns boolean

    • get isEmpty(): boolean

      Returns true if the session store is empty

      Returns boolean

    • get hasBeenModified(): boolean

      Returns true if the session store has been modified

      Returns boolean

    • Initiates the session store. The method results in a noop when called multiple times.

      Parameters

      • readonly: boolean

        Whether to initiate the session in readonly mode

      Returns Promise<void>

      await session.initiate(false) // Read-write mode
      await session.initiate(true) // Readonly mode
    • Puts a key-value pair to the session data store

      Parameters

      Returns void

      session.put('username', 'john')
      session.put('user.preferences', { theme: 'dark' })
    • Checks if a key exists inside the datastore

      Parameters

      • key: string

        The key to check for existence

      Returns boolean

      if (session.has('username')) {
      console.log('User is logged in')
      }
    • Gets the value of a key from the session datastore. You can specify a default value to use when key does not exist or has undefined value.

      Parameters

      • key: string

        The key to retrieve

      • OptionaldefaultValue: any

        Default value to return if key doesn't exist

      Returns any

      const username = session.get('username', 'guest')
      const preferences = session.get('user.preferences', {})
    • Gets everything from the session store

      Returns any

      const allData = session.all()
      console.log(allData) // { username: 'john', theme: 'dark' }
    • Removes a key from the session datastore

      Parameters

      • key: string

        The key to remove

      Returns void

      session.forget('temp_data')
      session.forget('user.cache')
    • Reads value for a key from the session datastore and removes it simultaneously

      Parameters

      • key: string

        The key to pull

      • OptionaldefaultValue: any

        Default value to return if key doesn't exist

      Returns any

      const message = session.pull('notification', 'No messages')
      // message contains the value, and it's removed from session
    • Increments the value of a key inside the session store. A new key will be defined if it doesn't exist already with value 1.

      Parameters

      • key: string

        The key to increment

      • steps: number = 1

        Number of steps to increment (default: 1)

      Returns void

      session.increment('page_views')     // Increments by 1
      session.increment('score', 10) // Increments by 10
    • Decrements the value of a key inside the session store. A new key will be defined if it doesn't exist already with value -1.

      Parameters

      • key: string

        The key to decrement

      • steps: number = 1

        Number of steps to decrement (default: 1)

      Returns void

      session.decrement('attempts')       // Decrements by 1
      session.decrement('credits', 5) // Decrements by 5
    • Empties the session store

      Returns void

      session.clear() // Removes all session data
      
    • Adds a key-value pair to flash messages

      Parameters

      • key: string

        The key or object of key-value pairs to flash

      • value: AllowedSessionValues

        The value to flash (when key is a string)

      Returns void

      session.flash('success', 'Data saved successfully!')
      session.flash({ error: 'Validation failed', info: 'Try again' })
    • Adds a key-value pair to flash messages

      Parameters

      Returns void

      session.flash('success', 'Data saved successfully!')
      session.flash({ error: 'Validation failed', info: 'Try again' })
    • Flashes errors to the errorsBag. You can read these errors via the "@error" tag. Appends new messages to the existing collection.

      Parameters

      • errorsCollection: Record<string, string | string[]>

        Collection of error messages

      Returns void

      session.flashErrors({
      general: 'Something went wrong',
      validation: ['Name is required', 'Email is invalid']
      })
    • Flashes error messages for form fields to the inputErrorsBag, the same bag "flashValidationErrors" fills. The "@inputError" tag and the Inertia adapter read them like validation errors. Messages are appended to the ones already flashed for a field.

      Parameters

      • messages: Record<string, string | string[]>

        Error messages keyed by field name

      Returns void

      session.flashInputErrors({ email: 'This email is already registered' })
      
    • Flashes validation error messages. Make sure the error is an instance of VineJS ValidationException. Overrides existing inputErrors.

      Parameters

      • error: HttpError

        HTTP error containing validation messages

      • withInput: boolean = true

      Returns void

      try {
      await request.validate(schema)
      } catch (error) {
      session.flashValidationErrors(error)
      }
    • Flashes all form input data to the flash messages store

      Returns void

      session.flashAll() // Flashes all request input for next request
      
    • Flashes form input data (except some keys) to the flash messages store

      Parameters

      • keys: string[]

        Array of keys to exclude from flashing

      Returns void

      session.flashExcept(['password', '_csrf'])
      
    • Flashes form input data (only some keys) to the flash messages store

      Parameters

      • keys: string[]

        Array of keys to include in flashing

      Returns void

      session.flashOnly(['name', 'email'])
      
    • Reflashes messages from the last request in the current response

      Returns void

      session.reflash() // Keep all flash messages for another request
      
    • Reflashes messages (only some keys) from the last request in the current response

      Parameters

      • keys: string[]

        Array of keys to reflash

      Returns void

      session.reflashOnly(['success', 'info'])
      
    • Reflashes messages (except some keys) from the last request in the current response

      Parameters

      • keys: string[]

        Array of keys to exclude from reflashing

      Returns void

      session.reflashExcept(['error', 'warning'])
      
    • Checks if the current store supports session tagging. Only Memory, Redis, and Database stores support tagging.

      Returns boolean

      if (session.supportsTagging()) {
      await session.tag(String(user.id))
      }
    • Tag the current session with a user ID. Only supported by Memory, Redis, and Database stores. This enables features like "logout from all devices".

      Parameters

      • userId: string

        The user ID to tag this session with

      Returns Promise<void>

      // During login, tag the session with the user's ID
      await session.tag(String(user.id))
    • Removes the tag association between this session and a user ID. Only supported by Memory, Redis, and Database stores.

      Parameters

      • userId: string

        The user ID to untag this session from

      Returns Promise<void>

      // During logout, untag the session
      await session.untag(String(user.id))
    • Store a URL as the intended redirect destination. The URL is validated using isValidRedirectUrl before storing. Invalid URLs are silently ignored.

      Parameters

      • url: string

        The URL to store as the intended destination

      Returns void

    • Returns the intended URL without consuming it, or null if no intended URL is stored.

      Returns string | null

    • Returns the intended URL and removes it from the session, or null if no intended URL is stored.

      Returns string | null

    • Removes the intended URL from the session.

      Returns void

    • Re-generates the session id and migrates data to it

      Returns void

      session.regenerate() // Generates new session ID for security
      
    • Commits session changes. No more mutations will be allowed after commit.

      Returns Promise<void>

      await session.commit() // Save all changes to the session store