Nodejs: How to get Dotenv configuration done first

Viewed 32

I'm getting an error when initialising Postmark 'Invalid api token'. I'm getting this error because my own environment variables aren't loaded yet.

In index.js I've got a start function. The first thing is configuring dotenv with the correct environment file (development/production/test).

The sendEmail file is loaded before the configuration. I can move the creation of the client inside the sendEmailConfirmationMail function but than I will have the initialize the client for every mail function.

Any other solution?

index.js

const __dirname = path.resolve();
    
// Load env vars
dotenv.config({ 
   path: path.join(__dirname, `./config/.env.${process.env.NODE_ENV}`)
});

const start = async () => {
    try {    
        // Connect to database
        await connectDB(process.env.DATABASE_URL);

        // Create app
        const app = express();

        // Body parser
        app.use(express.json())
        app.use(express.urlencoded({ extended: true }));

        // Cookie parser
        app.use(cookieParser());

        // Mount routes
        app.use(`/${process.env.API_VERSION}`, authRoutes);

        // Error handler
        app.use(errorHandler);

        // Not found handler
        app.use(notFoundHandler);

        // Start server
        const server = app.listen(process.env.PORT, () => {
            console.log(`Server running in ${process.env.NODE_ENV} mode on http://${process.env.HOST}:${process.env.PORT}/${process.env.API_VERSION}`)
        });

        // Handle unhandled promise rejections
        process.on('unhandledRejection', (reason, promise) => {
            console.log('UNHANDLED REJECTION!  Shutting down...');
            console.log('Unhandled rejection at:', promise, 'reason:', reason);

            // Close server and exit process
            server.close(() => process.exit(1));
        });

        process.on('uncaughtException', err => {
            console.log('UNCAUGHT EXCEPTION!  Shutting down...');
            console.log(err.name, err.message);
        
            // Close server and exit process
            server.close(() => process.exit(1));
        });
    } catch(error) {
        console.log('Server crashed');
        console.log(error);
    }
}

start();

package.json

"scripts": {
    "dev": "set NODE_ENV=production && nodemon --experimental-specifier-resolution=node index.js"
}

utils/sendEmail.js

import postmark from 'postmark';

const client = new postmark.ServerClient(process.env.POSTMARK_API_TOKEN);

export const sendEmailConfirmationMail = async (email, first_name, language, confirmation_token) => {    
    return client.sendEmailWithTemplate({
        To: email,
        From: process.env.MAIL_FROM,
        TemplateId: language === 'fr' ? 19699565 : 19699566,
        TemplateModel: {
            "first_name": first_name,
            "url": `${process.env.FRONTEND_URL}/confirm-email?confirmation_token=${confirmation_token}&email=${email}&lang=${language}`
        }
    });
}
0 Answers
Related