npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

postgres-entra-auth

v1.0.0

Published

Azure Entra ID authentication extension for PostgreSQL in JavaScript

Readme

postgres-entra-auth: Azure Database for PostgreSQL Entra ID Authentication (JavaScript)

This package provides seamless Azure Entra ID authentication for JavaScript/Node.js database drivers connecting to Azure Database for PostgreSQL. It supports both Sequelize ORM and the native pg driver with automatic token management and connection pooling.

Features

  • 🔐 Azure Entra ID Authentication: Automatic token acquisition and refresh for secure database connections
  • 🔄 Multi-Driver Support: Works with Sequelize ORM and node-postgres (pg) driver
  • ⚡ Connection Pooling: Built-in support for connection pooling with automatic token refresh
  • 🌐 Cross-platform: Works on Windows, Linux, and macOS
  • 📦 Flexible Peer Dependencies: Use with your existing Sequelize or pg installation

Installation

Basic Installation

Install the package:

npm install postgres-entra-auth

With Sequelize

Install Sequelize and the pg driver as peer dependencies:

npm install postgres-entra-auth sequelize pg

With pg Driver

Install the pg driver as a peer dependency:

npm install postgres-entra-auth pg

Quick Start

The repository includes comprehensive working examples in the samples/ directory:

  • samples/pg/getting-started/: node-postgres (pg) examples
  • samples/sequelize/getting-started/: Sequelize ORM examples

Configure your environment variables first, then run the samples:

# Copy and configure environment (if using .env file)
cp samples/pg/getting-started/.env.example samples/pg/getting-started/.env
# Edit .env with your Azure PostgreSQL server details

# Test pg driver
node samples/pg/getting-started/create-db-connection.js

# Test Sequelize with hook
node samples/sequelize/getting-started/create-db-connection-hook.js

pg Driver Integration

The pg driver integration provides connection support with Azure Entra ID authentication through a dynamic password function.

import { Pool } from 'pg';
import { getPassword } from 'postgres-entra-auth';

const pool = new Pool({
  host: process.env.PGHOST,
  port: process.env.PGPORT,
  database: process.env.PGDATABASE,
  user: process.env.PGUSER,
  password: getPassword, // Dynamic password function
  ssl: { rejectUnauthorized: true },
  connectionTimeoutMillis: 10000,
  idleTimeoutMillis: 30000,
  max: 10, // Maximum pool size
  min: 2   // Minimum pool size
});

// Use the pool
const client = await pool.connect();

Sequelize Integration

Sequelize integration uses pg as the backend driver with automatic Entra ID authentication through hooks.

import { Sequelize } from 'sequelize';
import { configureEntraIdAuth } from 'postgres-entra-auth';

const sequelize = new Sequelize({
  dialect: 'postgres',
  host: process.env.PGHOST,
  port: process.env.PGPORT,
  database: process.env.PGDATABASE,
  dialectOptions: { 
    ssl: { rejectUnauthorized: true } 
  },
  pool: { 
    min: 2, 
    max: 10, 
    idle: 30000 
  }
});

// Configure Entra ID authentication
configureEntraIdAuth(sequelize, {
  fallbackUsername: 'my-db-user' // Optional fallback username
});

await sequelize.authenticate();
console.log('Connection established successfully.');

How It Works

  1. Token Acquisition: Uses Azure Identity libraries (DefaultAzureCredential by default) to acquire access tokens from Azure Entra ID
  2. Automatic Refresh: Tokens are automatically refreshed before each new database connection
  3. Secure Transport: Tokens are passed as passwords in PostgreSQL connection strings over SSL
  4. Server Validation: Azure Database for PostgreSQL validates the token and establishes the authenticated connection
  5. User Mapping: The token's user principal name (UPN) or application ID is mapped to a PostgreSQL user for authorization

Troubleshooting

Common Issues

Authentication Errors

# Error: "password authentication failed"
# Solution: Ensure your Azure identity has been granted access to the database
# Run this SQL as a database administrator:
CREATE ROLE "[email protected]" WITH LOGIN;
GRANT ALL PRIVILEGES ON DATABASE your_database TO "[email protected]";

Connection Timeouts

// Increase connection timeout for slow networks
const pool = new Pool({
  host: process.env.PGHOST,
  database: process.env.PGDATABASE,
  password: getPassword,
  connectionTimeoutMillis: 30000  // 30 seconds instead of default
});

Development

Prerequisites

  • Node.js 18+
  • npm or yarn

Setup

# Clone the repository
git clone https://github.com/Azure/postgres-entra-auth.git
cd postgres-entra-auth/javascript

# Install dependencies
npm install

Available Scripts

# Run tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm run test:coverage

# Lint code
npm run lint

# Fix linting issues
npm run lint:fix

# Format code
npm run format

# Check formatting
npm run format:check

# Run sample applications
npm run samples:pg
npm run samples:sequelize-hook

Running Quality Checks

Run all quality checks locally before pushing:

# Run all checks (install, lint, format, test)
.\scripts\run-javascript-checks.ps1

# Skip npm install if dependencies are already installed
.\scripts\run-javascript-checks.ps1 -SkipInstall

Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

Development Workflow

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Run quality checks (.\scripts\run-javascript-checks.ps1)
  5. Commit your changes (git commit -m 'Add some amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.


Support

For support and questions: