getting 401 response codes on a deployed React App that worked fine in development? - node.js

I am trying to complete a Redux project and got everything to work fine in development on my own machine but when deployed, the browser is failing to recognise my hidden environment variables so not passing client keys to Api calls and thus making unauthorised requests. I have a '.env' file with the keys in them and then refer thus...
const API_URL = https://api.openweathermap.org/data/2.5/weather?appid=${process.env.REACT_APP_OPEN_WEATHER_MAP_API_KEY}&units=metric;
I have looked up the problem on here and think I understand what's going wrong but don't know how to put it right. I am deploying site via Netlify from my Github repo and my build settings appear to be correct. I thought 'npm run build' took care of all that for me?
99% finished a project and now scratching my head furiously...

Try defining variables in .env file starting with REACT_APP like:
REACT_APP_CLIENT_ID=4
REACT_APP_API_URL=/api
Try using it anywhere like:
const apiUrl: process.env.REACT_APP_API_URL;

Set the environment variables specifically within the Netlify UI. So 'Deploy Settings > Environment > Environment Variables' then variable -'REACT_APP....' value - '*****' for each variable you want defined.

Related

Azure static web app environment variable

I am trying to publish Gatsbyjs by Azure Static web app.
I have a plugin (gatsby-source-contentful).
I need to pass variables like:
{
resolve: `gatsby-source-contentful`,
options: {
spaceId: process.env.CONTENTFUL_SPACE_ID,
accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
},
},
Error:
Running 'npm run build'...
> gatsby-starter-default#0.1.0 build /github/workspace
> gatsby build
success open and validate gatsby-configs - 0.021s
error Invalid plugin options for "gatsby-source-contentful":
- "accessToken" is required
- "spaceId" is required
not finished load plugins - 0.905s
Where can I pass this?
Thanks.
For Azure Static Web Apps there is two ways to set environment variables one for front-end and one for back-end scenarios.
Since you are using Gatsby, I guess its safe to assume you are building your front-end. For that you will need to add the environment variables on your build configuration (azure-static-web-apps-.yml).
Like so:
env: # Add environment variables here
CONTENTFUL_SPACE_ID: <your-id>
Here is the link for that in documenation.
Not to be confused with this one which is used for defining backend environment variables.
They are called environment variables. They are intended to store sensitive data such as tokens, identifiers, etc, and they shouldn't be pushed in your repository, so you should ignore them (in your .gitignore file).
By default, Gatsby creates 2 environments without noticing you, one for each compilation method:
gatsby develop: uses .env.development
gatsby build: uses .env.production
Note: you can change this behavior if needed to add your own environments using NODE_ENV custom commands.
So, to pass your data to your gatsby-config.js you just need to create two files (.env.development and .env.production) at the root of your project. Then, add the following snippet at the top of your gatsby-config.js:
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
})
Note: dotenv is already a dependency of Gatsby so you don't need to install it again
This will tell Gatsby where to take the environment variables.
You just remain to populate both environment files. Look for the credentials in Contentful and add them in the files using the sane naming than you've set in your gatsby-config.js:
CONTENTFUL_SPACE_ID=123456789
CONTENTFUL_ACCESS_TOKEN=123456789
Keep also in mind that when dealing with Azure, Netlify, AWS, or similar CI/CD tools, you'll need to provide to the server the same environment files to avoid a code-breaking when pushing the changes.

Environment variables in NodeJs using cPanel

So I'm using cPanel with Setup Node.js App plugin for a Next.js app. (don't asky why cPanel)
Everything is working as expected in development, except for environment variables in production, I set up them manually from the cPanel interface, I restarted/stopped the app, logging the process.env on the server and I don't see the env variables there (not to say when trying to call them they are undefined).
When doing
res.json(JSON.stringify(process.env)); i get a bunch of variables except for the one I manually wrote in cPanel variables interface.
It is important for me to store these variables as secret key because they are API credentials.
Anyone know what I might have misconfigured or had this problem?
Never mind, found the answer, apparenlty was a Next.js misconfiguration. I had to add the following lines of code inside next.config.js in order to read env variables on build version.
require('dotenv').config();
module.exports = {
env: {
EMAIL_NAME: process.env.EMAIL_NAME,
EMAIL_PASSWORD: process.env.EMAIL_PASSWORD,
GETRESPONSE_API_KEY: process.env.GETRESPONSE_API_KEY
}
};
Where EMAIL_NAME, EMAIL_PASSWORD, GETRESPONSE_API_KEY were the variables defined by me on cPanel interface

How do I get my deployed React.js app to use API secret keys? I'm using Heroku confing vars but still not working

Problem:
I created a simple React app (using Javascript and Node) that uses the GitHub API to search for users and return information about them. I need to use a GitHub oauth key so that I can make authenticated API requests. However, I am having trouble giving my deployed app (using Heroku) the key without hard-coding it into the API call. I'm fairly new at this so any help would be great! I linked the github repo at the bottom of this post.
I have tried several things which I will explain below:
Attempt 1:
I created a file where I set my GitHub key to a variable and exported it (Image of code)
I put said file in the .gitignore
I imported the variable in the files where I made API calls and used them it directly in the API call. (Image of API call)
This worked on my dev environment but (obviously) did not work on my deployed Heroku app because it had no idea what the variable was. (Image of error)
Attempt 2:
I configured variables in Heroku and set GITHUB_KEY to my key. (Image of Heroku variable setting).
Next, I checked that Heroku recognized this variable by running the command heroku config:get GITHUB_KEY and received the correct key in response (Image of terminal)
In my secrets file, I set the variable like so: process.env.GITHUB_KEY = 'a93b2c21918b42df5a28e0e529c627ee22c60de4'; (Image of setting variable using process.env)
And then I use it in my API calls on the frontend: const res = await fetch(
'https://api.github.com/users/${this.state.input}?access_token=${process.env.GITHUB_KEY}'
);.
However, I get the following error: SearchBar.js:32 GET https://api.github.com/users/livmarx?access_token=undefined 401 (Unauthorized). (Image of error).
So, I know that I'm misunderstanding how process.env works but cannot seem to figure it out! Any clarification would be super helpful.
Here is the link to my github repo: https://github.com/livmarx/zilliow-challenge

How to get Heroku to ignore a failed import?

I've got a project deployed on heroku using React and node, for which I'm importing a json file which contains various API keys (for firebase, AWS, etc.). In development, I simply do import keys from './keys.json'. However I was aware that wouldn't work in Heroku, so I set up the appropriate environment vars and used process.env to get them. Now though... the whole compilation/build of my project fails because Heroku can't find keys.json (since I don't deploy it, for apparent reasons). Is there any way to get it to ignore this one particular failure during build so it can go ahead and use the env vars?
Wrap the import in a conditional:
var keys = {}
if (!process.env['AWS_KEY']) {
keys = require('./keys.json')['keys'];
}
This has the side effect of giving precedence to environment variables over a local file. If you want the file to have precedence instead, look at fs.existsSync as your conditional (fs.exists could be used with some work).

How can I set up a node app (ember app kit) on heroku that reads ENV variables and makes the values available to the application?

Okay, I'm new to node, and really only just using the node server to serve static js, but I can't find any info on this anywhere.
I'm running an application ember app kit, which gets built to a node server.js for deploy, and heroku runs it with node server.js.
It uses grunt for building, testing, etc.
I'd like to know how I can specify configuration variables (i.e. authentication tokens) that can be overridden by heroku config variables.
The closest I've been able to get is a custom task that reads environment variables and writes out a json file that gets built into the site (and assigned to a global var). This works locally, but doesn't take into account heroku configs.
I even wrote a deploy script that gets heroku's configs, exports them as environment variables locally, and does the build--Which works, but the configs only get updated on app deploy. So if I do a heroku config:add CONFIG_TEST=test_value, my app doesn't see that value for CONFIG_TEST until the next time I deploy the app.
I'd like for my app to start embedding that config value in the browser JS immediately.
Any way to do this with node the way my app is set up?
I am not sure I understand what's wrong with simply taking config variables, at run time, from the environment. Use process.env.KEY in your code, and embed that result into whatever template you may have, and serve that as the result.
When you change Heroku config variables your process gets restarted, so it picks up the new values.
Is the problem the fact that you serve static files? If so -- can you simply change it so that you use a template engine to do some processing on them before serving?
OK, here's a solution for ember-app-kit using grunt-sed.
In EMBER_APP_KIT_PROJECT/tasks/options/sed.js
Add something like
module.exports = {
version: {
path: "./dist/",
pattern: '{{env.API_BASE_PATH}}',
replacement: function(){
return process.env.API_BASE_PATH;
},
recursive: true
}
};
then in your code just put
"{{env.API_BASE_PATH}}"
Now, when you run
$ grunt sed
it will replace "{{env.API_BASE_PATH}}" with whatever's in the environment variable.

Resources