@aws/aurora-dsql-postgresjs-connector

中文文档
0.3.1发布于 2026/09/22Apache-2.0TypeScriptESM + CJS构建来源已验证近 30 天下载 1.1万

An AWS Aurora DSQL connector with IAM authentication for Postgres.js

原始使用文档
文档目录22 节
  1. About the Connector
  2. What is Aurora DSQL Authentication?
  3. Features
  4. Quick start guide
  5. Requirements
  6. ⚠️ Important
  7. Installation
  8. Basic Usage
  9. Connection String
  10. Advanced Configuration
  11. OCC Retry
  12. Configuration Options
  13. Websocket Connector
  14. Use Case - Environments Without TCP Sockets
  15. Use Case - Browser Applications
  16. Basic Usage
  17. Configuration Options
  18. Authentication
  19. Admin vs Regular Users
  20. Sample usage
  21. Development
  22. License

Aurora DSQL Connector for Postgres.js

GitHub License NPM Version Discord chat

The Aurora DSQL Connector for Postgres.js is a Node.js connector built on Postgres.js that integrates IAM Authentication for connecting JavaScript applications to Amazon Aurora DSQL clusters.

The Aurora DSQL Connector for Postgres.js is designed as an authentication plugin that extends the functionality of the Postgres.js client to enable applications to authenticate with Amazon Aurora DSQL using IAM credentials. The connector does not connect directly to the database, but provides seamless IAM authentication on top of the underlying Postgres.js driver.

About the Connector

Amazon Aurora DSQL is a distributed SQL database service that provides high availability and scalability for PostgreSQL-compatible applications. Aurora DSQL requires IAM-based authentication with time-limited tokens that existing Node.js drivers do not natively support.

The idea behind the Aurora DSQL Connector for Postgres.js is to add an authentication layer on top of the Postgres.js client that handles IAM token generation, allowing users to connect to Aurora DSQL without changing their existing Postgres.js workflows.

The Aurora DSQL Connector for Postgres.js works with most versions of Postgres.js. Users provide their own version by installing Postgres.js directly.

What is Aurora DSQL Authentication?

In Aurora DSQL, authentication involves:

  • IAM Authentication: All connections use IAM-based authentication with time-limited tokens
  • Token Generation: Authentication tokens are generated using AWS credentials and have configurable lifetimes

The Aurora DSQL Connector for Postgres.js is designed to understand these requirements and automatically generate IAM authentication tokens when establishing connections.

Features

  • Automatic IAM Authentication - Handles DSQL token generation and refresh
  • Built on Postgres.js - Leverages the fast PostgreSQL client for Node.js
  • Seamless Integration - Works with existing Postgres.js connection patterns
  • Region Auto-Discovery - Extracts AWS region from DSQL cluster hostname
  • Full TypeScript Support - Provides full type safety
  • AWS Credentials Support - Supports various AWS credential providers (default, profile-based, custom)
  • Connection Pooling Compatibility - Works seamlessly with Postgres.js' built-in connection pooling
  • OCC Retry - Automatic retry with exponential backoff on optimistic concurrency conflicts

Quick start guide

Requirements

  • Node.js 20+
  • Access to an Aurora DSQL cluster
  • Set up appropriate IAM permissions to allow your application to connect to Aurora DSQL.
  • AWS credentials configured (via AWS CLI, environment variables, or IAM roles)

⚠️ Important

  • Running this code might result in charges to your AWS account.
  • We recommend that you grant your code least privilege. At most, grant only the minimum permissions required to perform the task. For more information, see Grant least privilege.
  • This code is not tested in every AWS Region. For more information, see AWS Regional Services.

Installation

npm install @aws/aurora-dsql-postgresjs-connector
# Postgres.js is a peer-dependency, so users must install it themselves
npm install postgres

Basic Usage

import { auroraDSQLPostgres } from '@aws/aurora-dsql-postgresjs-connector';

const sql = auroraDSQLPostgres({
  host: 'your-cluster.dsql.us-east-1.on.aws',
  username: 'admin',
    
});

// Execute queries
const users = await sql`SELECT * FROM users WHERE age > ${25}`;
console.log(users);

// Clean up
await sql.end();

Using cluster ID instead of host

const sql = auroraDSQLPostgres({
  host: 'your-cluster-id',
  region: 'us-east-1',
  username: 'admin',
    
});

Connection String

const sql = AuroraDSQLPostgres(
  'postgres://[email protected]'
);

const result = await sql`SELECT current_timestamp`;

Advanced Configuration

import { fromNodeProviderChain } from '@aws-sdk/credential-providers';

const sql = AuroraDSQLPostgres({
  host: 'your-cluster.dsql.us-east-1.on.aws',
  database: 'postgres',
  username: 'admin',
  customCredentialsProvider: fromNodeProviderChain(), // Optionally provide custom credentials provider
  tokenDurationSecs: 3600,                            // Token expiration (seconds)
  
  // Standard Postgres.js options
  max: 20,                              // Connection pool size
  ssl: { rejectUnauthorized: false }    // SSL configuration
});

OCC Retry

Aurora DSQL uses optimistic concurrency control (OCC). Transactions that conflict are rejected at commit time with error codes OC000, OC001, or 40001. The connector can automatically retry begin() transactions on these conflicts with exponential backoff.

import { auroraDSQLPostgres } from '@aws/aurora-dsql-postgresjs-connector';

// Opt-in at connection level — all begin() calls will retry on OCC conflicts
const sql = auroraDSQLPostgres({
  host: 'your-cluster.dsql.us-east-1.on.aws',
  username: 'admin',
  retry: true,
});

// No per-call config needed
await sql.begin(async (tx) => {
  await tx`INSERT INTO accounts(id, balance) VALUES(${1}, ${100})`;
});

The retry config accepts a partial object — unset fields use defaults:

FieldDefaultDescription
maxRetries3Number of retry attempts after the initial try (0 = no retry)
baseDelayMs1Initial backoff delay in ms
maxDelayMs100Maximum base backoff delay in ms (jitter is added on top)
jitterFactor0.25Jitter as a fraction of delay

Per-call opt-in/out:

// Per-call opt-in (no constructor config needed)
await sql.begin(async (tx) => { ... }, { retry: true });
await sql.begin(async (tx) => { ... }, { retry: { maxRetries: 10 } });

// Per-call opt-out (overrides constructor config)
await sql.begin(async (tx) => { ... }, { retry: false });

Note: The callback may be invoked multiple times on OCC conflicts. Keep it idempotent - avoid non-database side effects (HTTP calls, message publishes, external counters) inside the transaction body.

Configuration Options

OptionTypeRequiredDescription
hoststringYesDSQL cluster hostname or cluster ID
databasestring?NoDatabase name
usernamestring?NoDatabase username (uses admin if not provided)
regionstring?NoAWS region (auto-detected from hostname if not provided)
customCredentialsProviderAwsCredentialIdentityProvider?NoCustom AWS credentials provider
tokenDurationSecsnumber?NoToken expiration time in seconds
retryPartial<OCCRetryConfig> | booleanNoOCC retry configuration (see above)
loggerLoggerNoLogger with error method and optional debug (e.g. console)

All standard Postgres.js options are also supported.

Websocket Connector

The websocket connector provides an alternative connection method to Aurora DSQL using WebSockets instead of standard TCP sockets. This is designed for environments where TCP sockets are unavailable. For Node.js server applications, use the standard TCP socket connector shown above.

Use Case - Environments Without TCP Sockets

Some JavaScript runtimes don't provide TCP socket support. The WebSocket connector enables DSQL connections from these environments. If credentials remain server-controlled, the security model is similar to traditional server-side applications and credentials can be configured using your platform's secrets management (e.g., environment variables, secrets store).

Use Case - Browser Applications

Web browsers don't support TCP sockets. The WebSocket connector enables direct browser-to-database connections for use cases like internal tools, prototypes, or applications where users can safely have direct database access.

⚠️ Security Considerations for Browser Usage

When using the WebSocket connector from a browser, the database connection runs in an environment controlled by the end user. This has important security implications:

  • Users can execute any query their database role permits. There is no server-side layer to validate, filter, or restrict queries. The browser's JavaScript can be inspected and modified.

  • Database role permissions are your access control boundary. The IAM role grants connection ability, but the PostgreSQL database role determines what data the user can access. Configure database roles with minimal necessary permissions.

This approach is appropriate when users should have direct database access such as internal admin tools, single-user applications, or scenarios with properly scoped database roles. It is not a substitute for a backend API when you need to control what queries users can run.

For guidance on configuring IAM roles and database permissions, see:

Basic Usage

import type { AwsCredentialIdentity } from '@aws-sdk/types';
import { auroraDSQLWsPostgres, AuroraDSQLWsConfig } from '@aws/aurora-dsql-postgresjs-connector';

// For testing only, DO NOT USE in a production environment
const simulateSecureGetCredentialsAPI = (): Promise<AwsCredentialIdentity> => {
  // Users must retrieve the AwsCredentialIdentity through a secure API
  // DO NOT store the IAM accessKeyId and secretAccessKey inside the JavaScript source code
  // for more details, refer to the example in the folder "example/src/alternative/websocket"
};

const config: AuroraDSQLWsConfig<{}> = {
  host: 'your-cluster.dsql.us-east-1.on.aws',
  database: "postgres",
  user: "admin",
  customCredentialsProvider: simulateSecureGetCredentialsAPI,
};

const sql = auroraDSQLWsPostgres(config);

const result = await sql`SELECT version()`;
console.log(result);
await sql.end();

Configuration Options

OptionTypeRequiredDescription
hoststringYesDSQL cluster hostname or cluster ID
databasestring?NoDatabase name
usernamestring?NoDatabase username (uses admin if not provided)
regionstring?NoAWS region (auto-detected from hostname if not provided)
customCredentialsProviderAwsCredentialIdentityProvider?NoCustom AWS credentials provider
tokenDurationSecsnumber?NoToken expiration time in seconds
connectionCheckboolean?NoPerform a heart beat connectivity check withSelect 1 before every query (Default: false)
connectionIdstring?NoAn optional connection identifier to be used in the onReservedConnectionClose callback
onReservedConnectionClose(connectionId?: string) => void?NoA callback that is executed upon unexpected closure of a reserved connection, such as a heartbeat failure. The connectionId is passed to the callback when available.

Other standard Postgres.js options are also supported, except for socket, port, and ssl, which have default values.

Authentication

The connector automatically handles DSQL authentication by generating tokens using the DSQL client token generator. If the AWS region is not provided, it will be automatically parsed from the hostname provided.

For more information on authentication in Aurora DSQL, see the user guide.

Admin vs Regular Users

  • Users named "admin" automatically use admin authentication tokens
  • All other users use regular authentication tokens
  • Tokens are generated dynamically for each connection

Sample usage

An JavaScript example using the Aurora DSQL Connector for Postgres.js is available here.

Development

# Install dependencies
npm install

# Build the project
npm run build

# Set a cluster for use in integration tests
export CLUSTER_ENDPOINT=your-cluster.dsql.us-east-1.on.aws

# Run tests
npm run test

# Alternatively, run only unit or integration tests
npm run test:unit
npm run test:integration

License

This software is released under the Apache 2.0 license.

Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0

版本与发布记录

@aws/aurora-dsql-postgresjs-connector 共发布 8 个版本,首次发布于 2025/10/30;过去 12 个月发布了 7 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.3.1latest2026/09/221 个月前
0.3.02026/05/235 个月前
0.2.12026/02/069 个月前
0.2.02026/01/179 个月前
0.1.32025/12/3110 个月前
0.1.22025/12/1210 个月前

关于 @aws/aurora-dsql-postgresjs-connector 的常见问题

@aws/aurora-dsql-postgresjs-connector 是什么?

An AWS Aurora DSQL connector with IAM authentication for Postgres.js

如何安装 @aws/aurora-dsql-postgresjs-connector?

在项目目录运行 npm install @aws/aurora-dsql-postgresjs-connector,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:postgres(^3.4.7)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@aws/aurora-dsql-postgresjs-connector 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@aws/aurora-dsql-postgresjs-connector 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@aws/aurora-dsql-postgresjs-connector 可以商用吗?

@aws/aurora-dsql-postgresjs-connector 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@aws/aurora-dsql-postgresjs-connector 的下载量有多少?

根据 npm 官方下载统计,@aws/aurora-dsql-postgresjs-connector 在 2026/10/08 – 2026/11/06 这 30 天内被下载 11,396 次,日均约 380 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@aws/aurora-dsql-postgresjs-connector 还在维护吗?

最新版本 0.3.1 发布于 2026/09/22(1 个月前);至今共发布 8 个版本,其中过去 12 个月发布了 7 个;首次发布于 2025/10/30。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。