0

Is the below code correct ? I want to access the window variable in a javascript object.

export const configs={
  //firebase configuration
  apiKey: window._env_.API_KEY,
  projectId: window._env_.PROJECT_ID,
  messagingSenderId: window._env_.MESSAGING_SENDER_ID,
  backendURL: window._env_.BACKEND_URL
}
2
  • Where and how you have set these variables? Can you also show that part. Just put xxxx in place of actual API_KEY value just to be safe. Commented Mar 14, 2020 at 12:54
  • Really depends on the context of this code. Syntax-wise it’s at least not invalid. Commented Mar 14, 2020 at 15:01

2 Answers 2

2

If this code is executed in a browser, window is available as a global object. However, if this code is executed in a node environment (server side), window will be undefined.

Here's one way to handle this if your code will execute both server-side (node environment) and client-side (browser environment):

if (typeof window !== 'undefined') {
  configs = {
    //firebase configuration
    apiKey: window._env_.API_KEY,
    projectId: window._env_.PROJECT_ID,
    messagingSenderId: window._env_.MESSAGING_SENDER_ID,
    backendURL: window._env_.BACKEND_URL
  }
} else {
  // handle server-side logic here
}

If there's no need for this to execute in the browser, it would be simplest to just use process.env instead of setting these variables on the window. If you do need these variables in both places (and they're coming from process.env), this might be another solution:

const env = typeof window === 'undefined' ? process.env : window._env_;

export const configs = {
  //firebase configuration
  apiKey: env.API_KEY,
  projectId: env.PROJECT_ID,
  messagingSenderId: env.MESSAGING_SENDER_ID,
  backendURL: env.BACKEND_URL
}
Sign up to request clarification or add additional context in comments.

Comments

1

You should create a new js file, then write as below. File name is appsettings.js

window.appSettings = {
    apiKey: '${REACT_API_KEY}',
    projectId: '${REACT_PROJECT_ID}',
    messagingSenderId: '${REACT_SENDER_ID}',
    backendURL: '${REACT_BACKEND_URL}'
};

env files

REACT_API_KEY=value
REACT_PROJECT_ID=value
REACT_SENDER_ID=value
REACT_BACKEND_URL=value

Public/index.html

<script src="http://localhost/appsettings.js?v={version}"></script>
    <script>
        window.appSettings.apiKey= '%REACT_API_KEY%';
        window.appSettings.projectId= '%REACT_PROJECT_ID%';
        window.appSettings.messagingSenderId= '%REACT_SENDER_ID%';
        window.appSettings.backendURL= '%REACT_BACKEND_URL%';
    </script>

Where you want to use, write this code

window.appSettings.apiKey

Not need declare another place because it declare index.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.