Credentials dynamically

Is there a way to pass database credentials dynamically when connecting to Microsoft SQL Server? Each request to the project can come from a different client, and I have too many clients to put them all in a map. I already receive the database credentials (for SQL Server) with each request — I just need to know how to pass them dynamically to establish the connection.

1 Like

Hi @jw_sistemas Welcome!
Yes, you can use expressions in the credentials field, just swtich your fields to expression mode and then enter your values:

{{ $json.db_host }}
{{ $json.db_user }}
{{ $json.db_password }}

somewhat like that i suppose, and as workflow data is divided into runs so there would not be any mismatch, HOWEVER, this works for populating fields with content dynamically, not switching between multiple credentials as that is not supported currently.

@jw_sistemas as Anshul noted his expression-in-cred-field approach can’t switch between multiple credentials — for that case the workaround is a Code node with the mssql package, host/user/pass come straight from $json so each request opens its own connection:

const sql = require('mssql');
const c = $input.first().json;
await sql.connect({
  server: c.host,
  user: c.user,
  password: c.pass,
  database: c.db
});
const r = await sql.query(c.query);
return r.recordset;

NODE_FUNCTION_ALLOW_EXTERNAL=mssql has to be set on your n8n env, otherwise the require fails.

@achamm just a question regarding this.

Can we actually ‘require’ packages and the Code node will auto fetch them before running? I thought we had to install them beforehand in the host env or docker image?

Assuming the .env var is set to allow all external pkgs.

(anyway, @jw_sistemas if you need help on adding custom packages to your n8n instance just ping here)