javascriptreactjsenvironment-variablespage-title

How to use environment variable as the react vite app title


How to use environment variable as the react vite app title?

One solution I found is, In the index.tsx file:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

// Set document title dynamically
document.title = import.meta.env.REACT_APP_MY_VARIABLE || 'Default Title';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

However, when using whatever value in

export REACT_APP_MY_VARIABLE=whatever

I alway ended up with 'Default Title'.

Following Create React App: using environment variables in index.html, I changed the above to process.env:

document.title = process.env.REACT_APP_MY_VARIABLE || 'Default Title';

but now my react app is only showing an empty page.

PS.

This is a react vite app, and I'm starting it with:

npx vite --host

PPS.

The solution has to be work for both dev/test time and build time.


Solution

  • In order for custom environment variables to be exposed in Vite, they need to prefixed with VITE_: https://vitejs.dev/guide/env-and-mode.

    You probably want to use import.meta.env.VITE_APP_TITLE and set the VITE_APP_TITLE variable.