Skip to content

Instantly share code, notes, and snippets.

@asabla
Created May 7, 2025 15:24
Show Gist options
  • Save asabla/f80439e26959a5616937e338a92db711 to your computer and use it in GitHub Desktop.
Save asabla/f80439e26959a5616937e338a92db711 to your computer and use it in GitHub Desktop.
Nodejs + typescript Azure Managed Identity example
import sql, { config, ConnectionPool } from "mssql";
import dotenv from "dotenv";
import { DefaultAzureCredential } from "@azure/identity";
dotenv.config();
async function getConfig(): Promise<config> {
const credential = new DefaultAzureCredential();
const tokenResponse = await credential.getToken("https://database.windows.net/.default");
return {
server: process.env.DB_SERVER || "localhost",
database: process.env.DB_NAME,
options: {
encrypt: true,
trustServerCertificate: true,
},
authentication: {
type: "azure-active-directory-access-token",
options: {
token: tokenResponse.token
},
},
} as config;
}
async function main() {
try {
const pool = await sql.connect(await getConfig());
console.log("Connected to the database successfully!");
const result = await pool.request().query("SELECT TOP 1 GETDATE() AS CurrentDateTime");
console.log("Query result:", result.recordset);
await pool.close();
} catch (error) {
console.error("Error connecting to the database:", error);
}
}
main().catch((error) => {
console.error("Error in main function:", error);
});
{
"name": "azure-sql-database",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "ts-node src/index.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs",
"dependencies": {
"@azure/identity": "^4.9.1",
"dotenv": "^16.5.0",
"mssql": "^11.0.1"
},
"devDependencies": {
"@types/mssql": "^9.1.7",
"@types/node": "^22.15.14",
"ts-node": "^10.9.1",
"typescript": "^5.8.3"
}
}
{
"compilerOptions": {
"target": "ES2020",
"module": "CommonJS",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment