How to access Heroku environment variables with Nuxt.JS app - heroku

I have deployed my app on Heroku and on the start of my app I check a config file and in there I want to access a config var I have created on Heroku API_KEY to define my Firebase config:
module.exports = {
fireConfig: {
apiKey: process.env.API_KEY,
authDomain: "my-app.firebaseapp.com",
databaseURL: "https://my-app.firebaseio.com",
projectId: "my-project-id",
storageBucket: "my-app.appspot.com",
messagingSenderId: "my-messaging-sender-id"
}
};
this process.env.API_KEY is undefined. Should I use a different way to access it?

You can define environment variables in your nuxt.config.js file, e.g.
export default {
env: {
firebaseApiKey: process.env.API_KEY || 'default value'
}
}
Here we use the API_KEY environment variable, if it's available, and assign that to firebaseApiKey.
If that environment variable isn't set, e.g. maybe in development (you can set it there too if you want), we fall back to 'default value'. Please don't put your real API key in 'default value'. You could use a separate throwaway Firebase account key here or just omit it (take || 'default value' right out) and rely on the environment variable being set.
These will be processed at build time and then made available using the name you give them, e.g.
module.exports = {
fireConfig: {
apiKey: process.env.firebaseApiKey, # Not API_KEY
// ...
};

Related

Add cypress dashboard record key in cypress config file

I have added my cypress record key in the cypress config file. But displaying this issue. Can someone help me to resolve this issue?
Tried like this too.
e2e: {
async setupNodeEvents(on, config) {
// implement node event listeners here
const bundler = createBundler({
plugins: [createEsbuildPlugin(config)],
});
on("file:preprocessor", bundler);
await addCucumberPreprocessorPlugin(on, config);
return config;
},
specPattern:"cypress/e2e/features/*feature",
baseUrl:"https://d2l5front.net/",
projectId: "7t2",
viewportWidth: 1600,
viewportHeight: 1100,
env: {
CYPRESS_RECORD_KEY: "62ad7c5d-2c01209cf1c7",
}
}
The CYPRESS_ prefix is only for "external" environment variables, those created in the OS before Cypress runs.
See Option #3: CYPRESS_*
Cypress automatically normalizes both the key and the value.
The leading CYPRESS_ or cypress_ is removed and the remaining name is camelCased, while values are converted to Number or Boolean wherever possible.
I would suggest you try without the CYPRESS_ prefix since you are providing the key "internally" as it were.
env: {
RECORD_KEY: "62ad7c5d-2c01209cf1c7",
}
Your env property should be under the e2e object, not at the same level.
...
e2e: {
...
env: {
CYPRESS_RECORD_KEY: 'foo',
},
...
}
...
I think that is by design. The record key should not be saved in the config (or any) file, as it's linked to billable usage.
From Dashboard - Record key
Exposing a record key
Anyone that has access to both the projectId and the record key of a project can record runs to that organization's project in the Dashboard.
The projectId can be saved as
const { defineConfig } = require('cypress')
module.exports = defineConfig({
projectId: 'a7bq2k'
})
but there is no mention of setting recordKey in the config.
Instead, you must set it in the external environment as CYPRESS_RECORD_KEY or on the command line
cypress run --record --key abc-key-123

How to read Gitlab (.gitlab-ci.yml ) environment variable from Spring Boot code?

I am trying to read an environment variable is being set from within Gitlab configuration when the application is being built, I am doing this for achieving that purpose:
I setup a variable in the application.properties.yml of my spring boot app:
sf:
apiKey: $SF_API_KEY
In the .gitlab-ci.yml, I defined the variable to be set, as follows:
variables:
SF_API_KEY: $SF_API_KEY
all I want, is to be able to read that variable from within one of my services, as the below code depicts:
#Service
class MyService(#Value("\${sf.apiKey}") val apiKey: String)
{
fun doSomething(){
//i am seeing the variable is being set by gitlab in the build logs but
// it is not being read here properly
var result = apiKey;
logger.info { "***check apiKey: $apiKey" }
//This line lgs $SF_API_KEY as a value of my variable, but not the
// real value
}
}
Am I doing something wrong? I would appreciate any help.
Try (note the {} around SF_API_KEY):
sf:
apiKey: ${SF_API_KEY}
Take a look at the docs where this placeholder notation is detailed.

Laravel environment variable with React: is this a good practice?

I have a React app which makes API requests to a Laravel backend.
My app is hosted on Heroku (I do not know if it changes something for my question).
I would like to differentiate a production and a local environment for these requests. I do it as follows.
In my "welcome.blade.php", I add this meta tag:
<meta name="app_env" content="<?php echo env("APP_ENV") ?>" />
The APP_ENV contains either "production" or "local".
In my React app, I have this script:
export let urlApi = (document.querySelector("[name=app_env]").content === "production" ) ?
"https://laravel-react.herokuapp.com/api"
:
"http://localhost/laravel_react/public/api"
;
And I import this function in each component which needs it:
import { urlApi } from './../findUrlApi';
// .....
return fetch(`${urlApi}/products`,{
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer "+localStorage.getItem("token")
}
})
It works fine.
But my question is, is it a good practice? (I am a beginner in React).
I don't think that it is a good practice. Environment variables (like APP_ENV and API URLs) should not reside in the source code.
However, you could store them like usual in Laravel .env file but by prefixing the key with MIX_. For example: MIX_API_URL=http://localhost. Every MIX_* variables in .env file will be exposed to your React application. Then, you could get MIX_API_URL value from your React application by calling process.env.MIX_API_URL.
Updated Laravel .env file
...
MIX_APP_ENV=production (or local) # Should be same as APP_ENV
MIX_API_LOCAL_URL=http://localhost/laravel_react/public/api
MIX_API_PRODUCTION_URL=https://laravel-react.herokuapp.com/api
In React components that need it
const { MIX_APP_ENV, MIX_API_LOCAL_URL, MIX_API_PRODUCTION_URL } = process.env;
const apiUrl = MIX_APP_ENV === 'local'? MIX_API_LOCAL_URL: MIX_API_PRODUCTION_URL;
return fetch(apiUrl + '/products', { ... });
If calling process.env.MIX_API_URL does not work and you are running npm run watch, try restarting npm run watch and hard reload your browser.
Reference
Laravel Documentation - Compiling Assets (Mix) - Environment
Variables

How to call .env file from YAML?

I want to hide my secret credential from my yaml, i need to use .env, so how to call .env file from my yaml, so that every I call this YAML, YAML will automatic call .env file. Please help me. thx
Instead of using an .env file, which is a simple properties file if you're following dotenv package, you can do the following:
create additional .yml file, for example .secrets.yml. you can store the secrets per stage:
prod:
MY_SECRET: foo
dev:
MY_SECRET: bar
store your secrets/configurations there
Then in serverless.yml:
load this file into an object:
custom:
secrets: ${file(.secrets.yml):${self:provider.stage}}
load object fields as environment variables:
provider:
environment:
MY_SECRET: ${self:custom.secrets.MY_SECRET}
How to test locally
In your tests you can load the secrets file this way:
const yaml = require('js-yaml');
const fs = require('fs');
const _ = require('lodash');
module.exports.loadSecrets = function (env = 'dev', path = './.secrets.yml') {
const secrets = yaml.load(fs.readFileSync(path));
_.forEach(secrets[env], (value, key) => {
process.env[key] = value;
});
}
Reference: http://www.goingserverless.com/blog/using-environment-variables-with-the-serverless-framework

node-config doesn't read config files when app is set up as Windows Service using node-windows

I'm using node-windows to set up my application to run as a Windows Service. I am using node-config to manage configuration settings. Of course, everything is working fine when I run my application manually using node app.js command. When I install it as a service and it starts, the configuration settings are empty. I have production.json file in ./config folder, and I can set NODE_ENV to production in the install script. I can confirm that the variable is set correctly and still nothing. log.info('CONFIG_DIR: ' + config.util.getEnv('CONFIG_DIR')); produces undefined even if I explicitly set it in env value for the service. Looking for any insight.
install script:
var Service = require('node-windows').Service;
var path = require('path');
// Create a new service object
var svc = new Service({
name:'Excel Data Import',
description: 'Excel Data Import Service.',
script: path.join(__dirname, "app.js"), // path application file
env:[
{name:"NODE_ENV", value:"production"},
{name:"CONFIG_DIR", value: "./config"},
{name:"$NODE_CONFIG_DIR", value: "./config"}
]
});
// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
svc.start();
});
svc.install();
app script:
var config = require('config');
var path = require('path');
var EventLogger = require('node-windows').EventLogger;
var log = new EventLogger('Excel Data Import');
init();
function init() {
log.info("init");
if(config.has("File.fileFolder")){
var pathConfig = config.get("File.fileFolder");
log.info(pathConfig);
var DirectoryWatcher = require('directory-watcher');
DirectoryWatcher.create(pathConfig, function (err, watcher) {
//...
});
}else{
log.info("config doesn't have File.fileFolder");
}
}
I know this response is very late, but also i had the same problem, and here is how i solved it :
var svc = new Service({
name:'ProcessName',
description: 'Process Description',
script: require('path').join(__dirname,'bin\\www'),
env:[
{name: "NODE_ENV", value: "development"},
{name: "PORT", value: PORT},
{name: "NODE_CONFIG_DIR", value: "c:\\route-to-your-proyect\\config"}
]
});
When you are using windows, prefixing your enviroment variables with $ , is not required.
Also, when your run script isnĀ“t on the same dir as your config dir, you have to provide a full path to your config dir.
When you have errors with node-windows , is also helpful dig into the error log. It is located on rundirectory/daemon/processname.err.log
I hope this will help somebody.

Resources