add express, automated mongodb atlas setup, fix stack architech

This commit is contained in:
Aman Varshney
2025-04-07 21:32:22 +05:30
parent c6c73fce76
commit 2cf01d155b
38 changed files with 902 additions and 393 deletions

View File

@@ -0,0 +1,14 @@
import type { CreateExpressContextOptions } from "@trpc/server/adapters/express";
import { fromNodeHeaders } from "better-auth/node";
import { auth } from "./auth";
export async function createContext(opts: CreateExpressContextOptions) {
const session = await auth.api.getSession({
headers: fromNodeHeaders(opts.req.headers),
});
return {
session,
};
}
export type Context = Awaited<ReturnType<typeof createContext>>;

View File

@@ -0,0 +1,34 @@
import "dotenv/config";
import { createExpressMiddleware } from "@trpc/server/adapters/express";
import { toNodeHandler } from "better-auth/node";
import cors from "cors";
import express from "express";
import { auth } from "./lib/auth";
import { createContext } from "./lib/context";
import { appRouter } from "./routers/index";
const app = express();
app.use(
cors({
origin: process.env.CORS_ORIGIN || "",
methods: ["GET", "POST", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization"],
credentials: true,
}),
);
app.all("/api/auth{/*path}", toNodeHandler(auth));
app.use(express.json());
app.use("/trpc", createExpressMiddleware({ router: appRouter, createContext }));
app.get("/", (_req, res) => {
res.status(200).send("OK");
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});

View File

@@ -0,0 +1,17 @@
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import prisma from "../../prisma";
export const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: "mongodb",
}),
trustedOrigins: [process.env.CORS_ORIGIN || ""],
emailAndPassword: { enabled: true },
advanced: {
defaultCookieAttributes: {
sameSite: "none",
secure: true,
},
},
});