Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions app/(protected)/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { auth } from "@clerk/nextjs/server";
import { ProtectedHeader } from "@/components/layout/ProtectedHeader";
import { syncUser } from "@/lib/auth/sync-user";

export default async function ProtectedLayout({
children,
Expand All @@ -9,6 +10,9 @@ export default async function ProtectedLayout({
// Resource-based server-side protection
await auth.protect();

// Automatically sync authenticated user to database (idempotent)
await syncUser();

return (
<div className="min-h-screen flex flex-col bg-[#09090b]">
<ProtectedHeader />
Expand All @@ -18,3 +22,4 @@ export default async function ProtectedLayout({
</div>
);
}

26 changes: 26 additions & 0 deletions db/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { neon } from "@neondatabase/serverless";
import { drizzle } from "drizzle-orm/neon-http";
import * as schema from "./schema";

const databaseUrl = process.env.DATABASE_URL;

if (!databaseUrl) {
if (process.env.NODE_ENV === "production") {
throw new Error(
"DATABASE_URL environment variable is required in production."
);
} else {
console.warn(
"\x1b[33m%s\x1b[0m",
"[db] Warning: DATABASE_URL is missing in environment variables. Add your Neon PostgreSQL URL to .env.local to enable database features."
);
}
}

// Dummy fallback to prevent build-time crashes when DATABASE_URL is not set during initial setup
const connectionString =
databaseUrl || "postgresql://placeholder:placeholder@ep-placeholder.neon.tech/neondb?sslmode=require";

const sql = neon(connectionString);

export const db = drizzle(sql, { schema });
25 changes: 25 additions & 0 deletions db/migrate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { neon } from "@neondatabase/serverless";
import { drizzle } from "drizzle-orm/neon-http";
import { migrate } from "drizzle-orm/neon-http/migrator";
import "dotenv/config";

async function runMigration() {
if (!process.env.DATABASE_URL) {
console.error("❌ DATABASE_URL environment variable is not defined.");
process.exit(1);
}

console.log("⏳ Running Neon PostgreSQL migrations...");
const sql = neon(process.env.DATABASE_URL);
const db = drizzle(sql);

try {
await migrate(db, { migrationsFolder: "./drizzle" });
console.log("✅ Migrations completed successfully!");
} catch (error) {
console.error("❌ Migration failed:", error);
process.exit(1);
}
}

runMigration();
77 changes: 77 additions & 0 deletions db/queries/users.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { eq } from "drizzle-orm";
import { db } from "../index";
import { users, type User } from "../schema/users";

export interface UpsertUserInput {
clerkId: string;
email: string;
username?: string | null;
firstName?: string | null;
lastName?: string | null;
imageUrl?: string | null;
}

/**
* Retrieves a user by their Clerk ID.
*/
export async function getUserByClerkId(clerkId: string): Promise<User | null> {
if (!clerkId) return null;
const result = await db
.select()
.from(users)
.where(eq(users.clerkId, clerkId))
.limit(1);
return result[0] || null;
}

/**
* Retrieves a user by their primary email address.
*/
export async function getUserByEmail(email: string): Promise<User | null> {
if (!email) return null;
const result = await db
.select()
.from(users)
.where(eq(users.email, email))
.limit(1);
return result[0] || null;
}

/**
* Atomically inserts a new user or updates an existing user profile by clerkId.
* Idempotent: safe to run on every authenticated request.
*/
export async function upsertUserFromClerk(
userData: UpsertUserInput
): Promise<User> {
const now = new Date();

const [user] = await db
.insert(users)
.values({
clerkId: userData.clerkId,
email: userData.email,
username: userData.username ?? null,
firstName: userData.firstName ?? null,
lastName: userData.lastName ?? null,
imageUrl: userData.imageUrl ?? null,
lastLoginAt: now,
createdAt: now,
updatedAt: now,
})
.onConflictDoUpdate({
target: users.clerkId,
set: {
email: userData.email,
username: userData.username ?? null,
firstName: userData.firstName ?? null,
lastName: userData.lastName ?? null,
imageUrl: userData.imageUrl ?? null,
lastLoginAt: now,
updatedAt: now,
},
})
.returning();

return user;
}
1 change: 1 addition & 0 deletions db/schema/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./users";
38 changes: 38 additions & 0 deletions db/schema/users.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import {
pgTable,
uuid,
varchar,
text,
timestamp,
index,
} from "drizzle-orm/pg-core";

export const users = pgTable(
"users",
{
id: uuid("id").defaultRandom().primaryKey(),
clerkId: varchar("clerk_id", { length: 255 }).notNull().unique(),
email: varchar("email", { length: 255 }).notNull().unique(),
username: varchar("username", { length: 255 }),
firstName: varchar("first_name", { length: 255 }),
lastName: varchar("last_name", { length: 255 }),
imageUrl: text("image_url"),
createdAt: timestamp("created_at", { withTimezone: true, mode: "date" })
.defaultNow()
.notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true, mode: "date" })
.defaultNow()
.notNull()
.$onUpdate(() => new Date()),
lastLoginAt: timestamp("last_login_at", { withTimezone: true, mode: "date" })
.defaultNow()
.notNull(),
},
(table) => [
index("users_clerk_id_idx").on(table.clerkId),
index("users_email_idx").on(table.email),
]
);

export type User = typeof users.$inferSelect;
export type NewUser = typeof users.$inferInsert;
13 changes: 13 additions & 0 deletions drizzle.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import "dotenv/config";
import { defineConfig } from "drizzle-kit";

export default defineConfig({
out: "./drizzle",
schema: "./db/schema/index.ts",
dialect: "postgresql",
dbCredentials: {
url:
process.env.DATABASE_URL ||
"postgresql://user:password@localhost:5432/neondb",
},
});
17 changes: 17 additions & 0 deletions drizzle/0000_aromatic_mandroid.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
CREATE TABLE "users" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"clerk_id" varchar(255) NOT NULL,
"email" varchar(255) NOT NULL,
"username" varchar(255),
"first_name" varchar(255),
"last_name" varchar(255),
"image_url" text,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
"last_login_at" timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT "users_clerk_id_unique" UNIQUE("clerk_id"),
CONSTRAINT "users_email_unique" UNIQUE("email")
);
--> statement-breakpoint
CREATE INDEX "users_clerk_id_idx" ON "users" USING btree ("clerk_id");--> statement-breakpoint
CREATE INDEX "users_email_idx" ON "users" USING btree ("email");
142 changes: 142 additions & 0 deletions drizzle/meta/0000_snapshot.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
{
"id": "73af57d1-719f-4bae-9a4c-0328ceef6b84",
"prevId": "00000000-0000-0000-0000-000000000000",
"version": "7",
"dialect": "postgresql",
"tables": {
"public.users": {
"name": "users",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true,
"default": "gen_random_uuid()"
},
"clerk_id": {
"name": "clerk_id",
"type": "varchar(255)",
"primaryKey": false,
"notNull": true
},
"email": {
"name": "email",
"type": "varchar(255)",
"primaryKey": false,
"notNull": true
},
"username": {
"name": "username",
"type": "varchar(255)",
"primaryKey": false,
"notNull": false
},
"first_name": {
"name": "first_name",
"type": "varchar(255)",
"primaryKey": false,
"notNull": false
},
"last_name": {
"name": "last_name",
"type": "varchar(255)",
"primaryKey": false,
"notNull": false
},
"image_url": {
"name": "image_url",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"last_login_at": {
"name": "last_login_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {
"users_clerk_id_idx": {
"name": "users_clerk_id_idx",
"columns": [
{
"expression": "clerk_id",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
},
"users_email_idx": {
"name": "users_email_idx",
"columns": [
{
"expression": "email",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": false,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {
"users_clerk_id_unique": {
"name": "users_clerk_id_unique",
"nullsNotDistinct": false,
"columns": [
"clerk_id"
]
},
"users_email_unique": {
"name": "users_email_unique",
"nullsNotDistinct": false,
"columns": [
"email"
]
}
},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
}
},
"enums": {},
"schemas": {},
"sequences": {},
"roles": {},
"policies": {},
"views": {},
"_meta": {
"columns": {},
"schemas": {},
"tables": {}
}
}
13 changes: 13 additions & 0 deletions drizzle/meta/_journal.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"version": "7",
"dialect": "postgresql",
"entries": [
{
"idx": 0,
"version": "7",
"when": 1785866517131,
"tag": "0000_aromatic_mandroid",
"breakpoints": true
}
]
}
Loading