4.4. Environment Variables in Admin Customizations
In this chapter, you'll learn how to use environment variables in your admin customizations.
How to Set Environment Variables#
The Medusa Admin is built on top of Vite. To set an environment variable that you want to use in a widget or UI route, prefix the environment variable with VITE_
.
For example:
How to Use Environment Variables#
To access or use an environment variable starting with VITE_
, use the import.meta.env
object.
For example:
1import { defineWidgetConfig } from "@medusajs/admin-sdk"2import { Container, Heading } from "@medusajs/ui"3 4const ProductWidget = () => {5 return (6 <Container className="divide-y p-0">7 <div className="flex items-center justify-between px-6 py-4">8 <Heading level="h2">API Key: {import.meta.env.VITE_MY_API_KEY}</Heading>9 </div>10 </Container>11 )12}13 14export const config = defineWidgetConfig({15 zone: "product.details.before",16})17 18export default ProductWidget
In this example, you display the API key in a widget using import.meta.env.VITE_MY_API_KEY
.
Type Error on import.meta.env#
If you receive a type error on import.meta.env
, create the file src/admin/vite-env.d.ts
with the following content:
This file tells TypeScript to recognize the import.meta.env
object and enhances the types of your custom environment variables.
Check Node Environment in Admin Customizations#
To check the current environment, Vite exposes two variables:
import.meta.env.DEV
: Returnstrue
if the current environment is development.import.meta.env.PROD
: Returnstrue
if the current environment is production.
Learn more about other Vite environment variables in the Vite documentation.
Environment Variables in Production#
When you build the Medusa application, including the Medusa Admin, with the build
command, the environment variables are inlined into the build. This means that you can't change the environment variables without rebuilding the application.
For example, the VITE_MY_API_KEY
environment variable in the example above will be replaced with the actual value during the build process.