Use Environment Variables in different js File in Node Express App - javascript

I want to use environment Variables in a different js File in an Express App. I tried many things, googled a lot, and didn't make it work.
My Setup:
I have an Express app with an index.js to serve a html page with javascript and css files. There I import the module dotenv and want to use Environment Variables inside the .env file. Printing out the variables in the index.js is working. The Code of my index.js looks like this:
const express = require("express");
const app = express();
const path = require("path");
const router = express.Router();
const dotenv = require("dotenv").config();
app.use(express.static("."));
Now I want to use the variables inside my JavaScript-File (main.js).
I tried different things...
Using exports. -> I can't import the variables because main.js is not a module. -> If I make main.js to a module, my included functions won't work.
Use requireJS -> This was not successful. Probably I made something wrong...
Use const dotenv = require("dotenv"); inside main.js -> Don't work because "require" is not defined..
Use the variables process.env.user inside main.js -> "Process is not defined"
I think that the way I serve and using express is wrong, but I don't know how and what to change and didn't find a short way.
Summarized:
I serve a website with an express app and want to use environment variables to don't publish access keys. I also want to later use these environment variables by building a docker container. I don't know how to use or export environment variables from the index.js to another js-File where my function for the website is located.
This is my first post. If I didn't make it clear I will be happy if you tell me what you need to help me.

Try placing the dotenv require statement at the top like this,
const dotenv = require("dotenv").config();
const express = require("express");
const app = express();
const path = require("path");
const router = express.Router();
app.use(express.static("."));
This should work.
Further, in order to use environment variable, you just need to do this,
process.env.VARIABLE_NAME
If I didn't make anything clear please do let me know, I am also a beginner like you :)

Related

Node.js Express custom process.env variables not accessible from all files

I am working on an app with Node.js and express and am using the 'dotenv' package to config/load my variables from the .env file. My issue is that I can only access the variables I defined in the main index.js file and not in all of the project files. I would like to be able to do so to do stuff like set up the db config in a separate file.
database=application`
And this is what I have in index.js:
`const dotenv = require('dotenv');
dotenv.config({ path: './config/config.env' })
const HOSTNAME = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 3000;`
As I said, I have no issue accessing these variables in the index.js file but if I try to access process.env.DB_SERVER for example from a different file, the value is undefined.
Any help or suggestions would be much appreciated! Thanks!!
Note that all imports modules in your index.js file are evaluated before index.js is being evaluated.
This means that dotenv.config({ path: 'config/config.env' }); is being executed only after other imported were executed, so inside those modules the DB_SERVER environment variable is not yet loaded.

Using ES6 modules in Express

Is there a way to
write my code using ES6 modules in Express app;
without reverting to babel or #std/esm ?
once I am committed to app.js of Express, I can't find a way to get out of it.
This seems like something that should be already on the web, but all I can find is above options (transpiling, esm).
With node.js, you HAVE to tell it that your main file you are loading is an ESM module. There are a couple ways to do that. The simplest is to just give the main file a .mjs file extension.
// app.mjs
import express from 'express';
const app = express();
app.get("/", (req, res) => {
res.send("hello");
});
app.listen(80);
Then, start your program with:
node app.mjs
This works - I just ran it with node v14.4.0:. The others ways to do it are discussed in the link I previously gave you here. Per that documentation, there are three ways to specify you are loading an ESM module as the top-level module file:
Files ending in .mjs.
Files ending in .js when the nearest parent package.json file contains a top-level field "type" with a value of "module".
Strings passed in as an argument to --eval, or piped to node via STDIN, with the flag --input-type=module.

Node - Can't Get moment.js to compile in VSCode (module and require problem)

I have been using an online ide to put together my node app, but now I am trying to get it to run on my local computer. At this time, I am now running into an issue with starting it up: when I use the terminal to run "node app.js" I get the following error message:
\node_modules\moment\moment.js:7
import { hooks as moment, setHookCallback } from './lib/utils/hooks';
^^^^^^
SyntaxError: Cannot use import statement outside a module
I have found that the answer to fixing this issue is to add "type": "module" to the package.json file in the directory. However, when I add that to it and I try to run the application again, I get this error message:
app.js:2
const bodyParser = require("body-parser"),
^
ReferenceError: require is not defined
Here are my imports:
const bodyParser = require("body-parser"),
methodOverride = require("method-override"),
mongoose = require("mongoose"),
express = require("express"),
moment = require("moment"),
app = express();
So I am unsure why I cannot get both to work so my app can run; I am sure this is something simple but I am at a loss. Thank you.
When you add type = module you tell the compiler that you are using ES6 modules type in the application. So, now you can't use require anymore.
Better way to fix the initial problem is to uninstall moment.js and try reinstalling some compatible version. As per my observation, error raised in the installed moment.js.
You should only use require in NodeJS.
The moment.js script is not meant to be used in server-side JavaScript that way. Use require('moment') instead:
const moment = require('moment');
const bodyParser = require("body-parser");
in place of - app.js:2
const bodyParser = require("body-parser")
can you try with -
import bodyParser from 'body-parser'

How do I access libraries I'm adding via require, in my Node/Koa server

I'm trying to require an external library in my Node app (Koa server). I'm adding njwt in my main server.js file var njwt = require('njwt');
But I can't access njwt, in my route handler function it gives an error saying njwt is undefined.
From this answer (https://stackoverflow.com/a/5809968), it seems that using strict mode in my main server.js file makes functions and variables defined in my imported file inaccessible.
But what's the workaround?
If I am understanding correctly, all you need to do is change it to: var njwt = require('./njwt');
This is assuming you have already done an npm install in the njwt directory.
I think the issue is how to send njwt instance to your router,
You can pass njwt instance like this,
require('./routes')(njwt);
I'm not sure if this is the best approach. I just ended up requiring the library in the route handler
const router = require('koa-router')();
router.post('/register', async function(ctx, next) {
var jwt = require('jsonwebtoken');
debugger;
And I'm able to access the library this way (the other two methods didn't work for me).

Node module dependency

I am new to Nodejs and javascript and not sure yet how to ask the right question.
My main file has a var express = require('express'); on top of it. I am also creating a module that I will be requiring in my main file. I know that module also require the express module. Do I have to import the express module into it or the main file will take care of that?
Modules are completely self contained. Every module has to import the dependencies it needs.

Categories

Resources