MONGO_URI Undefined

No matter what I do, setting the MONGO_URI in service variables fails and gives undefined.

I tried:

  • setting it with ?retryWrites=true&w=majority suffix and without
  • adding it as a secret
  • adding it with quotation marks
  • writing it as a literal string in constants/index.js
  • with and without explicitly setting production environment for the deployment and making sure dotenv is not used in the deployment
  • adding it as APP_MONGO_URI

What am I missing??

Deployment settings (showing I have MONGO_URI set):

{"name":"match-platform","type":"WEB","strategy":{"type":"DEPLOYMENT_STRATEGY_TYPE_ROLLING"},"routes":[{"port":8080,"path":"/"}],"ports":[{"port":8080,"protocol":"http"}],"env":[{"scopes":["region:fra"],"key":"MONGO_URI","value":"mongodb+srv://fgaletic:<password>@couplis.w8n7v.mongodb.net/Couplis/?retryWrites=true&w=majority"}],"regions":["fra"],"scalings":[{"scopes":["region:fra"],"min":1,"max":1,"targets":[]}],"instance_types":[{"scopes":["region:fra"],"type":"free"}],"health_checks":[{"grace_period":5,"interval":30,"restart_limit":3,"timeout":5,"tcp":{"port":8080}}],"volumes":[],"files":[],"skip_cache":false,"git":{"repository":"github.com/fgaletic/match-platform","branch":"main","tag":"","sha":"","build_command":"","run_command":"","no_deploy_on_push":false,"workdir":"","buildpack":{"build_command":"","run_command":"","privileged":false}}}

Hi @Filip_Galetic,

How do you use this env var? What gives you the “undefined” error?

Thanks for the reply.

I have a Turbo monorepo with client and server and within server I have:

  • constants/index.js: This file contains the environment variable definitions, including MONGO_URI and JWT_SECRET.
require('dotenv').config();

const ORIGIN = '*'

const PORT = process.env.PORT || 8080

console.log('All environment variables:', process.env);

console.log('MONGO_URI environment variable:', process.env.MONGO_URI);

const MONGO_URI = process.env.MONGO_URI;

console.log('Final MONGO_URI constant:', MONGO_URI);

const MONGO_OPTIONS = {}

const JWT_SECRET = process.env.JWT_SECRET || 'unsafe_secret';

module.exports = {

ORIGIN,

PORT,

MONGO_URI,

MONGO_OPTIONS,

JWT_SECRET,}
  • utils/mongo.js: This file contains the MongoDB connection logic, which uses the MONGO_URI environment variable.
const mongoose = require('mongoose');
const { MONGO_URI, MONGO_OPTIONS } = require('../constants'); // Adjust the path as necessary

const connect = async () => {
  const connection = mongoose.connection;

  connection.on('connected', () => console.log('âś… MongoDB connected'));
  connection.on('disconnected', () => console.log('❌ MongoDB disconnected'));
  connection.on('error', (error) => console.log('❌ MongoDB connection error:', error));

  console.log('Attempting to connect to MongoDB...');
  await mongoose.connect(MONGO_URI, MONGO_OPTIONS);
};

module.exports = { connect };
  • index.js: This file contains the main application logic, which uses the constants/index.js file to load environment variables.
const app = require('./utils/app');
const { connect: mongoConnect } = require('./utils/mongo');
const { PORT } = require('./constants');
const routes = require('./routes');

async function bootstrap() {
  await mongoConnect();

  app.use(routes);

  // Start Server
  app.listen(PORT, () => {
    console.log(`âś… Server is running on http://localhost:${PORT}`);
  });
}

bootstrap();
  • package.json: with the following scripts:
 "scripts": {
    "dev": "dotenv -e .env nodemon index.js",
    "build": "echo 'No build step for server'",
    "start": "node index.js"
  },

Not sure if useful but these are the scripts in the root package:

"scripts": {
    "dev": "dotenv -e .env turbo run dev",
    "build": "turbo run build",
    "start": "turbo run start",
    "start:frontend": "dotenv -e .env turbo run dev --scope=client",
    "start:backend": "dotenv -e .env turbo run dev --scope=server",
    "clean": "turbo run clean"
  },

I’m neither node or turbo expert but could you try changing your start script to:

"start": "dotenv -e .env turbo run start",

I did, it failed :frowning:

I’m losing my wits, I’ll end up hard coding the password into the codebase lol

Hi, dotenv allows loading environment variables from a file to facilitate development.

When running the app on Koyeb, the environment variables are already provided, so using dotenv is not necessary (process.env.MY_VARIABLE will be set without using dotenv).

Did you reference the environment variables in your turbo.json file?

1 Like

Thank you! I agree dotenv seemed pointless but I was at superstition stage :smiley:

I added the env declarations to turbo.json and it made the difference. Thanks!

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.