Author
PinoyFreeCoder
Published
Sun Mar 24 2024
Type
Free
Download
Not Available
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.
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.
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
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
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);
}
}
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);
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;
},
},
};
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
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 */}
);
}
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.
Discover amazing deals and products we recommend