Skip to content

Commit 1ae357b

Browse files
document env() behavior with optional environment variables in prisma.config.ts (#7342)
1 parent e8a0927 commit 1ae357b

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

content/200-orm/500-reference/325-prisma-config-reference.mdx

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -626,6 +626,43 @@ export default defineConfig({
626626
});
627627
```
628628

629+
#### Handling optional environment variables
630+
631+
The `env()` helper function from `prisma/config` **throws an error** if the specified environment variable is not defined. This is important to understand because:
632+
633+
- Every Prisma CLI command loads the `prisma.config.ts` file
634+
- Only **some** commands actually need the `datasource.url` value (e.g., `prisma db *`, `prisma migrate *`, `prisma generate --sql`)
635+
- Commands like `prisma generate` don't need a database URL, but will still fail if `env()` throws an error when loading the config file
636+
637+
For example, if you run `prisma generate` without `DATABASE_URL` set, and your config uses `env('DATABASE_URL')`, you'll see:
638+
639+
```terminal
640+
Error: PrismaConfigEnvError: Missing required environment variable: DATABASE_URL
641+
```
642+
643+
**Solution:** If your environment variable isn't guaranteed to exist (e.g., in CI/CD pipelines where you only run `prisma generate` for type-checking), don't use the `env()` helper. Instead, access the environment variable directly:
644+
645+
```ts
646+
import 'dotenv/config'
647+
import { defineConfig } from "prisma/config";
648+
649+
export default defineConfig({
650+
schema: 'prisma/schema.prisma',
651+
migrations: {
652+
path: 'prisma/migrations',
653+
},
654+
datasource: {
655+
url: process.env.DATABASE_URL!, // Or use: process.env.DATABASE_URL ?? '' to provide a fallback value
656+
},
657+
});
658+
```
659+
660+
:::note
661+
662+
Use the `env()` helper when you want to **enforce** that an environment variable exists. Use `process.env` directly when the variable may be optional depending on the command being run.
663+
664+
:::
665+
629666
### Using multi-file schemas
630667

631668
If you want to split your Prisma schema into multiple files, you need to specify the path to your Prisma schema folder via the `schema` property:

0 commit comments

Comments
 (0)