To properly read public environment variables in Nuxt 3, you should use the useRuntimeConfig() composable instead of directly accessing process.env. Here's how you can modify your code to correctly access the public environment variables:
import { useRuntimeConfig } from '#app'
const config = useRuntimeConfig()
const client = new Client()
.setEndpoint(config.public.APPWRITE_ENDPOINT)
.setProject(config.public.APPWRITE_PROJECT_ID);
This approach will work both on the server-side and in the browser. Here's why this is the correct way to handle environment variables in Nuxt 3:
-
Nuxt 3 uses a runtime config system to expose configuration and environment variables to your application Runtime Config.
-
You need to define these variables in your nuxt.config.ts file under the runtimeConfig.public object Runtime Config - Exposing.
-
Environment variables prefixed with NUXT_PUBLIC_ are automatically added to the public runtime config Environment Variables.
-
The useRuntimeConfig() composable is used to access these variables throughout your application Access Runtime Config.
Remember to update your nuxt.config.ts file to include these variables:
export default defineNuxtConfig({
runtimeConfig: {
public: {
APPWRITE_ENDPOINT: '',
APPWRITE_PROJECT_ID: ''
}
}
})
Then, you can set the actual values in your .env file:
NUXT_PUBLIC_APPWRITE_ENDPOINT=your_endpoint_here
NUXT_PUBLIC_APPWRITE_PROJECT_ID=your_project_id_here