Sharing Constant Variables between Node and React

164
March 29, 2018, at 12:33 PM

Is it possible to share constants between react and node - I am running node and react concurrently? For example, I have some constants I've defined on the client side using export const that could be useful to have on the server side, but node gives me an error when I try to const {x} = require('./constants'); because it can't import correctly. Has anyone run into this problem and found a solution?

React Constants:

// constants.js
export const X = 'x';
export const Y = 'y';
export const Z = 'z';
// App.js
import {x, y, z} from './constants';

Node Constants:

// constants_node.js
module.exports.username = 'foo_user';
module.exports.id = 10;
// server.js
const {username, id} = require('./constants_node');
Answer 1

If you are using the same node environment to serve your ReactJS components you can probably use environment variables for this purpose.

You can use a .env file and import it as process.env.VARIABLE_NAME where you want to use it.

Maybe this question - Pass or use process.env variable from node to reactjs can answer your question.

READ ALSO
having problems with wss over ssl

having problems with wss over ssl

I am having trouble converting my ws connection into wssI have 2 types of servers running on my code

135
What does body-parser actually do with express?

What does body-parser actually do with express?

Okay, So i was going through my old node code which I wrote when I was following some tutorial

161
Nginx 502 Bad Gateway error on EC2 Instance

Nginx 502 Bad Gateway error on EC2 Instance

I've been having some trouble configuring an nginx server on a EC2 Linux instanceI'm running an application on port 3000 and want to map that to port 80 using nginx

172
express js render object variables to webpage

express js render object variables to webpage

I have an object that I am trying to print its key and value variables onto my browserthe object looks like this

159