Here's a production-ready approach to calling Supabase RPCs in JavaScript, including error handling, typing, and retry logic:
import { createClient } from '@supabase/supabase-js';
import { retry } from 'async-retry';
// Type definitions for better IDE support and type safety
interface SupabaseConfig {
url: string;
key: string;
timeout?: number;
maxRetries?: number;
}
interface RpcOptions {
timeout?: number;
retries?: number;
}
class SupabaseRpcClient {
private supabase;
private defaultTimeout: number;
private maxRetries: number;
constructor(config: SupabaseConfig) {
this.supabase = createClient(config.url, config.key, {
auth: {
persistSession: false
},
db: {
schema: 'public'
}
});
this.defaultTimeout = config.timeout || 30000;
this.maxRetries = config.maxRetries || 3;
}
async callRpc<T>(
procedureName: string,
params?: Record<string, any>,
options: RpcOptions = {}
): Promise<T> {
const timeout = options.timeout || this.defaultTimeout;
const retries = options.retries || this.maxRetries;
try {
const result = await retry(
async (bail) => {
try {
const response = await Promise.race([
this.supabase.rpc(procedureName, params),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('RPC Timeout')), timeout)
)
]);
if (response.error) {
// If it's a fatal error that shouldn't be retried
if (response.error.code === '23505' || response.error.code === '23503') {
bail(response.error);
return;
}
throw response.error;
}
return response.data;
} catch (error) {
if (error.message === 'RPC Timeout') {
throw error; // Will be retried
}
bail(error); // Fatal error, don't retry
return;
}
},
{
retries,
factor: 2,
minTimeout: 1000,
maxTimeout: 5000,
onRetry: (error, attempt) => {
console.warn(
`RPC ${procedureName} failed (attempt ${attempt}):`,
error.message
);
}
}
);
return result as T;
} catch (error) {
throw new Error(`RPC ${procedureName} failed: ${error.message}`);
}
}
}
// Usage example:
const rpcClient = new SupabaseRpcClient({
url: process.env.SUPABASE_URL!,
key: process.env.SUPABASE_KEY!,
timeout: 15000,
maxRetries: 3
});
// Example usage with TypeScript
interface UserStats {
total_posts: number;
total_likes: number;
}
try {
const stats = await rpcClient.callRpc<UserStats>(
'get_user_stats',
{ user_id: 123 },
{ timeout: 5000 }
);
console.log('User stats:', stats);
} catch (error) {
console.error('Failed to get user stats:', error);
}
For middleware or API route usage (Next.js example):
// pages/api/stats/[userId].ts
import { NextApiRequest, NextApiResponse } from 'next';
import { SupabaseRpcClient } from '@/lib/supabase-rpc';
const rpcClient = new SupabaseRpcClient({
url: process.env.SUPABASE_URL!,
key: process.env.SUPABASE_SERVICE_KEY!
});
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== 'GET') {
return res.status(405).json({ error: 'Method not allowed' });
}
const { userId } = req.query;
try {
const stats = await rpcClient.callRpc<UserStats>(
'get_user_stats',
{ user_id: parseInt(userId as string) }
);
res.status(200).json(stats);
} catch (error) {
console.error('RPC Error:', error);
res.status(500).json({
error: 'Failed to fetch user stats',
details: process.env.NODE_ENV === 'development' ? error.message : undefined
});
}
}
For React component usage:
// hooks/useRpc.ts
import { useState, useCallback } from 'react';
import { SupabaseRpcClient } from '@/lib/supabase-rpc';
const rpcClient = new SupabaseRpcClient({
url: process.env.NEXT_PUBLIC_SUPABASE_URL!,
key: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
});
export function useRpc<T>(procedureName: string) {
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const execute = useCallback(
async (params?: Record<string, any>) => {
setLoading(true);
setError(null);
try {
const result = await rpcClient.callRpc<T>(procedureName, params);
return result;
} catch (err) {
setError(err);
throw err;
} finally {
setLoading(false);
}
},
[procedureName]
);
return { execute, loading, error };
}
// Component usage
function UserStatsComponent({ userId }: { userId: number }) {
const { execute, loading, error } = useRpc<UserStats>('get_user_stats');
const [stats, setStats] = useState<UserStats | null>(null);
useEffect(() => {
async function fetchStats() {
try {
const result = await execute({ user_id: userId });
setStats(result);
} catch (err) {
console.error('Failed to fetch stats:', err);
}
}
fetchStats();
}, [userId, execute]);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
if (!stats) return null;
return (
<div>
<p>Total Posts: {stats.total_posts}</p>
<p>Total Likes: {stats.total_likes}</p>
</div>
);
}
This implementation includes:
- Proper error handling and typing
- Configurable timeouts
- Automatic retries with exponential backoff
- Request cancellation on timeout
- Environment-specific error reporting
- React hooks for easy component integration
- Type safety with TypeScript
- Logging for debugging
- Production-ready error messages
Remember to:
- Store sensitive keys in environment variables
- Add appropriate error monitoring (e.g., Sentry)
- Implement rate limiting if needed
- Add request logging for production debugging
- Consider adding circuit breaker patterns for high-traffic applications
- Add proper error boundaries in React components
- Implement proper security headers and CORS settings in API routes