@neondatabase/postgrest-js
v0.2.0-beta
Published
PostgreSQL client for Neon Data API - query your database without authentication
Downloads
103,783
Readme
@neondatabase/postgrest-js
Generic PostgreSQL client for Neon Data API without built-in authentication.
Overview
@neondatabase/postgrest-js provides a lightweight PostgreSQL client for querying Neon databases without requiring Neon Auth integration. It's ideal for scenarios where:
- Authentication is handled externally (e.g., API keys, custom auth providers)
- You want to bring your own token management
- You need a minimal client without auth dependencies
For auth-integrated clients, use @neondatabase/neon-js instead.
Installation
npm install @neondatabase/postgrest-js
# or
bun add @neondatabase/postgrest-jsUsage
Basic Client
import { NeonPostgrestClient } from '@neondatabase/postgrest-js';
const client = new NeonPostgrestClient({
dataApiUrl: 'https://ep-xxx.apirest.region.aws.neon.build/dbname/rest/v1',
options: {
global: {
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
},
},
db: {
schema: 'public',
},
},
});
// Query your database
const { data, error } = await client
.from('users')
.select('*')
.eq('status', 'active');With Token Provider
Use fetchWithToken() for dynamic token resolution:
import { NeonPostgrestClient, fetchWithToken } from '@neondatabase/postgrest-js';
// Your token provider function
const getToken = async () => {
// Fetch from your auth system, environment, etc.
return process.env.DATABASE_TOKEN;
};
const client = new NeonPostgrestClient({
dataApiUrl: 'https://ep-xxx.apirest.region.aws.neon.build/dbname/rest/v1',
options: {
global: {
fetch: fetchWithToken(getToken),
},
},
});
// Automatically injects token on every request
const { data } = await client.from('posts').select();Custom Fetch Implementation
import { NeonPostgrestClient, fetchWithToken } from '@neondatabase/postgrest-js';
const customFetch: typeof fetch = async (input, init) => {
console.log('Making request:', input);
return fetch(input, init);
};
const client = new NeonPostgrestClient({
dataApiUrl: 'https://ep-xxx.apirest.region.aws.neon.build/dbname/rest/v1',
options: {
global: {
fetch: fetchWithToken(getToken, customFetch),
},
},
});API Reference
NeonPostgrestClient
Extends the upstream PostgrestClient with Neon-specific configuration.
Constructor Options:
type NeonPostgrestClientConstructorOptions<SchemaName> = {
dataApiUrl: string;
options?: {
db?: {
schema?: SchemaName; // Database schema (default: 'public')
};
global?: {
fetch?: typeof fetch; // Custom fetch implementation
headers?: Record<string, string>; // Global headers
};
};
};Example:
const client = new NeonPostgrestClient({
dataApiUrl: 'https://your-api-url.com/rest/v1',
options: {
db: { schema: 'public' },
global: {
headers: { 'X-Custom-Header': 'value' },
},
},
});fetchWithToken()
Generic fetch wrapper that injects authentication tokens.
Signature:
function fetchWithToken(
getAccessToken: () => Promise<string | null>,
customFetch?: typeof fetch
): typeof fetchParameters:
getAccessToken: Async function that returns the current access tokencustomFetch: Optional custom fetch implementation (default: globalfetch)
Returns: Wrapped fetch function that automatically adds Authorization: Bearer <token> header
Throws: AuthRequiredError if getAccessToken() returns null
Example:
const authFetch = fetchWithToken(async () => {
return await getTokenFromYourAuthSystem();
});
// Use with client
const client = new NeonPostgrestClient({
dataApiUrl: 'https://api.example.com',
options: { global: { fetch: authFetch } },
});AuthRequiredError
Error thrown when a request requires authentication but no token is available.
class AuthRequiredError extends Error {
constructor(message?: string);
}Usage:
import { AuthRequiredError } from '@neondatabase/postgrest-js';
try {
await client.from('users').select();
} catch (error) {
if (error instanceof AuthRequiredError) {
console.error('Authentication required');
}
}Querying
All PostgrestClient query methods are available:
// SELECT
const { data } = await client
.from('users')
.select('id, name, email')
.eq('status', 'active')
.order('created_at', { ascending: false })
.limit(10);
// INSERT
const { data } = await client
.from('users')
.insert({ name: 'Alice', email: '[email protected]' })
.select();
// UPDATE
const { data } = await client
.from('users')
.update({ status: 'inactive' })
.eq('id', 123);
// DELETE
const { data } = await client
.from('users')
.delete()
.eq('id', 123);
// RPC (stored procedures)
const { data } = await client
.rpc('get_user_stats', { user_id: 123 });Environment Compatibility
Works in both browser and Node.js environments:
- Browser: Full fetch API support
- Node.js: Works with Node.js 18+ native fetch or polyfills
TypeScript
Full TypeScript support with generic database types:
interface Database {
public: {
users: {
Row: { id: number; name: string; email: string };
Insert: { name: string; email: string };
Update: { name?: string; email?: string };
};
};
}
const client = new NeonPostgrestClient<Database>({
dataApiUrl: 'https://api.example.com',
});
// Fully typed!
const { data } = await client.from('users').select();Related Packages
@neondatabase/neon-js- Full SDK with Neon Auth integration@neondatabase/auth- Standalone auth adapters
Support
License
Apache-2.0
