Skip to content

Commit 574fd81

Browse files
fix(netlify): Make database connection lazy and enable serverless deployment
- Changed db.ts to use lazy initialization pattern to prevent build-time errors - Removed static export mode from next.config.ts to support API routes - Build now succeeds even when DATABASE_URL is not set during build time
1 parent 4b4a599 commit 574fd81

2 files changed

Lines changed: 25 additions & 9 deletions

File tree

next.config.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import type { NextConfig } from "next";
22

33
const nextConfig: NextConfig = {
4-
output: "export",
54
/* config options here */
65
};
76

src/lib/db.ts

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,32 @@ import { drizzle } from 'drizzle-orm/neon-serverless';
22
import { Pool } from '@neondatabase/serverless';
33
import * as schema from './schema';
44

5-
if (!process.env.DATABASE_URL) {
6-
throw new Error('DATABASE_URL environment variable is not set');
5+
// Lazy initialization - only create pool when needed
6+
let pool: Pool | null = null;
7+
let dbInstance: ReturnType<typeof drizzle> | null = null;
8+
9+
function getPool() {
10+
if (!pool) {
11+
if (!process.env.DATABASE_URL) {
12+
throw new Error('DATABASE_URL environment variable is not set');
13+
}
14+
pool = new Pool({ connectionString: process.env.DATABASE_URL });
15+
}
16+
return pool;
717
}
818

9-
// Create a connection pool
10-
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
19+
function getDb() {
20+
if (!dbInstance) {
21+
dbInstance = drizzle(getPool(), { schema });
22+
}
23+
return dbInstance;
24+
}
1125

12-
// Create and export the drizzle instance
13-
export const db = drizzle(pool, { schema });
26+
// Export getters instead of direct instances
27+
export const db = new Proxy({} as ReturnType<typeof drizzle>, {
28+
get(target, prop) {
29+
return getDb()[prop as keyof ReturnType<typeof drizzle>];
30+
}
31+
});
1432

15-
// Export the pool for direct access if needed
16-
export { pool };
33+
export { getPool as pool };

0 commit comments

Comments
 (0)