node.jsglobalnodemailer

Create one nodemailer test account and hold it in a module global


I have a nodejs application. One of the modules is for the mail transporter. I'd like to create a mail test configuration one per launch and store it (in global) so it can be reused.

However, during the running of my application each time a module touches this module global.dev_mail_settings is always undefined and I get a brand new testAccount.

All the docs I have read say that global is supposed to retain the value. What am I doing wrong?

How can I make it do what I want?

import nodemailer from 'nodemailer'

const sendmailSettings = {
    // prod
}

let actualSettings = null

if (process.env.NODE_ENV === 'development') {
    if (!global.mail_settings) {            // <----- always undefined, even when set previously
        const account = await nodemailer.createTestAccount()

        const testAcount = {
            host: account.smtp.host,
            port: account.smtp.port,
            secure: account.smtp.secure,
            auth: {
                user: account.user,
                pass: account.pass
            }
        }
        global.mail_settings = testAcount  // <----- assignment ok
        console.log('==========================================================')
        console.log('Using mail credentials: ' + stringifyPretty(global.mail_settings))
        console.log('==========================================================')

    }
    actualSettings = global.mail_settings   // <----- usage ok

} else {
    actualSettings = sendmailSettings
}

const transporter = nodemailer.createTransport(actualSettings)

export default transporter

Solution

  • When the applications runs in NODE_ENV === 'development' each call is a fresh call. global is only remembered when running in NODE_ENV === 'production'.