KeystoneJS: Use different databases on production and development environments.

Using separate databases for different project environments is a well-known best practice. Here's how to setup distinct databases on a KeystoneJS project.

Oct 24, 2023

Unlike NextJS and React, KeystoneJS doesn't include the dotenv library right out of the box. So, let's kick things off by installing this library:

npm i dotenv

Import dotenv into your keystone.ts (or keystone.js) file:

import dotenv from 'dotenv';
dotenv.config({ path: `.env-${process.env.NODE_ENV}` });

Now, let's set the environment variable when you run your development environment. This tells Keystone which environment file to use. Open your package.json file, and under the scripts section, change the command for running development from:

"keystone dev"

to:

"export NODE_ENV=development && keystone dev"

Create two files for your environment variables: .env-development and .env-production. In each of these files, add the database URL and provider specific to the environment you're targeting. For instance, if you're using SQLite for development and PostgreSQL for production:

In your .env-development file:

DATABASE_URL: "file:./keystone.db"
PROVIDER: "sqlite"

And in your .env-production file:

DATABASE_URL: "[Database URL from hosting provider]"
PROVIDER: "postgresql"

To test the production setup, update the build script with the production environment variable:

Modify the build command from:

"keystone build"

to:

"export NODE_ENV=production && keystone build"

By following these steps, you'll effectively configure different databases for your KeystoneJS project in both development and production environments. This separation streamlines project management and aligns with best practices in web development.

Here's a Git diff of the above changes: https://github.com/iris-i/deep-dives-cms/commit/93ffe2fb000b531331a4387f9b9202c302d2a52c