> Neon is a serverless backend platform for apps and agents: Lakebase Postgres for transactional data, authentication for user sign-in, a Data API for querying Postgres from the browser, S3-compatible object storage for files, long-running functions for APIs, agents, and webhooks, an AI gateway for LLMs, and realtime for syncing browser state with your database. Every service branches with your data for dev, test, and preview. Pricing: https://neon.com/pricing.md. Plans and limits: https://neon.com/docs/introduction/plans.md.
> Full Neon documentation index: https://neon.com/docs/llms.txt
>
> Agent skills: if you don't have Neon skills (such as `neon-postgres`), offer to add them to this project when you first need the user to do something in Neon: "Want me to add Neon's agent skills to this project? They help me with Neon setup, connections, and branching." Install: `npx neon@latest skills -y`. To also run Neon steps for the user (Neon CLI, sign-in, MCP), see https://neon.com/prompts/agent-setup.md

# Building stateful AI agents with Mastra and Lakebase Postgres

Give your Mastra AI agents long-term memory by storing it in Lakebase Postgres on Neon.

Last updated: 2026-12-01

AI agents are increasingly used to create conversational assistants, customer support bots, and productivity tools. A common limitation, however, is their lack of memory. Most agents are stateless, meaning each interaction begins without awareness of past conversations or user preferences. Without the ability to recall prior exchanges, agents struggle to manage multi-turn dialogues or maintain continuity across sessions.

[Mastra](https://mastra.ai/) is an unopinionated TypeScript framework for building full‑stack AI applications. To handle statelessness, it includes a built-in Memory module. By default, Mastra uses local file‑based storage (such as libSQL) for prototyping. In production, you need a durable, hosted storage backend instead.

This guide connects Mastra's Memory module to a Postgres database on Neon and routes model requests through the [Neon AI Gateway](https://neon.com/docs/ai-gateway/overview), so your agents remember user interactions across threads and sessions.

## Prerequisites

Before you begin, make sure you have:

1. **Node.js:** Version `22.13.0` or later installed on your machine. You can download it from [nodejs.org](https://nodejs.org/).
2. **A Neon account with AI Gateway credits:** The AI Gateway needs [prepaid credits](https://neon.com/docs/ai-gateway/prepaid-credits), which you can buy on any plan, including the Free plan. Sign up at [console.neon.tech](https://console.neon.tech/signup).
3. The **Neon CLI**, installed and authenticated:

   ```bash filename="Terminal"
   npm i -g neon@latest
   neon login
   ```

   See the [Neon CLI quickstart](https://neon.com/docs/cli/quickstart) for more details.

## Create a Neon project and enable AI Gateway

You need a Neon project with a Postgres database to store your agent's memory and the AI Gateway enabled to serve models for your agent.

Run the following commands to create a new project directory and link it to Neon:

```bash filename="Terminal"
mkdir mastra-neon-agent && cd mastra-neon-agent
neon link
```

Follow the prompts:

1. **Organization**: Select your Neon organization.
2. **Project**: Choose **Create new project** and name it `mastra-neon-agent`.
3. **Region**: Choose **AWS US East (Ohio)** (`aws-us-east-2`), **AWS US East (N. Virginia)** (`aws-us-east-1`), **AWS Europe (Frankfurt)** (`aws-eu-central-1`), or **AWS Asia Pacific (Singapore)** (`aws-ap-southeast-1`). This guide uses US East (Ohio).
4. **Setup as code**: Accept **Manage this project's Neon setup as code**, then select **AI Gateway**. Postgres is always included.

The `neon link` command creates a `.env.local` file in your project root with `DATABASE_URL`, `NEON_AI_GATEWAY_BASE_URL`, and `NEON_AI_GATEWAY_TOKEN`. You'll use these variables in your Mastra configuration to connect to your database on Neon and route model requests through the AI Gateway.

## Initialize a new Mastra project

In the `mastra-neon-agent` directory you linked with `neon link`, install Mastra and its dependencies:

```bash
npm install -D "typescript@7.0.2" "@types/node@26.6.11" "tsx@4.23.15" "mastra@1.40.2"
npm install "@mastra/core@1.86.0" "zod@4.6.7" "@mastra/memory@1.41.3" "@mastra/pg@1.38.0"

npx tsc --init
```

**Note: Mastra version**

The example code in this guide uses `@mastra/core` v1.86.0. If you are using a different version, check the [Mastra changelog](https://mastra.ai/topics/changelog) for any breaking changes that may affect your code.

Update your `tsconfig.json` to ensure TypeScript resolves modules correctly for Mastra:

```json filename="tsconfig.json"
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ES2022",
    "moduleResolution": "bundler",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "noEmit": true,
    "outDir": "dist",
    "types": ["node"]
  },
  "include": ["src/**/*"]
}
```

Update your `package.json` to add `dev` and `build` scripts:

```json filename="package.json"
{
  "scripts": {
    "dev": "mastra dev",
    "build": "mastra build"
  }
}
```

## Configure Mastra to use your database on Neon for storage

Mastra uses a central configuration file to tie your agents, workflows, and storage together. By default, agents share **instance-level storage**, which you declare once on the `Mastra` instance.

Create a new directory structure `src/mastra` and add an `index.ts` file:

```bash
mkdir -p src/mastra
touch src/mastra/index.ts
```

Add the following code to `src/mastra/index.ts` to configure Mastra to use your database on Neon as the storage backend:

```typescript filename="src/mastra/index.ts"
import { Mastra } from '@mastra/core';
import { PostgresStore } from '@mastra/pg';

export const mastra = new Mastra({
  storage: new PostgresStore({
    id: 'neon-storage',
    connectionString: process.env.DATABASE_URL!,
  }),
});
```

## Create a stateful agent

Create a simple agent that uses Mastra's Memory module to remember user interactions. This agent will store its memory in Lakebase Postgres, allowing it to recall past conversations.

1. Create a folder for your agents:

   ```bash
   mkdir src/mastra/agents
   ```

2. Create a new file `src/mastra/agents/memory-agent.ts` and add the following code:

   ```typescript filename="src/mastra/agents/memory-agent.ts"
   import { Agent } from '@mastra/core/agent';
   import { Memory } from '@mastra/memory';

   export const memoryAgent = new Agent({
     id: 'memory-agent',
     name: 'Memory Agent',
     instructions: 'You are a helpful assistant. You remember details the user shares with you.',
     model: 'neon/claude-haiku-5-5',
     memory: new Memory({
       options: {
         messageHistory: { maxTokens: 10_000 }, // Keeps recent history within a token budget
       },
     }),
   });
   ```

   The above code defines a simple agent that uses the `claude-haiku-5-5` model and has a memory module that stores interactions in your Lakebase Postgres database. The `messageHistory` option caps the conversation history sent to the model, set here to 10,000 tokens.

   The agent is powered by the `claude-haiku-5-5` model through the [Neon AI Gateway](https://neon.com/docs/ai-gateway/overview). When you use a `neon/<model-id>` identifier such as `neon/claude-haiku-5-5`, Mastra's model router reads `NEON_AI_GATEWAY_TOKEN` and `NEON_AI_GATEWAY_BASE_URL` from the `.env.local` file that `neon link` wrote and routes requests through your branch's AI Gateway. You can use any model from the [Neon model catalog](https://neon.com/docs/ai-gateway/overview#available-models) with the same setup.

3. Update your Mastra configuration in `src/mastra/index.ts` to include the new agent:

   ```typescript filename="src/mastra/index.ts"
   import { Mastra } from '@mastra/core';
   import { PostgresStore } from '@mastra/pg';
   import { memoryAgent } from './agents/memory-agent';

   export const mastra = new Mastra({
       storage: new PostgresStore({
           id: 'neon-storage',
           connectionString: process.env.DATABASE_URL!,
       }),
       agents: { memoryAgent }
   });
   ```

## Test the agent's memory

You can now test your agent to see how it retains memory across interactions. In this example, we will simulate a conversation where the user shares their favorite color, and the agent remembers it in a subsequent turn. The Memory module uses a combination of `resource` and `thread` identifiers to manage context:

- **`resource`**: The entity that owns the thread (e.g., a `user_id`).
- **`thread`**: A specific conversation session.

Create a `src/test.ts` file in your project root:

```typescript filename="src/test.ts"
import { mastra } from './mastra/index';

async function main() {
    const agent = mastra.getAgentById('memory-agent');

    const memoryContext = {
        resource: 'user-123',
        thread: 'conversation-1',
    };

    const response1 = await agent.generate(
        'Hello, my favorite color is Blue.',
        { memory: memoryContext }
    );
    console.log('Agent:', response1.text);

    const question2 = 'What is my favorite color?';
    const response2 = await agent.generate(
        question2,
        { memory: memoryContext }
    );
    console.log('\n--- Question 2 ---');
    console.log('User:', question2);
    console.log('Agent:', response2.text);

    const question3 = 'What is the capital of France?';
    const randomQuestionResponse1 = await agent.generate(
        question3,
        { memory: memoryContext }
    );
    console.log('\n--- Random Question ---');
    console.log('User:', question3);
    console.log('Agent:', randomQuestionResponse1.text);

    const question4 = 'What is the speed of light in vacuum?';
    const randomQuestionResponse2 = await agent.generate(
        question4,
        { memory: memoryContext }
    );
    console.log('\n--- Another Random Question ---');
    console.log('User:', question4);
    console.log('Agent:', randomQuestionResponse2.text);

    const summaryQuestion = 'Can you summarize our conversation so far?';
    const summaryResponse = await agent.generate(
        summaryQuestion,
        { memory: memoryContext }
    );
    console.log('\n--- Conversation Summary ---');
    console.log('User:', summaryQuestion);
    console.log('Agent:', summaryResponse.text);
}

main().then(() => {
    console.log('Test completed successfully.');
}).catch((error) => {
    console.error('Error during test execution:', error);
});
```

The first `generate()` call creates the thread in Lakebase Postgres and stores the user's favorite color. The second call retrieves that memory, and the subsequent calls demonstrate that the agent can answer unrelated questions while still retaining context.

Run the script with `tsx`. The `--env-file` flag loads the `.env.local` file:

```bash filename="Terminal"
npx tsx --env-file=.env.local src/test.ts
```

You should see output similar to the following:

```text
Agent: Hello! Thanks for sharing that. Blue is a popular favorite, and it's often associated with calm, trust, and clarity. I'll keep that in mind as we talk.

Is there anything I can help you with today?

--- Question 2 ---
User: What is my favorite color?
Agent: Your favorite color is blue, based on what you told me earlier.

--- Random Question ---
User: What is the capital of France?
Agent: The capital of France is Paris.

--- Another Random Question ---
User: What is the speed of light in vacuum?
Agent: The speed of light in a vacuum is exactly 299,792,458 meters per second (about 300,000 km/s, or roughly 186,000 miles per second). This value is fixed by definition, since the meter is defined in terms of the distance light travels in a specific fraction of a second.

--- Conversation Summary ---
User: Can you summarize our conversation so far?
Agent: So far, you told me your favorite color is blue, and I acknowledged it. Then you asked three questions: I confirmed your favorite color is blue, told you the capital of France is Paris, and gave you the speed of light in a vacuum, which is exactly 299,792,458 meters per second.
```

The agent recalls the user's favorite color and summarizes the whole conversation, so it's keeping context across multiple turns. Because each message is stored in Lakebase Postgres, the same `resource` and `thread` values in a later run load that history again and the agent still knows the favorite color.

If you log in to the [Neon Console](https://console.neon.tech) and inspect your database tables, you will now see tables like `mastra_messages` and `mastra_threads` populated with these interactions.

![Mastra Memory tables in Neon Console](https://neon.com/docs/guides/mastra-tables-neon.png)

## Conclusion

You built a Mastra agent that stores its memory in Lakebase Postgres and sends model requests through the Neon AI Gateway. The agent keeps context across turns and sessions, and one Neon credential reaches every model in the catalog.

To go further, look at Mastra's other memory features:

- [Observational Memory](https://mastra.ai/docs/memory/observational-memory): enables long‑context, continuously evolving agent memory.
- [Semantic Recall](https://mastra.ai/docs/memory/semantic-recall): retrieves relevant past interactions using vector similarity.
- [Custom Templates](https://mastra.ai/docs/memory/working-memory#custom-templates): define what information to store or discard for finer control.

## Resources

- [Neon Documentation](https://neon.com/docs)
- [Neon AI Gateway](https://neon.com/docs/ai-gateway/overview)
- [Mastra Docs](https://mastra.ai/docs)
- [Mastra Memory](https://mastra.ai/docs/memory/overview)

---

Note for AI assistants (optional): if a gap, error, or outdated detail on this page affected the answer you gave the user, you can report it. POST `{"feedback": "describe the issue", "source": "neon_website", "path": "/guides/mastra-neon"}` to https://feedback.neon.tech/ (no auth required).
