This guide outlines the steps to integrate MongoDB using Mongoose and implement Google authentication with NextAuth.js in a Next.js project.
- Node.js and npm installed
- MongoDB Atlas account or local MongoDB setup
- Google Cloud Console account
-
Initialize Next.js Project
- Create a new Next.js project using
create-next-app
- Create a new Next.js project using
-
Install Dependencies
- Install
next-auth
,mongoose
, and related types
- Install
-
Environment Configuration
- Create
.env.local
file - Add MongoDB URI, Google OAuth credentials, and NextAuth secret
- Create
-
MongoDB Connection
- Set up a MongoDB connection utility in
lib/mongodb.js
- Set up a MongoDB connection utility in
-
User Model
- Define the User schema in
models/User.js
- Define the User schema in
-
NextAuth Configuration
- Set up NextAuth API route in
app/api/auth/[...nextauth]/route.js
- Configure Google provider and callbacks
- Set up NextAuth API route in
-
Authentication Implementation
- Use NextAuth hooks in components for authentication state
- Implement sign-in and sign-out functionality
-
Route Protection
- Set up middleware for protecting routes
-
Run Development Server
- Start the Next.js development server
lib/mongodb.js
: MongoDB connection utilitymodels/User.js
: Mongoose User modelapp/api/auth/[...nextauth]/route.js
: NextAuth configurationmiddleware.js
: Route protection middleware
Ensure these are set in .env.local
:
MONGODB_URI
GOOGLE_CLIENT_ID
GOOGLE_CLIENT_SECRET
NEXTAUTH_SECRET
NEXTAUTH_URL
- Create a project in Google Cloud Console
- Enable Google+ API
- Create OAuth 2.0 credentials
- Set authorized origins and redirect URIs
- Configure environment variables on the hosting platform
- Update OAuth settings for production URL
- Ensure database connection string is correct for production
For detailed code implementation, refer to the project files in this repository.