Using Environment Variables
The Plasmo framework utilizes a cascading/overriding strategy for environment variables using the dotenv
package. Next.js developers will find this familiar as it's the same package Next.js uses.
To add public environment variables accessible to the extension, create a .env
file:
PLASMO_PUBLIC_SHIP_NAME=ncc-1701
PLASMO_PUBLIC_SHIELD_FREQUENCY=42
PRIVATE_KEY=xxx
Only environment variables prefixed with PLASMO_PUBLIC_
will be exposed in the built version of your extension. Use them in any of your extension's source files:
// For TSX (popups, options):
const FrontHull = () => <h1>{process.env.PLASMO_PUBLIC_SHIP_NAME}</h1>
// For TS (content scripts or background-scripts):
const shield = new Shield(process.env.PLASMO_PUBLIC_SHIELD_FREQUENCY)
// Will be undefined
console.log(process.env.PRIVATE_KEY)
To override a variable in the production build with plasmo build
, supply a .env.production
file. Since Plasmo cascades .env files, only specify the variable to replace.
To enjoy Typescript IntelliSense with your environment variables, create an index.d.ts
file:
declare namespace NodeJS {
interface ProcessEnv {
PLASMO_PUBLIC_SHIP_NAME?: string
PLASMO_PUBLIC_SHIELD_FREQUENCY?: number
}
}
See with-env-files for more details about using .env variables.
Non-cascading environment variables
Sometimes, you might want some environment variables strictly for development. Environment-specific files only inject into their environments and don't cascade:
.env.development
.env.production
If there is a CRX_PUBLIC_KEY
environment variable in .env.development
but not in .env.production
or .env
, it will be available in plasmo dev
but not plasmo build
.
Local namespaced environment variables
Plasmo also supports the following environment file names (Next.js developers will find this familiar):
.env.local
.env.production.local
.env.development.local
Files with .local
at the end of their names have a higher priority than the non-local ones. .env.local
has higher priority than .env.production
and .env.development
. Within the same namespace, however, the cascading order is as expected.
Using env in remote code import statements
Use public environment variables if you are importing remote code:
import "https://www.plasmo.com/js?id=$PLASMO_PUBLIC_ITERO"
Using env in manifest overrides
Plasmo enables you to override the final generated extension manifest via the manifest
property of the package.json file. Taking one step further, Plasmo also parses any environment variables used in the manifest overrides:
"manifest": {
"key": "$CRX_PUBLIC_KEY"
}
You can use public (prefixed with PLASMO_PUBLIC
) and private environment variables in your manifest overrides. 😎
NOTE: Plasmo will delete the key if it can't find the environment variable.