How to connect in database using async credentials?

System Information
  • Strapi Version: 4.12.0-beta-2
  • Operating System: MacOS
  • Database: Postgres
  • Node Version: 16
  • NPM Version: 8
  • Yarn Version:

Hello everyone,

I’m need get database credentials from Amazon Aws Secrets in a async call, but the database.ts file is syncronous so an error occur when Strapi try to connect in database:

Error: Unknown dialect undefined

So my question is: How to connect in database with async credentials?

Hello you can use register function from src/index.js. Register function is an async function.
Install aws-sdk. Call secret manager and inject credentials on strapi.config object.
Example :

const secretManager = new awsSdk.SecretsManager({
  region: 'eu-west-1',
})
const { SecretString } = await secretManager
  .getSecretValue({ SecretId: `<secret-id-secret-manager>` })
  .promise()
const { host, port, username, password, type, database } = JSON.parse(SecretString)
strapi.config.set('database.connection.client', type)
strapi.config.set('database.connection.connection.port', port)
1 Like

Could you please show the code changes that should be made to /config/database.js after the database configurations are set with strapi.config?

Hi !

That’s a good question. Is the database.js config the same as original or do you use the strapi.config.get instead of env(’…’, ‘…’) ?

Thanks

Thanks Glenn, thats a very usefult answer you provided.
For anyone whos is till confused, please write an async function in default register method in index.js in src folder for strapi v4

To connect to the database with async credentials, you’ll need to adjust your databases file to handle asynchronous operations. Instead of synchronous retrieval, utilize async/await syntax to fetch credentials from Amazon AWS Secrets Manager. Ensure robust error handling to address any issues during credential retrieval. Test thoroughly to verify the updated setup’s functionality. This approach should allow you to connect to the database without encountering the “Unknown dialect undefined” error. If you encounter any challenges, don’t hesitate to seek assistance.