env-vars in React using Dotenv and Webpack - javascript

I want to access some of my environment variables defined in the frontend (React).
I have the following setup:
React + NodeJS (I do NOT use create-react-app)
Webpack 4
Dotenv
I have tried to follow https://medium.com/#trekinbami/using-environment-variables-in-react-6b0a99d83cf5#0618 but it does not work either any error is thrown.
webpack.config.js
const dotenv = require("dotenv");
module.exports = () => {
// call dotenv and it will return an Object with a parsed key
const env = dotenv.config().parsed;
// reduce it to a nice object, the same as before
const envKeys = Object.keys(env).reduce((prev, next) => {
console.log(prev)
prev[`process.env.${next}`] = JSON.stringify(env[next]);
return prev;
}, {});
return {
...,
plugins: [
new webpack.DefinePlugin(envKeys)
],
...
}
With above Webpack config I think I should be able to do <h4>My var: {process.env.REACT_APP_MY_VAR}</h4> in file.js, of course I have defined REACT_APP_MY_VAR in my .env-file located in the project root.
With above I expect file.js to render the value of REACT_APP_MY_VAR, but i does render nothing, either the value or an error.

I would recommend using dotenv-webpack instead of dotenv package for easy configuration.
4 simple steps:-
1) install dotenv-wepack using
npm install dotenv-webpack --save
2) Create .env file at root of application
API_URL=http://localhost:8000
3) Add this to your webpack config file.
const Dotenv = require('dotenv-webpack');
module.exports = {
...
plugins: [
new Dotenv()
]
...
};
4) Use env variable inside your application anywhere.
import React from 'react';
const App = () => {
return (
<h1>{process.env.API_URL}</h1>
);
}
export default App;
Hope that helps!!!

Related

Why don't I get any value from process.env?

I want to use environmental variables in my angular project to hide sensitive information. I have followed this tutorial using dotenv https://javascript.plainenglish.io/setup-dotenv-to-access-environment-variables-in-angular-9-f06c6ffb86c0 but I can't seem to get any value from my process.env. I can't figure out why or how.
setenv.ts file
const { writeFile } = require('fs');
const { argv } = require('yargs');
// read environment variables from .env file
require('dotenv').config();
// read the command line arguments passed with yargs
const environment = argv.environment;
const isProduction = environment === 'prod';
const targetPath = isProduction
? `./src/environments/environment.prod.ts`
: `./src/environments/environment.ts`;
if (!process.env.API_KEY || !process.env.ANOTHER_API_KEY) {
console.error('All the required environment variables were not provided!');
process.exit(-1);
}
// we have access to our environment variables
// in the process.env object thanks to dotenv
const environmentFileContent = `
export const environment = {
production: ${isProduction},
APP_ID: "${process.env.APP_ID}",
API_KEY: "${process.env.API_KEY}"
};
`;
// write the content to the respective file
writeFile(targetPath, environmentFileContent, function (err) {
if (err) {
console.log(err);
}
console.log(`Wrote variables to ${targetPath}`);
});
package.json
"ng": "ng",
"config": "npx ts-node ./scripts/setenv.ts",
"start": "npm run config -- --environment=dev && ng serve",
"build": "npm run config -- --environment=prod && ng build",
.env
APP_ID=myAppId
API_KEY=myApi_Key
I believe your path is wrong. The way I do it is import environment at the top of the document, for example, with a relative path from src/app/services/api.service.ts to src/enviroments/environment.ts:
import { environment } from '../../environments/environment';
And then just extract values you need:
BACKEND_URL = environment.apiUrl;
I suspect you don't have the .env file in the right place. Can you try this
require('dotenv').config({ path: '/custom/path/to/.env' })
See here https://www.npmjs.com/package/dotenv

SSR with React : Unexpected token '<' in call to renderToString()

I'm working on SSR with react but I'm encountering the following error.
Syntax error: Unexpected token '<'`
<div id="root">${ReactDOMServer.renderToString(<App />)}</div>```
^
As mentioned is here
babel-register doesn't process the file it is called from.
Therefore, I rightly declared my babel dependencies in a new file, however I'm still getting the above error.
Below is my index.js file
import babelRegister from '#babel/register';
import ignoreStyles from 'ignore-styles';
babelRegister({
ignore: [/node_modules/],
presets: ['#babel/preset-env', '#babel/preset-react'],
});
import express from 'express';
import appRender from './server.js';
const app = express();
appRender(app);
My server.js file.
import initialRenderRoutes from './routes/initialRenderRoutes.js';
import path from 'path';
const appRender = (app) => {
const __dirname = path.resolve();
app.use(express.static(path.resolve(__dirname, '../build')));
app.use('*', initialRenderRoutes);
const port = 5000;
app.listen(port, () => console.log(`Server running on port ${port}`));
};
export default appRender;
My initialController.js file
import fs from 'fs';
import ReactDOMServer from 'react-dom/server.js';
import path from 'path';
import App from '../../src/App.js';
const initialRenderController = (req, res, next) => {
console.log(path.resolve());
fs.readFile(
path.resolve('../client/build/index.html'),
'utf8',
(err, data) => {
if (err) {
console.log(err);
return res.status(500).send('Internal Server Error');
}
return res.send(
data.replace(
'<div id="root"></div>',
`<div id="root">${ReactDOMServer.renderToString(<App />)}</div>`
<<<<The problem lies here>>>>
)
);
}
);
};
export default initialRenderController;
Is it something related to babel, please help.
Try the below changes in your index.js file,
require('ignore-styles');
require('#babel/register')({
ignore: [/(node_modules)/],
presets: ['#babel/preset-env', '#babel/preset-react']
});
require('./server');
require('./initialController');
The above should work, I tested locally the below, it works perfectly fine.
My server.js
import express from 'express';
import fs from 'fs';
import path from 'path';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import App from '../App';
const app = express();
app.use('^/$', (req, res, next) => {
fs.readFile(path.resolve('./build/index.html'), 'utf-8', (err, data) => {
if (err) {
console.log(err);
return res.status(500).send("Some error occurred")
}
return res.send(data.replace('<div id="root"></div>', `<div id="root">${ReactDOMServer.renderToString(<App />)}</div>`))
})
});
app.use(express.static(path.resolve(__dirname, "..", "build")));
app.listen(5000, ()=>{
console.log("App running on port 5k")
})
index.js
require('ignore-styles');
require('#babel/register')({
ignore: [/(node_modules)/],
presets: ['#babel/preset-env', '#babel/preset-react']
});
require('./server');
I hope you have the .babelrc file with the required presets.
Update in response to comment:
Consider removing type: "module", since it will throw error when you use require. #babel/register will run files using babel on the fly. The require hook will bind itself to the node’s require and will automatically compile files at runtime. server.js using es module won't clash if you remove type: "module". The order of require matters, we require babel-register in index.js with the presets needed to recognize the syntaxes in the then-required server.js.
I believe there are two things that need to be changed. One on your initialControler.js you are using export default in a node.js file, use module.exports
module.exports vs. export default in Node.js and ES6
You should change all the imports in your node files.
You use export / export default in React and then import to pull in the files
https://www.geeksforgeeks.org/reactjs-importing-exporting/
module.exports and require to pull in the files for Node
What is the purpose of Node.js module.exports and how do you use it?
Second they moved the app.get into that renderReact.js file and then required it into their index.js file. However on your server.js file I don't see you importing in your initialController file.
From your example it looks like you should be doing something like this:
Server.js
let initialController = require('/path to this file');
initialController(app)
Yow broh don’t waste yow time reading them parchments.
All you need to do is remove any space b4 and after each ><
const val= ReactDOMServer.renderToString(<App />);
/// make sure you don’t have any sort of space
/// between them > < and yow ${}
/// is better if you store that long text into an small var, as I did to ///prevent prettier or some other 💩 to add a line break of an space
return res.send( `<div id="root">${val}</div>`);

Load separate .env from package.json

"start:dev": "set NODE_ENV=development&&nodemon ./bin/www",
"start:test": "set NODE_ENV=testing&&nodemon ./bin/www",
I have two separate .env files dev.env and test.env
I want to load dev.env on npm run start:dev and load test.env on npm run start:test
I have searched every where on the Internet, but no help.
Any help is appreciated.
You can only set node env in npm script. to import file you need to write code on your server file.
import dotenv in your server file
import dotenv from "dotenv";
or
const dotenv = require("dotenv");
use below code to import particular env file.
let envConfig={}
if (process.env.NODE_ENV === "development") {
if (fs.existsSync(".env.development")) {
envConfig = dotenv.parse(fs.readFileSync(".env.development"));
}
} else if(process.env.NODE_ENV === "testing"){
if (fs.existsSync(".env.test")) {
envConfig = dotenv.parse(fs.readFileSync(".env.test"));
}
}
for (const k in envConfig) {
process.env[k] = envConfig[k];
}
The dotenv NPM package loads a file called .env by default, but this behaviour can be overriden. So you can do something like:
const { config } = require('dotenv')
if (process.env.NODE_ENV === 'development') {
config({ path: '/full/path/to/your/dev.env' })
} else if (process.env.NODE_ENV === 'testing') {
config({ path: '/full/path/to/your/test.env' })
}
I believe this answer has a solution for you:
scripts: {
"set-env:production": "export $(cat .production.env | grep \"^[^#;]\" |xargs)",
"set-env:development": "export $(cat .env | grep \"^[^#;]\" |xargs)",
}

require all model of mongoose in express app.js

In my app.js of express app, I always have to include model every time I created a model
require('./models/Users')
require('./models/Projects')
Is there a way to avoid this? something like require('./models/*) ?
using glob to get all file in models path
var glob = require( 'glob' )
, path = require( 'path' );
glob.sync( './models/**/*.js' ).forEach( function( file ) {
require( path.resolve( file ) );
});
Using native nodejs, You can read the directory and load/require modules dynamically.
const fs = require("fs");
const path = require("path");
const models = fs.readdirSync("./models/");
models.forEach((dir) => {
if (fs.statSync(dir).isFile) require(path.join("./models/", dir));
});
Util:
const getModels = (dir) => {
return fs
.readdirSync(dir)
.filter((file) => fs.statSync(file).isFile)
.map((file) => require(path.join("./models/", file)));
};
module.exports ={getModels}
// How to use
const models = getModels("./models/")
Create a Separate file which will include all the exported module file and just export on objects and use it whenever required,

module not found importing function of npm script

//something.spec.js
import { myCustomGlob } from './scripts/index'
describe.only('generate index', () => {
console.log(myCustomGlob) //MODULE NOT FONUD ERROR
})
//script
const fs = require('fs')
const myCustomGlob = () => {
//some fs operation
}
export {
myCustomGlob
}
I have a npm script that used glob and fs to generate some code to create a new file. But I want to write unit test for those function too, but I got MODULE 'fs' NOT FOUND error. why? I thought 'fs' is included since I import myCustomGlob?
Try import * as fs from 'fs' or just try removing the quotes from the first fs. You are looking up the module with a string, that doesn't work.

Categories