1

so essentially, for the purposes of testing locally, I need to define my API keys in a .env file and the only place I can read them into my code is in my server.js file.

as an example, let's say in my server.js, I have the following code with the necessary imports:

const {api_key1, api_key2} = process.env;

I thought I would try to be clever and try the following:

export default {api_key1, api_key2};

so I could then import server from 'server.js'; from a front end javascript file, like index.js.

Of course, I tried running that and was greeted with SyntaxError: Unexpected token export

TLDR: What's the best way to transfer these environment variables into other JSX files?

Follow up edits:

when I try const {apikey1, apikey2} = process.env in index.js, I get Reference Error: Process is not defined

when I try adding a require('dotenv').config() above the process.env call, I get Module not found: can't resolve 'fs' in ..node_modules\dotenv\lib

notacorn
  • 3,526
  • 4
  • 30
  • 60

1 Answers1

0

Probably, You are misled when you're thinking about doing so.

You don't need to export those variables, these are implicitly available in process object. So you can access those in any file like the same way you're doing in server.js.

Like, in index.js you can do something like const {api_key1, api_key2} = process.env; and that's perfectly fine.

Deepak
  • 850
  • 5
  • 13
  • So I saw this SO thread earlier: https://stackoverflow.com/a/48359480/8652920 and from what I can tell using dotenv/process.env in `index.js` is a big no no? – notacorn May 18 '19 at 16:36
  • My code has `const dotenv = require('dotenv');` and the exact code you mentioned in `index.js` right now, and on compile I'm getting the classic `Cant resolve 'fs' in ...node_modules\dotenv\lib` – notacorn May 18 '19 at 16:37
  • You are doing that for client side application or server-side ? – Deepak May 18 '19 at 16:42
  • @ark0n Did you go through - https://github.com/motdotla/dotenv/issues/233#issuecomment-339066486 ? – Deepak May 18 '19 at 16:44
  • I'm requiring dotenv and accessing process.env in `index.js` at the moment, and the api key pops up on the screen for a brief second (because i added it as a header for the page) and then the fs error comes – notacorn May 18 '19 at 16:50
  • DotEnv is not supported for client side applications, please check the link a pasted. – Deepak May 18 '19 at 16:52
  • and @DJ Yadav, I added both the linked webpack config and `target: "node"`, none of which are allowing me to use `process` in `index.js` – notacorn May 18 '19 at 16:54