next.jsdrizzle

Unable to Load .env Database URL in Drizzle-Kit's drizzle.config.ts with Next.js 14


I am currently leveraging Drizzle-Kit to manage my database tables, specifically using drizzle-kit push:pg. However, in order to execute this command, it necessitates a drizzle.config.ts file containing essential configurations like schema, output, and credentials.

Traditionally, I rely on .env files for storing sensitive credentials. But when integrating with Next.js 14, drizzle-kit push:pg seems unable to access the database URL stored within the .env file. It appears that the environment variable isn't being picked up.

Considering security best practices and the risk associated with storing credentials directly in the drizzle.config.ts file, especially when dealing with version control (Git), I'm reluctant to include these sensitive details there. This approach also requires managing credentials in two separate places, which is far from ideal.

Is there a recommended method or workaround to enable drizzle.config.ts to access the .env file for the database URL while utilizing Drizzle Kit in conjunction with Next.js 14? I'm aiming to maintain a secure approach to handling credentials without compromising on functionality. Any insights or alternative strategies would be greatly appreciated.


Solution

  • This tripped me up initially too! The easiest way I know is to use dotenv to access your relevant .env files.

    Here is my current drizzle config as an example (I am using mysql but the parts with dotenv are what you need):

    import type { Config } from "drizzle-kit";
    import dotenv from "dotenv";
    
    dotenv.config({
      path: ".env.local",
    });
    
    export default {
      schema: "src/db/schema/index.ts",
      out: "src/db/migrations",
      driver: "mysql2",
      dbCredentials: {
        uri: process.env.DATABASE_URL!,
      }
    } satisfies Config