Node.js Quick Start
Build and deploy backend applications with Varity’s database, authentication, and hosting. This guide gets you started in under 5 minutes.
Prerequisites
Section titled “Prerequisites”- Node.js 18 or later
- npm or yarn
- TypeScript knowledge (recommended)
Installation
Section titled “Installation”Install the Varity SDK and types:
npm install @varity-labs/sdk @varity-labs/typesyarn add @varity-labs/sdk @varity-labs/typespnpm add @varity-labs/sdk @varity-labs/typesFor TypeScript projects, install type definitions:
npm install --save-dev @types/node typescriptQuick Start: Database CRUD
Section titled “Quick Start: Database CRUD”The fastest way to get started is with Varity’s built-in database. No configuration required.
1. Import the Database
Section titled “1. Import the Database”import { db } from '@varity-labs/sdk';
// The db instance is ready to use immediately// No connection strings, no setup required2. Define Your Data Types
Section titled “2. Define Your Data Types”export interface User { id?: string; name: string; email: string; role: 'admin' | 'user'; createdAt: string;}
export interface Post { id?: string; title: string; content: string; authorId: string; published: boolean; createdAt: string;}3. Basic CRUD Operations
Section titled “3. Basic CRUD Operations”-
Create (Add Documents)
import { db } from '@varity-labs/sdk';import type { User } from './types';async function createUser(name: string, email: string) {const result = await db.collection<User>('users').add({name,email,role: 'user',createdAt: new Date().toISOString(),});console.log('Created user:', result);// Returns: { id: 'doc_abc123', success: true }}createUser('Alice Johnson', 'alice@example.com'); -
Read (Get Documents)
// Get all documentsasync function getAllUsers() {const users = await db.collection<User>('users').get();console.log('All users:', users);// Returns: [{ id: 'doc_123', name: 'Alice', email: '...', ... }, ...]}// Get a specific user by filteringasync function getUserById(id: string) {const users = await db.collection<User>('users').get();const user = users.find((u) => u.id === id);console.log('User:', user);// Returns: { id: 'doc_123', name: 'Alice', email: '...', ... }}// Get with paginationasync function getRecentUsers() {const users = await db.collection<User>('users').get({limit: 10,offset: 0,orderBy: '-createdAt', // Prefix with - for descending});return users;} -
Update Documents
async function updateUser(id: string, updates: Partial<User>) {await db.collection<User>('users').update(id, updates);console.log('User updated successfully');}// Update specific fieldsupdateUser('doc_abc123', {name: 'Alice Updated',role: 'admin',}); -
Delete Documents
async function deleteUser(id: string) {await db.collection<User>('users').delete(id);console.log('User deleted successfully');}deleteUser('doc_abc123');
Complete Example: REST API
Section titled “Complete Example: REST API”Here’s a complete Express.js API with CRUD operations:
import express from 'express';import { db } from '@varity-labs/sdk';import type { User } from './types';
const app = express();app.use(express.json());
// Get all usersapp.get('/api/users', async (req, res) => { try { const users = await db.collection<User>('users').get(); res.json({ success: true, data: users }); } catch (error) { res.status(500).json({ success: false, error: error instanceof Error ? error.message : 'Failed to fetch users', }); }});
// Get user by IDapp.get('/api/users/:id', async (req, res) => { try { const users = await db.collection<User>('users').get(); const user = users.find((u) => u.id === req.params.id); if (!user) { return res.status(404).json({ success: false, error: 'User not found' }); } res.json({ success: true, data: user }); } catch (error) { res.status(500).json({ success: false, error: error instanceof Error ? error.message : 'Failed to fetch user', }); }});
// Create userapp.post('/api/users', async (req, res) => { try { const { name, email, role } = req.body;
// Validation if (!name || !email) { return res.status(400).json({ success: false, error: 'Name and email are required', }); }
const result = await db.collection<User>('users').add({ name, email, role: role || 'user', createdAt: new Date().toISOString(), });
res.status(201).json({ success: true, data: result }); } catch (error) { res.status(500).json({ success: false, error: error instanceof Error ? error.message : 'Failed to create user', }); }});
// Update userapp.patch('/api/users/:id', async (req, res) => { try { const updates = req.body; await db.collection<User>('users').update(req.params.id, updates); res.json({ success: true }); } catch (error) { res.status(500).json({ success: false, error: error instanceof Error ? error.message : 'Failed to update user', }); }});
// Delete userapp.delete('/api/users/:id', async (req, res) => { try { await db.collection<User>('users').delete(req.params.id); res.json({ success: true }); } catch (error) { res.status(500).json({ success: false, error: error instanceof Error ? error.message : 'Failed to delete user', }); }});
const PORT = process.env.PORT || 3000;app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`);});Run the server:
npx tsx src/server.tsEnvironment Setup
Section titled “Environment Setup”Development (Local)
Section titled “Development (Local)”During development, Varity uses shared development credentials automatically. No configuration needed.
// Works immediately - no env vars requiredimport { db } from '@varity-labs/sdk';
const users = await db.collection('users').get();Production
Section titled “Production”For production deployments, configure these environment variables:
VARITY_APP_ID=your-app-idVARITY_APP_TOKEN=your-app-tokenVARITY_DB_PROXY_URL=your-db-proxy-urlError Handling Best Practices
Section titled “Error Handling Best Practices”Always wrap database operations in try-catch blocks:
import { db } from '@varity-labs/sdk';
async function safeGetUser(id: string) { try { const users = await db.collection('users').get(); const user = users.find((u) => u.id === id); return { success: true, data: user ?? null }; } catch (error) { console.error('Database error:', error); return { success: false, error: error instanceof Error ? error.message : 'Unknown error', }; }}Filtering and Querying
Section titled “Filtering and Querying”// Get all users, then filterconst allUsers = await db.collection<User>('users').get();
// Filter by roleconst admins = allUsers.filter((user) => user.role === 'admin');
// Filter by email domainconst companyUsers = allUsers.filter((user) => user.email.endsWith('@company.com'));
// Combine filtersconst recentAdmins = allUsers .filter((user) => user.role === 'admin') .filter((user) => { const created = new Date(user.createdAt); const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000); return created > weekAgo; });TypeScript Tips
Section titled “TypeScript Tips”Use Explicit Types
Section titled “Use Explicit Types”import type { User } from './types';
// Explicit type ensures type safetyconst users = await db.collection<User>('users').get();
// TypeScript knows user fields are typed as Userusers.forEach((user) => { console.log(user.name); // Type-safe console.log(user.invalid); // TypeScript error});Define Return Types
Section titled “Define Return Types”async function getUser(id: string): Promise<(User & { id: string }) | undefined> { const users = await db.collection<User>('users').get(); return users.find((u) => u.id === id);}
async function getAllUsers(): Promise<Array<User & { id: string }>> { return await db.collection<User>('users').get();}Non-Null Assertions for IDs
Section titled “Non-Null Assertions for IDs”// After adding a documentconst result = await db.collection<User>('users').add(userData);const userId = result.id; // string | undefined
// Use non-null assertion if you know add() succeededawait db.collection<User>('users').update(result.id!, updates);
// Or check explicitlyif (result.id) { await db.collection<User>('users').update(result.id, updates);}Common Patterns
Section titled “Common Patterns”Collection Factory
Section titled “Collection Factory”Create reusable collection accessors:
import { db } from '@varity-labs/sdk';import type { User, Post } from './types';
export const users = () => db.collection<User>('users');export const posts = () => db.collection<Post>('posts');Use in your app:
import { users, posts } from './lib/database';
// Clean, reusable syntaxconst allUsers = await users().get();const allPosts = await posts().get();
await users().add({ name: 'Bob', email: 'bob@example.com', role: 'user', createdAt: new Date().toISOString() });Pagination Helper
Section titled “Pagination Helper”async function paginate<T>( collection: string, page: number, pageSize: number = 20) { const offset = (page - 1) * pageSize; const items = await db.collection<T>(collection).get({ limit: pageSize, offset, });
return { items, page, pageSize, hasMore: items.length === pageSize, };}
// Usageconst result = await paginate<User>('users', 1, 10);console.log(`Page ${result.page}:`, result.items);Batch Operations
Section titled “Batch Operations”async function batchCreate(users: Array<Omit<User, 'id'>>) { const promises = users.map((user) => db.collection<User>('users').add(user) );
const results = await Promise.all(promises); return results;}
// Create 3 users in parallelawait batchCreate([ { name: 'Alice', email: 'alice@example.com', role: 'user', createdAt: new Date().toISOString() }, { name: 'Bob', email: 'bob@example.com', role: 'admin', createdAt: new Date().toISOString() }, { name: 'Carol', email: 'carol@example.com', role: 'user', createdAt: new Date().toISOString() },]);Deploy Your App
Section titled “Deploy Your App”Once your Node.js app is ready, deploy it with one command:
-
Install the CLI
Terminal window pip install varitykit -
Deploy your app
Terminal window varitykit app deploy -
Your app is live
Varity automatically:
- Builds your app
- Generates production credentials
- Deploys to global infrastructure
- Provides a live URL
Next Steps
Section titled “Next Steps”Now that you have a working Node.js backend:
- Authentication - Add user authentication to your API
- Deploy Guide - Advanced deployment options
- Database Guide - Full database documentation with React hooks
- Environment Variables - Configure production credentials
Full SDK Reference
Section titled “Full SDK Reference”For complete API documentation, see:
- Database Module - All database methods
- Types Package - TypeScript type definitions
- CLI Commands - All CLI commands and options