I've been working on setting up a project with Drizzle + Next.js + Vercel for my serverless backend. To utilize the ORM API of Drizzle, I reference my database in the following way:
import { drizzle } from "drizzle-orm/vercel-postgres";
import { sql } from "@vercel/postgres";
import { users } from "./schema";
import * as schema from "./schema";
export const db = drizzle(sql, { schema });
It became apparent that passing the {schema} parameter is necessary to infer typing for typescript and use the ORM relations defined in schemas.
However, I also came across the drizzle-kit which utilizes a drizzle.config.ts file referencing the schema like this:
import "@/lib/config";
import { defineConfig } from "drizzle-kit";
export default defineConfig({
schema: "./lib/schema.ts",
out: "./drizzle",
driver: "pg",
dbCredentials: {
connectionString: process.env.POSTGRES_URL,
},
verbose: true,
strict: true,
});
Initially, I assumed that using drizzle-kit obviated the need for the additional part "{ schema }" but it appears not to be the case.
The Drizzle documentation states:
Drizzle Kit allows you to split your schema into different files and manage multiple schemas for various databases within one project. You can swiftly design your database schema and push it directly to the database.
This raised the question of why do I have to specify the schema location twice? What role does my drizzle.config.ts file play?
Thank you
I attempted passing the config object directly to drizzle in this manner:
import { sql } from "@vercel/postgres";
import { drizzle } from "drizzle-orm/vercel-postgres";
import {config} from "@/drizzle.config";
// import dotenv from 'dotenv'
// dotenv.config({ path: '.env.local' })
// Utilize dotenv or a custom next js script to load .env.local variables in process.env for Node.js backend
import { loadEnvConfig } from "@next/env";
const projectDir = process.cwd();
loadEnvConfig(projectDir);
export const db = drizzle(sql, config);
or like this :
import { sql } from "@vercel/postgres";
import { drizzle } from "drizzle-orm/vercel-postgres";
import {config} from "@/drizzle.config";
// import dotenv from 'dotenv'
// dotenv.config({ path: '.env.local' })
// Utilize dotenv or a custom next js script to load .env.local variables in process.env for Node.js backend
import { loadEnvConfig } from "@next/env";
const projectDir = process.cwd();
loadEnvConfig(projectDir);
export const db = drizzle(sql, {schema: config.schema});
Unfortunately, neither method worked as expected.