Skip to content

Commit

Permalink
Setup MongoDB backend
Browse files Browse the repository at this point in the history
  • Loading branch information
pdiegel committed Feb 2, 2024
1 parent 756b4a1 commit 7db50cd
Show file tree
Hide file tree
Showing 4 changed files with 163 additions and 6 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ yarn-error.log*

# local env files
.env*.local
.env

# vercel
.vercel
Expand Down
28 changes: 28 additions & 0 deletions lib/mongodb.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { MongoClient } from "mongodb";

const uri = process.env.MONGODB_URI; // Your MongoDB connection string
declare global {
var _mongoClientPromise: Promise<MongoClient>;
}

let client;
let clientPromise;

if (!process.env.MONGODB_URI) {
throw new Error("Please add your Mongo URI to .env.local");
}

if (process.env.NODE_ENV === "development") {
// In development mode, use a global variable to preserve the database connection
if (!global._mongoClientPromise) {
client = new MongoClient(uri || "");
global._mongoClientPromise = client.connect();
}
clientPromise = global._mongoClientPromise;
} else {
// In production mode, use a new database connection
client = new MongoClient(uri || "");
clientPromise = client.connect();
}

export default clientPromise;
129 changes: 128 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 6 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,20 @@
"lint": "next lint"
},
"dependencies": {
"mongodb": "^6.3.0",
"next": "14.1.0",
"react": "^18",
"react-dom": "^18",
"next": "14.1.0"
"react-dom": "^18"
},
"devDependencies": {
"typescript": "^5",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"autoprefixer": "^10.0.1",
"eslint": "^8",
"eslint-config-next": "14.1.0",
"postcss": "^8",
"tailwindcss": "^3.3.0",
"eslint": "^8",
"eslint-config-next": "14.1.0"
"typescript": "^5"
}
}

0 comments on commit 7db50cd

Please sign in to comment.