Documentation
Feedback
Guides
Storefront Development

Storefront Development
Store Framework
Dealing with events
Collecting user session data

VTEX tracks users' sessions within apps by storing session information in a namespace. Each app has its own namespace, and only the app can modify its session properties. For example, the vtex.search-session app manages the search namespace.

This guide explains how to detect session changes in a specific namespace and respond to them programmatically.

Learn more about the Session manager and check the Session manager API reference. For a practical use case, refer to the Cart cleanup guide.

Session Manager API overview

To view a store's current session data and structure, open your browser and navigate to:


_10
https://{workspace}–{accountName}.myvtex.com/api/sessions?items=*

Only use items=* during development. Never use it in production, as it retrieves all session data. For production, retrieve specific session data by specifying the required namespace and properties (e.g., items=authentication.storeUserEmail,checkout.orderFormId).

Before you begin

Before starting, ensure you have the following:

  • VTEX IO CLI: Install and configure the VTEX IO CLI.
  • Existing app: If you are building a new app, run vtex init and select service-example to create a new app using the node builder. Make sure the app vendor is set to the appropriate account.

Instructions

Step 1 - Configuring the vtex.session builder

  1. Open your app's manifest.json file and add vtex.session under the builders section:

    manifest.json

    _10
    "builders": {
    _10
    "node": "7.x",
    _10
    "docs: "0.x",
    _10
    "vtex.session": "0.x"
    _10
    },

  2. In the root directory of your project, create a folder named vtex.session and add the configuration.json to it. This file defines the session behavior for your app.

  3. Inside configuration.json, define the session configuration using the following structure:

    configuration.json

    _10
    {
    _10
    "APP-NAME": {
    _10
    "input": {
    _10
    "NAMESPACE": ["VALUE"]
    _10
    },
    _10
    "output": {
    _10
    "NAMESPACE": ["VALUE"]
    _10
    }
    _10
    }
    _10
    }

ParameterDescription
APP-NAMEApp's name without the vendor prefix. For example, session-watcher-demo.
inputObject containing the key-value pairs corresponding to session changes you want to monitor.
outputObject containing the key-value pairs for the session changes you want to apply.

Example

In the following example, the app listens for changes in the authentication namespace to retrieve the user's email (storeUserEmail). It also monitors the checkout namespace to track the orderFormId. The output stores a property called demo in the public namespace.


_11
{
_11
"session-watcher-demo": {
_11
"input": {
_11
"authentication": ["storeUserEmail"],
_11
"checkout": ["orderFormId]
_11
},
_11
"output": {
_11
"public": ["demo"]
_11
}
_11
}
_11
}

Step 2 - Setting up the transform handler

The vtex.session builder detects changes in the input values of the configuration.json file and sends a POST request to the public endpoint (/_v/APP-NAME/session/transform) whenever a change occurs. All values listed under input are sent in the request, even if not all values have changed.

To set up this endpoint, take the following steps:

  1. Open the ./node/services.json file and add a route containing path and public under the routes property. For example:

    services.json

    _10
    "routes": {
    _10
    "clearCart": {
    _10
    "path": "/_v/session-watcher-demo/session/transform",
    _10
    "public": true
    _10
    }
    _10
    }

  2. Create the node/resolvers/index.ts file and define the handler function for processing session changes. This function will respond with the expected output defined in the configuration.json. Take the following example and note the handler receives a Context that gives access to the request body. The handle should respond as a JSON with the object expected on the output definition.

    node/resolvers/index.ts

    _29
    /* eslint-disable no-console */
    _29
    import { json } from 'co-body'
    _29
    _29
    export const resolvers = {
    _29
    Routes: {
    _29
    clearCart: async (ctx: Context) => {
    _29
    const { req } = ctx
    _29
    _29
    const body: any = await json(req)
    _29
    const email = body?.authentication?.storeUserEmail?.value ?? null
    _29
    _29
    console.log('clearCart =>', body)
    _29
    _29
    ctx.set('Content-Type', 'application/json')
    _29
    ctx.set('Cache-Control', 'no-cache, no-store')
    _29
    _29
    const res = {
    _29
    public: {
    _29
    demo: {
    _29
    value: email ? 'User Authenticated' : 'User not authenticated',
    _29
    },
    _29
    },
    _29
    }
    _29
    _29
    ctx.response.body = res
    _29
    ctx.response.status = 200
    _29
    },
    _29
    },
    _29
    }

  3. In the ./node/index.ts file, import the handler function file ( node/reseolvers/index.ts) and load it to the Service.

    node/index.ts

    _10
    import { resolvers } from ‘./resolvers’
    _10
    _10
    // Export a service that defines route handlers and client options.
    _10
    export default new Service{{
    _10
    clients,
    _10
    routes: resolvers.Routes,
    _10
    })

Step 3 - Testing your changes

  1. Link your app to a development workspace by running vtex link.

  2. Monitor the terminal for logs indicating the session changes. Once a user logs in or out, you should see logs like clearCart => with the body of the request.

    {"base64":"  ","img":{"width":1714,"height":186,"type":"png","mime":"image/png","wUnits":"px","hUnits":"px","length":140834,"url":"https://cdn.jsdelivr.net/gh/vtexdocs/dev-portal-content@main/images/vtex-io-documentation-collecting-user-session-data-2.png"}}

You can also check the session data changes by accessing the following URL:


_10
https://{workspace}–{accountName}.myvtex.com/api/sessions?items=public.demo

The response might look like this:


_10
{
_10
"id": "cca40248-a3f9-4a60-baf1-b67de92cd8a",
_10
"namespaces": {
_10
"public": {
_10
"demo": {
_10
"Value": "User Authenticated"
_10
}
_10
}
_10
}
_10
}

The vtex.session builder may take a few minutes to initialize after linking the app. If logs don’t appear immediately, please wait a few minutes.

For a complete example, download the code.

Contributors
2
Photo of the contributor
Photo of the contributor
+ 2 contributors
Was this helpful?
Yes
No
Suggest edits (Github)
Contributors
2
Photo of the contributor
Photo of the contributor
+ 2 contributors
On this page