In this tutorial, we'll explore how to set up authentication in a Next.js application using NextAuth.js with Google OAuth2 as the authentication provider. OAuth2 is a widely-used protocol for user authentication, and Google OAuth2 allows users to sign in to applications using their Google accounts, eliminating the need for separate account registration.
We'll cover the following steps:
- Setting up a Next.js project.
- Obtaining OAuth2 credentials from the Google Developer Console.
- Configuring NextAuth.js with Google OAuth2 provider.
- Integrating user authentication into Next.js pages.
- Running the application and testing the authentication flow.
By the end of this tutorial, you'll have a solid understanding of how to implement user authentication in your Next.js applications using NextAuth.js and Google OAuth2, empowering you to build secure and user-friendly web experiences.
Prerequisites:
- Basic knowledge of Next.js and React.
- Node.js installed on your machine.
- A Google Developer account to obtain OAuth2 credentials.
Step 1 : Set Up a Next.js Project
If you haven't already, create a new Next.js project:
npx create-next-app@latest my-next-auth-app
cd my-next-auth-app
Step 2 : Install Dependencies
Install NextAuth.js and its required dependencies:
npm install next-auth
npm install mongoose dotenv # If you're using MongoDB as your database
# Or npm install other-database-driver if you're using a different database
Step 3 : Set Up Google OAuth2 Credentials
- Go to the Google Developers Console: https://console.developers.google.com/.
- Navigate to Credentials and create OAuth client ID credentials.
- Set the authorized redirect URI to http://localhost:3000/api/auth/callback/google
- Note down your Client ID and Client Secret for later use.
Step 4 : Create a Database Configuration
Create a configuration file for your database connection. For MongoDB, you might create a file config/database.ts:
// config/database.ts
import mongoose from 'mongoose';
export default async function connectDB() {
try {
await mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log('Connected to MongoDB');
} catch (error) {
console.error('Error connecting to MongoDB:', error);
process.exit(1);
}
}
Step 5 : Create User Model
Define a User model. Create a file models/User.ts:
// models/User.ts
import mongoose from 'mongoose';
const UserSchema = new mongoose.Schema({
email: { type: String, unique: true },
username: String,
image: String,
});
export default mongoose.model('User', UserSchema);
Step 6 : Create NextAuth.ts Configuration
Create a file auth/[...nextauth].ts for configuring NextAuth.ts:
// auth/[...nextauth].ts
import connectDB from '@/config/database';
import User from '@/models/User';
import { Profile, Session, DefaultSession, AuthOptions } from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
export const authOptions: AuthOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
authorization: {
params: {
prompt: 'consent',
access_type: 'offline',
response_type: 'code',
},
},
}),
],
session: {
strategy: 'jwt',
},
jwt: {
secret: process.env.NEXTAUTH_SECRET,
},
callbacks: {
async signIn({ profile }: { profile?: Profile | undefined }): Promise {
await connectDB();
const userExist = await User.findOne({ email: profile?.email });
if (!userExist) {
const username = profile?.name?.slice(0, 20);
await User.create({
email: profile?.email,
username,
image: profile?.image,
});
}
return true;
},
async session({
session,
}: {
session: Session | DefaultSession;
}): Promise {
const user = await User.findOne({ email: session.user?.email });
if (session.user) session.user = user;
return session;
},
},
};
Step 7 : Create User Model
Set up your environment variables. Create a .env.local file in the root directory of your project:
# .env.local
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
NEXTAUTH_SECRET=your_nextauth_secret
MONGODB_URI=your_mongodb_uri
Step 8 : Integrate Authentication in Pages
You can integrate authentication in your pages using NextAuth.js hooks or higher-order components. For example, you can create a pages/dashboard.js:
// pages/dashboard.tsx
import { useSession } from 'next-auth/react';
export default function Dashboard() {
const { data: session } = useSession();
if (!session) {
// Redirect to sign-in page if not authenticated
return ;
}
return (
{/* Dashboard content */}
);
}
Step 9 : Start the Development Server
Start your Next.js development server:
npm run dev
Now you have a Next.js application set up with authentication using NextAuth.js and Google OAuth2 provider. Users can sign in with their Google accounts, and their session will be managed by NextAuth.js.