process.env.REACT_APP_STRIPE returns undefined - javascript

I am implementing Stripe in my project and getting this error on the browser: Failed prop type: The prop `stripeKey` is marked as required in `ReactStripeCheckout`, but its value is `undefined`.
I'm storing my publishable key in a .env file in the client folder:
REACT_APP_STRIPE = pk_mykeykey
And in my component, I've assigned the key to KEY:
const KEY = process.env.REACT_APP_STRIPE
And here's my Stripe component:
name="Lama Shop"
image="https://avatars.githubusercontent.com/u/1486366?v=4"
billingAddress
shippingAddress
description={`Your total is $${cart.total}`}
amount={cart.total * 100}
token={onToken}
stripeKey={KEY}
>
<Button>CHECKOUT NOW</Button>
</StripeCheckout>
I've console.logged the key, it returns undefined and the token also returns null.

Try:
re-starting the node-server again. Environment variables are only handled once in a react-app's lifecycle, which is on startup of the react app server.
Make sure your .env file is located in the same root directory as your package.json file, and if you aren't using create-react-app, make sure its included in your build script.
If the above steps didn't resolve your issue, you shouldn't need dotenv when building a react app, but you can import as such:
import * as dotenv from "dotenv"
//insert your config file path here
const configPath = "./path/to/.env"
const configVariables = dotenv.config(configPath)
const key = configVariables.REACT_APP_STRIPE
console.log(key)

Related

Package path ./standalone is not exported from package

I'm trying to use the firebase admin SDK, heres my code:
import * as admin from 'firebase-admin';
var firebaseAdminAccount = require("../serviceAccount.json");
var app : admin.app.App = null;
if(!admin.apps.length)
{
app = admin.initializeApp({
credential: admin.credential.cert(firebaseAdminAccount)
})
}
if(app === null)
{
app = admin.apps[0];
}
export default app;
the idea behind this is that whenever used, it will check if the firebase admin SDK is initialized or not, if it's not, then it will initialize it, then export it.
My problem however is when I try to run this, it gives me the following error:
error -
./node_modules/firebase-admin/lib/app/firebase-namespace.js:106:0
Module not found: Package path ./standalone is not exported from
package D:\NewRepos\1d3a\node_modules#firebase\database-compat (see
exports field in
D:\NewRepos\1d3a\node_modules#firebase\database-compat\package.json)
Import trace for requested module:
./node_modules/firebase-admin/lib/default-namespace.js
./node_modules/firebase-admin/lib/index.js ./lib/firebaseAdminSdk.ts
./middleware.ts
https://nextjs.org/docs/messages/module-not-found\
I just installed everything so it should be on the latest version, anyone have an idea why this is happening?
Seems like I didn't realize that Next.js middleware runs on V8, and therefor, firebase-admin cannot run on it. Back to the drawing board.

Exported Variable Is Undefined

context:
object named multiVerse that I need to access in another file that isn't server.js (main file)
using module.exports={multiVerse} in server.js
requiring the main file using const {multiVerse} = require('./server.js');
when using function to arrange object (made in the same file I require main, calling its class as module on server.js) it tells me multiVerse is undefined
when requiring the class into server.js to use arrangeBodies() I am doing const NBody = require('./nbody') const nbody = new NBody(); before the multiVerse object is initialized
questions:
Am I exporting it correctly? Why am I getting undefined?

overwrite config file in nodejs - best practice?

Wondering what would be the best practice for my case.
I have a variable I need to set its value on app load and access this value many times across my code. what is the best way to get this value?
Right now I'm just overriding a config file property. Does a global variable is better? Is there another way to do this?
The priority standard for configs IMHO is:
command line parameter
environment var
local config file
global config file
if no cli parameter found, fall to look into environment vars, then local config file, then global
I do this.
Put the variable in .env file:
# .env
APP_PORT=4000
In my app source code, I create a file named constants.js:
// constants.js
import { load as loadEnvVars } from 'dotenv'; // run `npm i dotenv` to install
// load the .env file content to process.env
loadEnvVars();
// export the variables I need
export const APP_PORT = process.env.APP_PORT || 3000;
I import that file when I need it like this:
// server.js
import Express from 'express';
// import the constant
import { APP_PORT } from './constants';
const app = Express();
app.listen(APP_PORT, () => console.log('server deployed');

Firebase module requires an older version of node while deploying the functions

I want to make a cloud function that uses 'firebase' module (not a 'firebase-functions')
And when I'm using or even only import it, npm throws an error:
Error: Error parsing triggers: Failed to load gRPC binary module because it was not installed for the current system
Expected directory: node-v64-darwin-x64-unknown
Found: [node-v79-darwin-x64-unknown]
This problem can often be fixed by running "npm rebuild" on the current system
Original error: Cannot find module '/Users/rame/functions/node_modules/grpc/src/node/extension_binary/node-v64-darwin-x64-unknown/grpc_node.node'
1) If you want to compile the package/file into executable, please pay attention to compilation warnings and specify a literal in 'require' call. 2) If you don't want to compile the package/file into executable and want to 'require' it from filesystem (likely plugin), specify an absolute path in 'require' call using process.cwd() or process.execPath
here's my code on Type script:
import * as functions from 'firebase-functions';
import admin = require('firebase-admin');
//the cause of an error
import * as firebase from 'firebase';
admin.initializeApp()
export const getProfilePicture = functions.https.onRequest((request, response) => {
//also there
const uid = firebase.auth().currentUser?.getIdToken
const promise = admin.storage().bucket().file('usersPfp/' + uid).getSignedUrl({
action: 'read',
expires: '03-09.2441'
})
const p2 = promise.then(GetSignedUrlResponse => {
const data = GetSignedUrlResponse[0]
return response.send({"data": data})
})
p2.catch(error =>{
console.log(error)
return response.status(500).send({"error": error})
})
})
How to fix that?
What you're doing isn't supported. The Firebase Authentication JavaScript client library isn't supported for use in backend environments like Cloud Functions.
The idea of a current user:
firebase.auth().currentUser
only makes sense in the client app where the user is signed in. It's not something that's known on the backend.
What you can do instead is send the user's ID token from your client to your function, the use the Admin SDK to verify it, then perform some actions on the user's behalf.

How to calculate checksum in React Native and Node?

I'm uploading an image file from React Native to AWS Lambda (Node 10.x) and want to verify the hash of the file I've sent matches the file received. To do this I'm using hashing in React Native and again in Lambda, but the hashes never match. Here are the relevant bits of code I've tried.
React Native
import RNFS from "react-native-fs";
const contentChecksum = await RNFS.hash(post.contentUrl, "md5");
Lambda (Node)
import AWS from "aws-sdk";
const crypto = require("crypto");
const s3 = new AWS.S3();
const data = await s3
.getObject({
Bucket: file.bucket,
Key: file.key
})
.promise();
const contentChecksum = crypto
.createHash("md5")
.update(data.Body)
.digest("hex");
These checksums never match. I've tried using base64 encoding in Node (data.Body.toString("base64")) and also sha256. What is the trick to calculating the checksum so they match in React Native and Node?
Edit: Here are the results from a recent test.
post.contentUrl: file:///Users/xxxxxxx/Library/Developer/CoreSimulator/Devices/2F2F4FD3-574E-40D7-BE6B-7080E926E70A/data/Containers/Data/Application/65A3FF67-98B2-444D-B75D-3717C1274FBC/Library/Caches/Camera/FDCD8F90-D24F-4E64-851A-96AB388C4B59.jpg
(the file is local on an iPhone)
contentChecksum from React Native: 48aa5cdb30f01719a2b12d481dc22f04
contentChecksum from Node (Lambda): 7b30b61a55d2c39707082293c625fc10
data.Body is a Buffer.
I also note that the eTag attribute on the S3 object matches the md5 checksum I'm calculating in Node. Since eTag is usually the md5 hash of the file, this tells me that I'm likely calculating the hash incorrectly in React Native, but I'm not sure how. I'm using the hash function from the react-native-fs package.
You can use the same code on React and AWS Lambda, that is Node.js.
So in your React.js application you could use the following code:
import * as React from 'react';
import crypto from 'crypto';
var key = 'YOUR_KEY';
export default class Test extends React.Component {
render() {
var hash = crypto.createHash('md5').update(key).digest('hex');
return (
<div>
{hash}
</div>
)
}
}
And the variable hash have to contains the same value you get on AWS.
In order to run you have to install the crypto library:
npm i --save react-native-crypto
Change the variable YOUR_KEY, then run the application:
npm start
And in the browser you should get:
4b751fef5e9660e3943173fd3e6c4224
You can use the crypto module.
To get a list of all available hash algorithms, you can use crypto.getHashes().
Here is a Nodejs example:
var crypto = require('crypto')
crypto.getHashes() // [ 'dsa', 'dsa-sha', ..., 'md5', ... ]
Here is a helper method for generating checksum value from string input:
var crypto = require('crypto')
function checksum(str, algorithm, encoding) {
return crypto
.createHash(algorithm || 'md5')
.update(str, 'utf8')
.digest(encoding || 'hex')
}
checksum('This is my test text');
checksum('This is my test text', 'sha1');

Categories

Resources