Anurag Singh
Anurag Singh

Reputation: 11

How to Hide API key in Preact?

How can i hide api key in preact , in react i used .env file , but don't know how to do it in preact ?

index.js?2e9b:8 Uncaught (in promise) ReferenceError: process is not defined
    at eval (index.js?2e9b:8)
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (index.js:5)
    at _next (index.js:7)
    at eval (index.js:7)
    at new Promise (<anonymous>)
    at eval (index.js:7)
    at getSeriesInfo (index.js?2e9b:7)
    at Object.eval [as __] (index.js?2e9b:14)
    at j (index.js?a178:361)

Upvotes: 0

Views: 835

Answers (1)

rschristian
rschristian

Reputation: 2956

Preact is just a UI library, but I'll assume you're referring to Preact-CLI, which is an actual build tool. Let me know if this is incorrect.

Our wiki covers this under "Use Environment Variables in your Application". process will not exist outside of Node so you'll need to specify the variables you want to use using DefinePlugin.

Add the following to your preact.config.js file:

export default (config, env, helpers) => {
    config.plugins.push(
        new helpers.webpack.DefinePlugin({
            'process.env.MY_VARIABLE': JSON.stringify('my-value'),
        }),
    );
};

If you specifically want to read from a .env file, you will also need to add some utility to read it, such as dotenv:

import dotenv from 'dotenv';

dotenv.config();

export default (config, env, helpers) => {
    config.plugins.push(
        new helpers.webpack.DefinePlugin({
            'process.env.MY_VARIABLE': JSON.stringify(process.env.MY_VARIABLE),
        }),
    );
};

Upvotes: 1

Related Questions