npm.io
0.2.0-beta • Published 6 months ago

@neondatabase/postgrest-js

Licence
Apache-2.0
Version
0.2.0-beta
Deps
1
Size
28 kB
Vulns
0
Weekly
0
Stars
19

@neondatabase/postgrest-js

npm version npm downloads TypeScript License

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-js

Usage

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 fetch

Parameters:

  • getAccessToken: Async function that returns the current access token
  • customFetch: Optional custom fetch implementation (default: global fetch)

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: 'alice@example.com' })
  .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();

Support

License

Apache-2.0

Keywords