Introduction: Understanding Appwrite
Appwrite is an open-source Backend-as-a-Service (BaaS) platform that provides developers with a set of APIs, tools, and services designed to reduce backend development time. It offers authentication, database management, file storage, cloud functions, and more—all with a focus on security and simplicity.
This cheatsheet serves as a comprehensive reference for developers working with Appwrite backend services, providing essential commands, configurations, and best practices.
Core Concepts & Architecture
| Component | Description | Purpose |
|---|---|---|
| Server | The core Appwrite server | Handles all API requests and services |
| Console | Web interface for managing projects | Visual management of all Appwrite resources |
| Client SDKs | Language-specific libraries | Connect applications to Appwrite services |
| CLI | Command-line interface | Automate and manage Appwrite from terminal |
| Cloud Functions | Serverless functions | Execute custom code on specific events |
| Projects | Organizational units | Group resources by application |
| Teams | User groups | Manage permissions and collaboration |
Installation & Setup
Docker Setup (Recommended)
# Pull and start Appwrite using Docker
docker run -it --rm \
--volume /var/run/docker.sock:/var/run/docker.sock \
--volume "$(pwd)"/appwrite:/usr/src/code/appwrite:rw \
--entrypoint="install" \
appwrite/appwrite:1.4.0
# Start Appwrite
docker-compose up -d
CLI Installation
# Install Appwrite CLI
npm install -g appwrite-cli
# Login to Appwrite
appwrite login
# Initialize a project
appwrite init project
Authentication Service
Key Authentication Methods
// Email/Password Authentication
const user = await sdk.account.create(
ID.unique(),
'email@example.com',
'password123'
);
// OAuth Authentication
const oauthUrl = sdk.account.createOAuth2Session(
'github',
'https://myapp.com/callback'
);
// Phone Authentication
const user = await sdk.account.createPhoneSession(
'+1234567890'
);
// Magic URL Authentication
const user = await sdk.account.createMagicURLSession(
ID.unique(),
'email@example.com',
'https://myapp.com/callback'
);
// Anonymous Session
const session = await sdk.account.createAnonymousSession();
Session Management
// Get current session
const session = await sdk.account.getSession('current');
// Get all sessions
const sessions = await sdk.account.listSessions();
// Delete session
await sdk.account.deleteSession('sessionId');
// Update session (extend expiry)
await sdk.account.updateSession('sessionId');
User Management
// Create user (admin API)
const user = await sdk.users.create(
ID.unique(),
'email@example.com',
'password123',
'John Doe'
);
// Get user
const user = await sdk.users.get('userId');
// List users
const users = await sdk.users.list();
// Update user
const user = await sdk.users.updateName('userId', 'New Name');
// Delete user
await sdk.users.delete('userId');
Database Service
Collections & Documents
// Create collection
const collection = await sdk.databases.createCollection(
'databaseId',
ID.unique(),
'Products',
[
Permission.read(Role.any()),
Permission.write(Role.team('adminTeamId'))
]
);
// Create document
const document = await sdk.databases.createDocument(
'databaseId',
'collectionId',
ID.unique(),
{ name: 'Product 1', price: 99.99 },
[
Permission.read(Role.any()),
Permission.update(Role.user('userId'))
]
);
// Get document
const document = await sdk.databases.getDocument(
'databaseId',
'collectionId',
'documentId'
);
// List documents
const documents = await sdk.databases.listDocuments(
'databaseId',
'collectionId'
);
// Update document
const document = await sdk.databases.updateDocument(
'databaseId',
'collectionId',
'documentId',
{ price: 89.99 }
);
// Delete document
await sdk.databases.deleteDocument(
'databaseId',
'collectionId',
'documentId'
);
Attributes & Indexes
// Create string attribute
await sdk.databases.createStringAttribute(
'databaseId',
'collectionId',
'title',
255,
true
);
// Create number attribute
await sdk.databases.createIntegerAttribute(
'databaseId',
'collectionId',
'price',
true
);
// Create boolean attribute
await sdk.databases.createBooleanAttribute(
'databaseId',
'collectionId',
'isAvailable',
true
);
// Create index
await sdk.databases.createIndex(
'databaseId',
'collectionId',
'price_index',
'key',
['price'],
['ASC']
);
Queries & Filters
// Equal to
const documents = await sdk.databases.listDocuments(
'databaseId',
'collectionId',
[
Query.equal('category', 'electronics')
]
);
// Greater/less than
const documents = await sdk.databases.listDocuments(
'databaseId',
'collectionId',
[
Query.greaterThan('price', 50),
Query.lessThan('price', 200)
]
);
// Search text
const documents = await sdk.databases.listDocuments(
'databaseId',
'collectionId',
[
Query.search('name', 'apple')
]
);
// Limit and offset
const documents = await sdk.databases.listDocuments(
'databaseId',
'collectionId',
[
Query.limit(20),
Query.offset(20)
]
);
// Sort
const documents = await sdk.databases.listDocuments(
'databaseId',
'collectionId',
[
Query.orderDesc('createdAt')
]
);
Storage Service
File Operations
// Upload file
const file = await sdk.storage.createFile(
'bucketId',
ID.unique(),
document.getElementById('uploader').files[0],
[
Permission.read(Role.any()),
Permission.update(Role.user('userId'))
]
);
// Get file
const file = await sdk.storage.getFile(
'bucketId',
'fileId'
);
// List files
const files = await sdk.storage.listFiles(
'bucketId'
);
// Get file preview
const filePreview = sdk.storage.getFilePreview(
'bucketId',
'fileId',
200, // width
200, // height
'center', // gravity
100 // quality
);
// Get file download
const fileDownload = sdk.storage.getFileDownload(
'bucketId',
'fileId'
);
// Delete file
await sdk.storage.deleteFile(
'bucketId',
'fileId'
);
Bucket Management
// Create bucket
const bucket = await sdk.storage.createBucket(
ID.unique(),
'Images',
[
Permission.read(Role.any()),
Permission.create(Role.users())
],
5000000, // 5MB max file size
['image/jpeg', 'image/png'] // Allowed file types
);
// Get bucket
const bucket = await sdk.storage.getBucket(
'bucketId'
);
// List buckets
const buckets = await sdk.storage.listBuckets();
// Update bucket
const bucket = await sdk.storage.updateBucket(
'bucketId',
'New Images'
);
// Delete bucket
await sdk.storage.deleteBucket(
'bucketId'
);
Functions Service
Function Management
// Create function
const fn = await sdk.functions.create(
ID.unique(),
'hello-world',
['node-18.0'],
'Hello world function'
);
// List functions
const functions = await sdk.functions.list();
// Get function
const fn = await sdk.functions.get(
'functionId'
);
// Update function
const fn = await sdk.functions.update(
'functionId',
'hello-world-updated',
['node-18.0'],
'Updated hello world function'
);
// Delete function
await sdk.functions.delete(
'functionId'
);
Deployments & Execution
// Create deployment
const deployment = await sdk.functions.createDeployment(
'functionId',
'main.js',
false, // activate immediately
fs.createReadStream('./function/main.js') // Function code
);
// Execute function
const execution = await sdk.functions.createExecution(
'functionId',
JSON.stringify({ key: 'value' }), // Optional data
false, // Async execution
'/redirectUrl', // Optional redirect URL
'GET', // HTTP method
{} // Optional headers
);
// Get execution
const execution = await sdk.functions.getExecution(
'functionId',
'executionId'
);
// List executions
const executions = await sdk.functions.listExecutions(
'functionId'
);
Teams Service
Team Management
// Create team
const team = await sdk.teams.create(
ID.unique(),
'Engineering',
[
Permission.read(Role.any()),
Permission.update(Role.team('teamId', 'owner'))
]
);
// Get team
const team = await sdk.teams.get(
'teamId'
);
// List teams
const teams = await sdk.teams.list();
// Update team
const team = await sdk.teams.update(
'teamId',
'Engineering Team'
);
// Delete team
await sdk.teams.delete(
'teamId'
);
Membership Management
// Create membership
const membership = await sdk.teams.createMembership(
'teamId',
['member'],
'https://example.com/callback',
'user@example.com'
);
// Get membership
const membership = await sdk.teams.getMembership(
'teamId',
'membershipId'
);
// List memberships
const memberships = await sdk.teams.listMemberships(
'teamId'
);
// Update membership
const membership = await sdk.teams.updateMembership(
'teamId',
'membershipId',
['admin']
);
// Delete membership
await sdk.teams.deleteMembership(
'teamId',
'membershipId'
);
Realtime Service
// Subscribe to changes
const unsubscribe = sdk.subscribe('collections.[databaseId].[collectionId].documents', response => {
console.log(response);
});
// Subscribe to multiple channels
const unsubscribe = sdk.subscribe([
'collections.[databaseId].[collectionId].documents',
'files.[bucketId]'
], response => {
console.log(response);
});
// Unsubscribe
unsubscribe();
Permissions System
Permission Types
// Read permission for anyone
Permission.read(Role.any())
// Write permission for authenticated users
Permission.write(Role.users())
// Create permission for specific user
Permission.create(Role.user('userId'))
// Update permission for team members
Permission.update(Role.team('teamId'))
// Delete permission for team admins
Permission.delete(Role.team('teamId', 'admin'))
Role Types
// Any user (including guests)
Role.any()
// Authenticated users
Role.users()
// Specific user
Role.user('userId')
// Team members
Role.team('teamId')
// Team members with specific role
Role.team('teamId', 'admin')
// Users with verified email
Role.users('verified')
Common Patterns & Recipes
User Registration with Verification
// Create user
const user = await sdk.account.create(
ID.unique(),
'email@example.com',
'password123',
'John Doe'
);
// Send verification email
await sdk.account.createVerification(
'https://example.com/verify'
);
// Complete verification
await sdk.account.updateVerification(
'userId',
'secret'
);
File Upload with Progress
// Upload file with progress
const file = await sdk.storage.createFile(
'bucketId',
ID.unique(),
document.getElementById('uploader').files[0],
[Permission.read(Role.any())],
(progress) => {
console.log(`Uploaded ${progress}%`);
}
);
Pagination Implementation
// Initial query
let offset = 0;
const limit = 25;
async function loadMore() {
const documents = await sdk.databases.listDocuments(
'databaseId',
'collectionId',
[
Query.limit(limit),
Query.offset(offset)
]
);
// Update offset for next page
offset += limit;
// Check if we have more results
const hasMore = documents.documents.length === limit;
return {
documents: documents.documents,
hasMore
};
}
Common Challenges & Solutions
| Challenge | Solution |
|---|---|
| CORS Issues | Configure allowed origins in Appwrite console |
| Rate Limiting | Implement proper error handling and retry mechanisms |
| Large File Uploads | Use chunked uploads for files over 5MB |
| Complex Queries | Create appropriate indexes to improve performance |
| Realtime Scaling | Use selective channel subscriptions to reduce overhead |
| Authentication Flow | Use OAuth or magic links for seamless UX |
| Function Timeouts | Break complex operations into smaller functions |
| Permission Errors | Check role-based access controls in console logs |
Security Best Practices
- Use environment variables for API keys and secrets
- Implement proper permission scopes for all resources
- Enable two-factor authentication for team members
- Regularly review access logs for suspicious activity
- Set secure password policies in project settings
- Use JWT expiration times appropriate to your use case
- Implement proper input validation in all function endpoints
- Use HTTPS for all API communications
Performance Optimization Tips
- Create appropriate indexes for frequently queried fields
- Use pagination for large data sets
- Implement caching for frequently accessed data
- Optimize query patterns to minimize data transfer
- Use batch operations where possible
- Compress assets before uploading to storage
- Implement lazy loading for media assets
- Monitor function execution times and optimize hotspots
Resources for Further Learning
- Appwrite Documentation – Official documentation
- Appwrite GitHub Repository – Source code and issues
- Appwrite Discord – Community support and discussions
- Appwrite Blog – Latest updates and tutorials
- Appwrite YouTube Channel – Video tutorials and webinars
- Awesome Appwrite – Curated list of resources
CLI Commands Reference
# Project commands
appwrite projects create --name="My Project"
appwrite projects list
appwrite projects get --projectId=123
appwrite projects delete --projectId=123
# Collection commands
appwrite databases collections create --databaseId=123 --name="Products"
appwrite databases collections list --databaseId=123
appwrite databases collections delete --databaseId=123 --collectionId=456
# Function commands
appwrite functions create --name="hello" --runtime="node-18.0"
appwrite functions createDeployment --functionId=123 --code="./function.zip"
appwrite functions createExecution --functionId=123
# Storage commands
appwrite storage buckets create --name="Images"
appwrite storage buckets list
appwrite storage files list --bucketId=123
This cheatsheet provides a comprehensive reference for Appwrite backend development, covering essential concepts, code examples, and best practices to help you build robust applications efficiently.
