> ## Documentation Index
> Fetch the complete documentation index at: https://docs.chainlit.io/llms.txt
> Use this file to discover all available pages before exploring further.

# User Session

The user session is designed to persist data in memory through the [life cycle](/concepts/chat-lifecycle) of a chat session. Each user session is unique to a user and a given chat session.

## Why use the user session?

Let's say you want to keep track of each chat session message count.

A naive implementation might look like this:

<Warning>
  This example is for illustrative purposes only. It is not recommended to use
  this code in production.
</Warning>

```python Naive Example theme={null}
import chainlit as cl

counter = 0


@cl.on_message
async def on_message(message: cl.Message):
    global counter
    counter += 1

    await cl.Message(content=f"You sent {counter} message(s)!").send()
```

At first glance, this code seems to work. However, it has a major flaw. If two users are chatting with the bot at the same time, both users will increment the same `counter`.

This is where the user session comes in. Let's rewrite the above example using the user session:

```python Correct example theme={null}
import chainlit as cl


@cl.on_chat_start
def on_chat_start():
    cl.user_session.set("counter", 0)


@cl.on_message
async def on_message(message: cl.Message):
    counter = cl.user_session.get("counter")
    counter += 1
    cl.user_session.set("counter", counter)

    await cl.Message(content=f"You sent {counter} message(s)!").send()
```

## User Session Default Values

By default, Chainlit stores chat session related data in the user session.

The following keys are reserved for chat session related data:

<ParamField path="id" type="str">
  The session id.
</ParamField>

<ParamField path="user" type="cl.User">
  Only set if you are enabled [Authentication](/authentication). Contains the
  user object of the user that started this chat session.
</ParamField>

<ParamField path="chat_profile" type="str">
  Only relevant if you are using the [Chat
  Profiles](/advanced-features/chat-profiles) feature. Contains the chat profile
  selected by this user.
</ParamField>

<ParamField path="chat_settings" type="Dict">
  Only relevant if you are using the [Chat
  Settings](/advanced-features/chat-settings) feature. Contains the chat
  settings given by this user.
</ParamField>

<ParamField path="env" type="Dict" default="{}">
  Only relevant if you are using the [user\_env](/backend/config/project) config.
  Contains the environment variables given by this user.
</ParamField>
