5

I am creating a vue3 application (created with Vite) that interacts with a smart contract written in Solidity and stored on Ropsten. Therefore I am using web3js to interact with my smart contracts and also web3.storage in order to store some images on IPFS. I have a .env file at the root of my project storing my API key for web3.storage :

VUE_APP_API_TOKEN=VALUE
VITE_API_TOKEN=VALUE

The problem is that apparently web3.storage expects the API token to be stored in process.env and I am unable to access the global process variable from my application. I am always getting an error Uncaught ReferenceError: process is not defined.

I think, this is linked to my usage of Vite instead of pure Vue3. I tried to export process env in the vite.config.ts file with that code but it didn't work:

export default ({ mode }) => {
   process.env = { ...process.env, ...loadEnv(mode, process.cwd(), '') };

   console.log(process.env.VITE_API_TOKEN)         //Works fine: VALUE is logged
   console.log(process.env.VUE_APP_API_TOKEN)      //Works fine: VALUE is logged

   return defineConfig({
       plugins: [vue()]
   });
}

How could I access the process variable from my vue files in order to get the values of my environment variable and make web3.storage work?

2
  • Docs might help. Commented Feb 13, 2022 at 21:09
  • @tao thanks for the tip, I already tried with the documentation but it didn't help Commented Feb 14, 2022 at 9:00

2 Answers 2

8

.env

VITE_WEB3_STORAGE_TOKEN="your_token"

SomeComponent.vue: (or any other file of your app, really):

console.log(import.meta.env.VITE_WEB3_STORAGE_TOKEN) // "your_token"

Note: as specified in vite documentation, only variables prefixed with VITE_ will be exposed:

To prevent accidentally leaking env variables to the client, only variables prefixed with VITE_ are exposed to your Vite-processed code.

Sign up to request clarification or add additional context in comments.

2 Comments

Okay thank you for your solution, I feel like this is the only way. The "process" global variable doesn't seem to be accessible anymore in Vue3 projects
It's not, for precisely the reason quoted in my answer. Considering what process has access to, and what people tend to put in those environment variables, I personally think it's a sensible only to expose what's been prefixed with VITE. You can now safely use other names for stuff that should not be visible anywhere in the client.
0

If you're running the build script in CI you will need to make sure that you're creating / populating the relevant .env file before you run the build script.

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.