There is a risk that your production database could be deleted if you store different connection URLs to each of your environments within a single .env file.

One solution is to have multiple .env files which each represent different environments. In practice this means you create a file for each of your environments:

  • .env.development
  • .env.test

.env.production is omitted from the above list as it's is not recommended to store your production credentials locally, even if they are git ignored.

Then using a package like dotenv-cli, you can load the correct connection URL for the environment you are working in.

Setup multiple .env files

For the purpose of this guide it is assumed you have a dedicated development database which you use whilst developing your application.

  1. Rename your .env file to .env.development
.env.development
1DATABASE_URL="postgresql://prisma:prisma@localhost:5433/dev"
  1. Create a new .env.test file and change the database name to test (or your preferred name)
.env.test
1DATABASE_URL="postgresql://prisma:prisma@localhost:5433/test"
  1. Install dotenv-cli

In order for Prisma and Jest to know which .env file to use, alter your package.json scripts to include and call the dotenv package and specify which file to use depending on what commands you are running and in which environment you want them to run.

Any top level script that is running the tests and migrations needs the dotenv command before it. This makes sure that the env variables from .env.test are passed to all commands including Jest.

Running migrations on different environments

You can use the dotenv-cli package to specify which environment file Prisma should use when running a migration.

The below script uses dotenv-cli to pass the .env.test environment file (which holds a DATABASE_URL connection string) to the Prisma migration script.

Migration script

package.json
1 "scripts": {
2 "migrate:postgres": "dotenv -e .env.test -- npx prisma migrate deploy",
3 },

Running tests on different environments

When running tests we advise you to mock the Prisma Client, in doing so you need to tell Jest which environment it should use when running its tests.

By default the Prisma Client will use the environment specified in the default .env file located at the projects root.

If you have created a separate .env.test file to specify your testing database, then this environment will need to be passed to Jest.

The below script uses dotenv-cli to pass the .env.test environment file (which holds a DATABASE_URL connection string) to Jest.

Test script

package.json
1 "scripts": {
2 "test": "dotenv -e .env.test jest -i"
3 },
Edit this page on GitHub