How to set environment variables with Prisma, Nextjs, and Vercel

Viewed 1973

Nextjs wants you to use a .env.local file to store env vars. Prisma uses .env

If I use a .env.local file then setting up the Prisma db

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

I get a DATABASE_URL does not exist error.

What's the right way to set up env vars for a Prisma, Nextjs, Vercel app?

2 Answers

You can use dotenv-cli to force loading specific environment file.

1- Install dotenv-cli package

2- create script to run env before prisma migration on your package

"scripts": {
    ...
    "prismaDev": "dotenv -e .env.local prisma migrate dev ",
  }

3- now you can simply run npm run prismaDev

No need to use an extra package, Nextjs will handle the env vars for you.

https://nextjs.org/docs/basic-features/environment-variables

You can leave the standard setup and use the created .env file (by the prisma cli: https://www.prisma.io/docs/getting-started/setup-prisma) and add your connection string.

the rest is magically handled by next. Be sure to follow the instructions (manual or cli pointers) regarding gitignore and such..

To reiterate: both can live next to each other! Check the next documentation for load order if it matters. (see link above)

Related