2 Quick and Easy Ways to Set the Environment Database in Prisma

So you’ve started working with Prisma because you love the type-safety features, automated migrations, and VSCode plugins that give you syntax highlighting. You want to have multiple environments with Prisma, but it reads by default from the .env file. Here are two quick and easy ways to set the environment database in Prisma, methods that don’t require writing scripts for dotenv.

1. Use a deployment service to set your environment variables.

Imagine you have the following Prisma Schema:

generator client {
provider = "prisma-client-js"
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
model schedules {
date Datetime? @db.DateTime(0)
id Int?
description String? @db.VarChar(100)

Prisma loads the environment variable from the .env file, not .env.local or .env.development, unless you use dotenv. So, be aware of where you define DATABASE_URL. In the deployment service you use, you can define DATABASE_URL to be different depending on the environment. Turning on previews for your deployment service is a great way to test out your app in the development database.

Note that you cannot load the provider from an environment variable! Prisma will not let you do this. So make sure you develop your local database provider to be the same across all your environments. It makes sense considering the model schema would have to change depending on the provider.

2. Manipulate the Prisma client object.

Another way you can set the environment variable to use with Prisma is to set it when you are defining the client object.

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient({
  datasources: {
    db: {
      url: process.env.DATABASE_URL,

This is programmatically overriding the DATABASE_URL you set in your Prisma Schema file. This can be useful if you need to check which environment you’re in before giving the client the URL to use because you can programmatically add logic here. You can only override the database URL and not the provider. That has to be defined in the Prisma Schema file.

Dotenv Alternative

Of course, you can use dotenv to specify which environment variable you want to use Prisma with. You have to programmatically load the environment file or run dotenv with every Prisma command, such as:

 dotenv -e .env.local -- npx prisma db pull 

This requires you to write custom scripts. If you wanted to skip that, you can use the first two options. Our use case on a recent project allowed us to get away with just using the first option and defining an environment file with just our local variables for development. It depends on your use case.

Happy coding!


Join the conversation

Your email address will not be published. Required fields are marked *