Home > Net >  Is it possible to get multiple random api key from .env?
Is it possible to get multiple random api key from .env?

Time:01-18

In my .env file there is something like this:

GOOGLE_MAP_API=AIzaSyByfXuuwxOIaWlefhSxqhMweF-0
Another_API_KEY=5893978af2537e042beb233b1

I would like to create a .env file in which "Another_API_KEY" is randomly choosen from multiple api keys list.

Something like this:

GOOGLE_MAP_API=AIzaSyByfXuuwxOIaWlefhSxqhMweF-0
    var r_text = new Array();
 r_text[0] = "a3219d4e2772db6e34c62144b27f";
 r_text[1] = "5bbe61fe6db548e665a49663eba2";
 r_text[2] = "d74ae61790a9937e3f6d5d3ddc83";

    var nn = Math.floor(3 * Math.random());
    var Another_API_KEY = r_text[nn]

But this is'n working. Is this possible to get random keys from the list to React JS Application from .env file?

CodePudding user response:

.env files store strings so it's not possible to run Javascript inside it.

What you can do, however, is store all keys you want to randomly pick up from in .env and, when you use them inside your app, you pick one of them.

.env

GOOGLE_MAP_API=AIzaSyByfXuuwxOIaWlefhSxqhMweF-0
RANDOM_KEYS="a3219d4e2772db6e34c62144b27f 5bbe61fe6db548e665a49663eba2 d74ae61790a9937e3f6d5d3ddc83"

Then on your code:

// Choose random key from all options
const RANDOM_KEYS_ARRAY = process.env.RANDOM_KEYS.split(" ")
const RANDOM_KEY = RANDOM_KEYS_ARRAY[Math.floor(RANDOM_KEYS_ARRAY.length * Math.random())]

Here's a sandbox with working code: https://codesandbox.io/s/getting-random-key-from-env-xuup4r

CodePudding user response:

I managed it.

I the file app.js where the command was to get api key from .env: &appid=${process.env.REACT_API_KEY}

I deleted: process.env. and inserted

'var r_text = new Array();
r_text[0] = "456afa82537e042beb233b25";
r_text[1] = "s54667e042b33b1fa525";
r_text[2] = "456a82537e042beb233b525";

var nn = Math.floor(3 * Math.random());
var REACT_API_KEY = r_text[nn];'

And it works. Thank you

  • Related