Next.js Discord

Discord Forum

Newbie here. Trying to figure out how on earth proces.env works

Answered
Japanese littleneck posted this in #help-forum
Open in Discord
Japanese littleneckOP
Ok I have a very weird setup: WSL2 Ubuntu which has docker and I use a node container to do everything in there. So far so good. I did all the permissions stuff too since Linux.

Now my problem is I am following a book and the book uses:
import mongoose, {ConnectOptions} from "mongoose";

const MONGO_URI = process.env.MONGO_URI || " ";

if (MONGO_URI.length) {
    throw new Error("Please define the MONGO_URI in the .env.local file.");
}


I am defining my environment variables under the root in .env.local file as the book says: MONGO_URI=mongodb://backend:27017/mathruck. Can I get some help on what is going on?

But for some reason I always get this error: https://pastebin.com/xWPHaVHd
Answered by American Crow
you forgot to negate your if statement
if (MONGO_URI.length) {
so you basically checking if you have the env variable and if it's there you throw the error
if (!MONGO_URI.length) {
or better
if (!MONGO_URI || MONGO_URI.length<0) {

Also you are setting the const MONGO_URI = process.env.MONGO_URI || " "; to a blank in the || " ". You should do ||"" (no blank inside the quotes)
And while we are there a bit better would be the Nullish coalescing operator for default values, so const MONGO_URI = process.env.MONGO_URI ?? "";
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing
I know its a lot, sorry and welcome to programming
View full answer

6 Replies

Japanese littleneckOP
The file shows up when I launch:
Next.js 14.2.3
mathruck-application  |   - Local:        http://localhost:3000
mathruck-application  |   - Environments: .env.local
mathruck-application  |
but the variables still give error
@Japanese littleneck The file shows up when I launch:
American Crow
you forgot to negate your if statement
if (MONGO_URI.length) {
so you basically checking if you have the env variable and if it's there you throw the error
if (!MONGO_URI.length) {
or better
if (!MONGO_URI || MONGO_URI.length<0) {

Also you are setting the const MONGO_URI = process.env.MONGO_URI || " "; to a blank in the || " ". You should do ||"" (no blank inside the quotes)
And while we are there a bit better would be the Nullish coalescing operator for default values, so const MONGO_URI = process.env.MONGO_URI ?? "";
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing
I know its a lot, sorry and welcome to programming
Answer
Japanese littleneckOP
Wow thanks for the other suggestions. I feel garbage right now on not doubting my code first. Thank you again!
American Crow
No worries just have to keep going when feeling garbage that's the crux