Nuxt
The Nuxt package comes preconfigured for Nuxt, and fills the runtimeEnv
option automatically. All you need to do is define your schemas!
Install dependencies
Install the required dependencies:
pnpm add @t3-oss/env-nuxt zod
pnpm add @t3-oss/env-nuxt zod
💡
@t3-oss/env-core
requires a minimum of typescript@4.7.2
.
Create your schema
env.ts
import { createEnv } from "@t3-oss/env-nuxt";
import { z } from "zod";
export const env = createEnv({
server: {
DATABASE_URL: z.string().url(),
OPEN_AI_API_KEY: z.string().min(1),
},
client: {
NUXT_PUBLIC_PUBLISHABLE_KEY: z.string().min(1),
},
});
env.ts
import { createEnv } from "@t3-oss/env-nuxt";
import { z } from "zod";
export const env = createEnv({
server: {
DATABASE_URL: z.string().url(),
OPEN_AI_API_KEY: z.string().min(1),
},
client: {
NUXT_PUBLIC_PUBLISHABLE_KEY: z.string().min(1),
},
});
Validate schema on build (recommended)
We recommend you importing your newly created file in your nuxt.config.ts
. This will make sure your environment variables are validated at build time which will save you a lot of time and headaches down the road.
nuxt.config.ts
import "./env";
export default defineNuxtConfig({
// ...
});
nuxt.config.ts
import "./env";
export default defineNuxtConfig({
// ...
});
Use your schema
Then, import the env
object in your application and use it, taking advantage of type-safety and auto-completion:
server/api/some-endpoint.ts
import { env } from "~~/env"; // On server
export default defineEventHandler(() => {
// do fancy ai stuff
const magic = await fetch("...", {
headers: { Authorization: env.OPEN_AI_API_KEY },
});
// ...
});
server/api/some-endpoint.ts
import { env } from "~~/env"; // On server
export default defineEventHandler(() => {
// do fancy ai stuff
const magic = await fetch("...", {
headers: { Authorization: env.OPEN_AI_API_KEY },
});
// ...
});
app.vue
<script setup lang="ts">
import { env } from "~~/env"; // On client - same import!
</script>
<template>
<div>Client says {{ env.NUXT_PUBLIC_GREETING }}!</div>
<a href="/api/hello">See what the server has to say!</a>
</template>
app.vue
<script setup lang="ts">
import { env } from "~~/env"; // On client - same import!
</script>
<template>
<div>Client says {{ env.NUXT_PUBLIC_GREETING }}!</div>
<a href="/api/hello">See what the server has to say!</a>
</template>