Supabase N8N With Postgres Memory
Learn how to build AI agents with persistent memory using Supabase Postgres database and n8n workflows for context-aware conversations
Supabase N8N With Postgres Memory Tutorial
If you're still using simple memories in your AI agents, you're missing out! Simple memories are non-persistent, meaning when you restart your workflow, all conversation history is lost. To retain information across sessions, you need persistent storage.
In this tutorial, you'll learn how to set up Postgres Chat Memory using Supabase and n8n, enabling your AI agents to remember conversations even after workflow restarts.
Why Postgres Chat Memory?
Simple Memory vs Postgres Memory:
- Simple Memory: Non-persistent, lost on workflow restart
- Postgres Memory: Persistent storage that retains all conversation history
Benefits:
- Persistence: Conversations survive restarts and can be accessed across sessions
- Reliability: Hosted on Supabase, a robust backend platform
- Scalability: Handle thousands of conversations efficiently
- Real-time Access: Query and retrieve conversation history anytime
Prerequisites
Before starting, you'll need:
- Supabase Account - Sign up at supabase.com
- N8N Instance - Self-hosted or cloud instance
- AI Agent Workflow - Basic n8n AI agent setup
Step 1: Create Supabase Project
1.1 Set Up New Project
-
Log in to your Supabase dashboard
-
Click "New Project"
-
Enter project details:
- Name:
n8n-supabase-integration(or any name you prefer) - Database Password: Generate a strong password
⚠️ Important: Copy and save your database password immediately - you won't be able to see it again!
- Name:
-
Click "Create New Project"
-
Wait for the project to finish provisioning (usually takes 1-2 minutes)
Step 2: Configure Postgres Memory in N8N
2.1 Add Postgres Chat Memory Node
- Open your n8n workflow
- Click on your AI Agent node
- In the Memory section, select "Postgres Chat Memory"
- Click "Create New Credential" for Postgres
2.2 Get Connection Details from Supabase
Now you need to get your database connection details from Supabase:
- Go back to your Supabase project
- Navigate to Project Settings (gear icon in sidebar)
- Click on "Database" in the left menu
- Scroll to the "Connection String" section
- Select "Connection Pooling" tab
- Choose "Transaction" mode (recommended for multiple concurrent transactions)
- Select "PSQL" format
You'll see a connection string that looks like this:
psql -h aws-0-us-west-1.pooler.supabase.com -p 6543 -d postgres -U postgres.xxxxxxxxxxxx
2.3 Parse Connection Details
Let's break down this connection string to fill in the n8n credentials:
Connection String Format:
-h [HOST] -p [PORT] -d [DATABASE] -U [USERNAME]
Extract each value:
- Host: Everything after
-h(e.g.,aws-0-us-west-1.pooler.supabase.com) - Port: Everything after
-p(e.g.,6543) - Database: Everything after
-d(usuallypostgres) - User: Everything after
-U(e.g.,postgres.xxxxxxxxxxxx) - Password: The password you saved when creating the project
2.4 Fill in N8N Credentials
In the n8n Postgres credential form, enter:
- Host: Paste the host from
-h - Database:
postgres(from-d) - User: Paste the username from
-U - Password: Paste the password you saved earlier
- Port: Paste the port from
-p(usually6543for pooled connection) - SSL: Leave as default (usually enabled for Supabase)
Click "Save" to test the connection. You should see a green checkmark if successful!
Step 3: Configure Memory Settings
3.1 Memory Node Configuration
In the Postgres Chat Memory node, configure:
- Table Name:
n8n_chat_histories(default - you can change this) - Session ID: Use a unique identifier for each conversation session
- Context Window Length: Number of messages to retain in memory (e.g.,
10)
The context window length determines how many previous messages the AI agent will remember during the conversation.
Context Window Length: 10 = Remembers last 10 messages
Step 4: Test Your Memory Setup
4.1 Run Your First Message
-
Trigger your workflow with a test message:
User: "Hi, I want to ask one question" -
The workflow should execute successfully
-
The Postgres memory node will automatically create the necessary table in Supabase
4.2 Verify in Supabase
- Go back to Supabase
- Click on "Table Editor" in the sidebar
- You should see a new table:
n8n_chat_histories - Click on the table to view entries
You'll see your conversation stored with:
- session_id: Your unique session identifier
- message: JSON format containing the conversation
Example stored message:
{
"type": "human",
"content": "Hi, I want to ask one question"
}
And the AI response:
{
"type": "ai",
"content": "[AI agent's response]"
}
4.3 Test Memory Persistence
Now test if the memory persists:
-
Send another message:
User: "I want you to remember that I love AI agents" -
Refresh the Supabase table editor
-
You should see a new entry with this message and the AI's response
4.4 Test Memory Recall
The real test - does it remember?
-
Restart your n8n workflow (to prove persistence works)
-
Send a follow-up message that requires memory:
User: "What did I just tell you to remember?" -
The AI should recall: "You mentioned that you love AI agents"
-
Check Supabase - all messages are stored, even after restart!
Understanding the Memory Storage
Table Structure
The automatically created table n8n_chat_histories stores:
| Column | Type | Description | |--------|------|-------------| | session_id | VARCHAR | Unique identifier for each conversation | | message | JSONB | The message content in JSON format | | created_at | TIMESTAMP | When the message was stored |
Message Format
Each message is stored as JSON with:
{
"type": "human", // or "ai"
"content": "The actual message text"
}
Viewing Your Conversations
In Supabase Table Editor, you can:
- Filter by session_id to see specific conversations
- View message history in chronological order
- Export data for analysis or backup
- Manually edit or delete messages if needed
Troubleshooting
Connection Failed
If you see a connection error:
- Check your password: Make sure you copied the correct database password
- Verify host: Ensure you're using the pooled connection host (not direct connection)
- Check port: Transaction pooler typically uses port
6543 - SSL settings: Supabase requires SSL - ensure it's enabled in n8n credentials
Table Not Created
If the table doesn't appear in Supabase:
- Make sure the workflow executed successfully
- Check n8n execution logs for errors
- Verify the Postgres credentials are saved and connected
- Try running the workflow again
Memory Not Persisting
If the agent doesn't remember conversations:
- Check that the same
session_idis being used across messages - Verify the context window length is set (e.g., 10)
- Look in Supabase Table Editor to confirm messages are being stored
- Restart the workflow and test again
Best Practices
1. Use Meaningful Session IDs
Create unique session IDs for each user or conversation:
// Example: User-based session ID
const sessionId = `user_${userId}_${Date.now()}`;
// Example: Channel-based session ID
const sessionId = `discord_${channelId}`;
2. Set Appropriate Context Window
Balance between context and performance:
- Short conversations (customer support): 5-10 messages
- Medium conversations (assistants): 10-20 messages
- Long conversations (tutoring): 20-50 messages
3. Clean Up Old Data
Periodically remove old conversations to manage database size:
-- Delete conversations older than 30 days
DELETE FROM n8n_chat_histories
WHERE created_at < NOW() - INTERVAL '30 days';
4. Monitor Database Usage
Check your Supabase dashboard regularly:
- Database size: Ensure you're within your plan limits
- Connection count: Monitor active connections
- Query performance: Check for slow queries
Advanced Tips
Multiple Agents with Separate Memories
Use different table names for different agents:
- Agent 1:
support_agent_memory - Agent 2:
sales_agent_memory - Agent 3:
general_assistant_memory
Add Custom Metadata
Store additional context in the message JSON:
{
"type": "human",
"content": "User message",
"metadata": {
"channel": "discord",
"user_id": "12345",
"timestamp": "2024-01-01T10:00:00Z"
}
}
Implement Memory Summarization
For very long conversations, periodically summarize earlier messages to save context window space.
Key Benefits
- Persistent Memory: Conversations survive workflow restarts
- Easy Setup: Simple configuration with Supabase
- Reliable: Hosted Postgres database with automatic backups
- Scalable: Handle thousands of conversations effortlessly
- Flexible: Customize table structure and memory behavior
- Cost-Effective: Supabase free tier is generous for most projects
Conclusion
You now have a fully functional persistent memory system for your AI agents! Your agents can:
✅ Remember conversations across workflow restarts
✅ Maintain context within sessions
✅ Store unlimited conversation history
✅ Scale to thousands of users
Next time you build AI agents with n8n, make sure to use Postgres memory instead of simple memory for a much better user experience!