Setting Up Your SvelteKit Project
#1 Installing Necessary Dependencies
npm install config cookie uuid string-hash mongodb
- I recommend using config instead of vite's .env variables for better security and reliability.
- cookie is essential for managing cookies effectively.
- uuid is useful for generating unique cookie IDs.
- string-hash provides secure password hashing for database storage.
- mongodb is required to establish a connection to your MongoDB database.
#2 Configuring the config
Library
Create a folder named config in the root directory. Inside this folder, create a file called default.json.
config/default.json
{
"mongoURI": "<yourMongoURI>",
"mongoDB": "<yourDatabaseName>"
}
#3 Setting Up Database Connection Code
Create a lib
folder inside the src
directory. Within the lib
folder, create a file named db.js
.
src/lib/db.js
import { MongoClient } from 'mongodb';
import config from 'config';
export const MONGODB_URI = config.get('mongoURI');
export const MONGODB_DB = config.get('mongoDB');
// Rest of the code remains the same as it establishes a connection with MongoDB using config
This code leverages next.js's approach to MongoDB connection setup but utilizes config instead of .env.