Migrating Environment Variables
Sanity Studio v3 uses Vite as its default bundler and development server and uses its approach to environment variables. It replaces the implicit replacement of predefined variables in v2, and exposes variables on import.meta.env.SANITY_STUDIO_VARIABLE_NAME
instead of process.env.SANITY_STUDIO_VARIABLE_NAME
.
Vite will automatically pick up variables in your environment prefixed with SANITY_STUDIO_
.
You might be used from server-side applications to access environment variables using process.env.SANITY_STUDIO_VARIABLE_NAME
. Since the Studio is a static client-side application, these variables will be bundled and exposed as import.meta.env.SANITY_STUDIO_VARIABLE_NAME
. In other words, the value of these variables will be included in the app source code.
# .env
SANITY_STUDIO_PROJECT_ID=your-project-id
SANITY_STUDIO_DATASET=your-dataset-name
// sanity.config.js
import { defineConfig } from "sanity";
import { deskTool } from "sanity/desk";
import schemaTypes from "./schemas";
export default defineConfig({
projectId: import.meta.env.SANITY_STUDIO_PROJECT_ID,
dataset: import.meta.env.SANITY_STUDIO_DATASET,
plugins: [
deskTool(),
],
schema: {
types: schemaTypes,
},
});
It is common practice to keep secret tokens and API keys as environment variables that are not checked into version control. This is a decent strategy for server-side applications where the runtime is protected. However, since the Studio is a client-side application, you will have to approach secrets differently. We recommend using the Sanity Secrets library that gives you hooks and UI components for handling secrets.
Vite will read .env
files by default and make its variables available for the development server. Note that you still have to follow the variable naming conventions mentioned above. Vite also supports env loading priorities for situations where you want to differentiate between sharing certain variables in all environments and overwriting them for production builds.
.env # loaded in all cases
.env.local # loaded in all cases, ignored by git
.env.[mode] # only loaded in specified mode
.env.[mode].local # only loaded in specified mode, ignored by git
If you use TypeScript, then you might encounter the Property 'env' does not exist on type 'ImportMeta'
error when trying to access your variables on import.meta.env
. To fix this, you will need to add typings for your variables. Following the official Vite documentation, replacing the VITE_APP_
prefix with SANITY_STUDIO_
:
// env.d.ts /// <reference types="vite/client" /> interface ImportMetaEnv { readonly SANITY_STUDIO_PROJECT_ID: string; readonly SANITY_STUDIO_DATASET: string; // more env variables... } interface ImportMeta { readonly env: ImportMetaEnv; }