Skip to content Skip to sidebar Skip to footer

How To Access Window Variable In Javascript Object?

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, project

Solution 1:

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 (typeofwindow !== 'undefined') {
  configs = {
    //firebase configurationapiKey: 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 = typeofwindow === 'undefined' ? process.env : window._env_;

exportconst configs = {
  //firebase configurationapiKey: env.API_KEY,
  projectId: env.PROJECT_ID,
  messagingSenderId: env.MESSAGING_SENDER_ID,
  backendURL: env.BACKEND_URL
}

Solution 2:

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

<scriptsrc="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

Post a Comment for "How To Access Window Variable In Javascript Object?"