I'll create a complete authentication system with sign-in, sign-up, and session management using Auth.js (formerly NextAuth.js) with MongoDB as the database.
For this authentication system to work, you'll need to set up the following environment variables:
MONGODB_URI=your_mongodb_connection_string
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=your_nextauth_secret
The NEXTAUTH_SECRET
is used to encrypt the JWT tokens. You can generate a secure random string for this.
You might want to add:
Please make sure to add the following environment variable to your project:
Great! Now that you've added the MONGODB_URI environment variable, your authentication system is ready to connect to your MongoDB database. Let's go through what you need to do next to get everything working properly.
Add the remaining environment variables:
NEXTAUTH_URL=http://localhost:3000 (use your deployment URL in production)
NEXTAUTH_SECRET=your_random_secret_key
You can generate a secure NEXTAUTH_SECRET with:
openssl rand -base64 32
Install required dependencies:
npm install next-auth @auth/mongodb-adapter mongodb bcrypt
# Types for TypeScript
npm install -D @types/bcrypt
Initialize your MongoDB database:
users
, accounts
, sessions
, and verification_tokens
.Test the authentication flow:
/signup
to create a new account/signin
/dashboard
without being logged inSign-up process:
/api/register
hashes the password and stores the user in MongoDBSign-in process:
Session management:
Sign-out process:
signOut()
function is calledYou can customize the authentication system in several ways:
maxAge
value in the Auth.js configurationIf you encounter any issues:
Let me know if you need any clarification or have questions about implementing specific features!