Author

PinoyFreeCoder

Published

Sun Mar 24 2024

Type

Free

Download

Not Available

TypeScriptReactJSauthenticationauthOptionTypeScriptNextJSReactJSauthenticationauthOption

Share this Source Code

Share This Article

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.

Quick Actions

Technologies

TypeScript
NextJS
ReactJS
authentication
authOption

Featured Products

Discover amazing deals and products we recommend

Bonavita Coffee 8 in 1 ( Buy 5 boxes + 1 box FREE)

Bonavita Coffee 8 in 1 ( Buy 5 boxes + 1 box FREE)

Sustainably sourced, chemical-free beans for a delightful brew. Packed With Rich Nutrients. Coffee drink with mangosteen, guyabano and acai berry!

View Product
Ambi Pur Car Freshener Sky Breeze Value Pack Lavender Comfort Value Pack 2.2ml Car Vent Clip (Long-lasting Car Freshener, Air Freshener)

Ambi Pur Car Freshener Sky Breeze Value Pack Lavender Comfort Value Pack 2.2ml Car Vent Clip (Long-lasting Car Freshener, Air Freshener)

Ambi Pur Car Freshener Sky Breeze Value Pack Lavender Comfort Value Pack 2.2ml Car Vent Clip (Long-lasting Car Freshener, Air Freshener)

View Product
URU4500 Digital Persona Biometric Reader Fingerprint U.are.U 4500 Fingerprint Scanner With Free SDK

URU4500 Digital Persona Biometric Reader Fingerprint U.are.U 4500 Fingerprint Scanner With Free SDK

The U.are.U 4500 Fingerprint Reader is a USB peripheral perfect for individual desk top users, as well as multiple users in shared environments. Its compact design conserves desk space in enterprises, and its professional, modern appearance looks elegant in point-of-sale environments.

View Product
ANSEN Webcam for PC Laptop Online Class 2K 1080P HD USB Web Camera with Mic

ANSEN Webcam for PC Laptop Online Class 2K 1080P HD USB Web Camera with Mic

ANSEN 1080P Webcam for PC Laptop Online Class Webcams HD USB Web Camera with Mic Live Steam

View Product
TOPICAL HAIR GROWER TRINOXTERIDE20 (ROLL ON)

TOPICAL HAIR GROWER TRINOXTERIDE20 (ROLL ON)

After washing your hair, roll on your scalp or skin spot you want to grow hair and gently massage for 2-3 minutes, no need to wash out, oil-based easy to use, and visible results within 2-4 weeks (depending on the skin absorption)

View Product
NB North Bayou DUAL Monitor Arm Mount Stand F160 by NeatPH

NB North Bayou DUAL Monitor Arm Mount Stand F160 by NeatPH

The F160 dual screen desktop monitor arm has a durable Gas-strut design to enable adjustment of your screen to your desired height and angle. This allows you to experience your interface from the best possible viewing angle. This design is particularly useful in a professional environment for collaborative work that requires multiple screens, or any space where you need to efficiently fit multiple screens. A gravity spring pivot joint design offers effortless titling to eliminate awkward positioning.

View Product
Logitech Gaming Mouse G102 LIGHTSYNC 8,000 DPI Customizable RGB Lighting 6 Programmable Button Wired

Logitech Gaming Mouse G102 LIGHTSYNC 8,000 DPI Customizable RGB Lighting 6 Programmable Button Wired

Make the most of play time with G203—a gaming mouse in a variety of vibrant colors. With LIGHTSYNC technology, a gaming-grade sensor and a classic 6-button design, you’ll light up your game and your desk

View Product
Under Table Storage basket Cable Management Tray Desk Socket Holder Wire Organizer Rack Storage Rack

Under Table Storage basket Cable Management Tray Desk Socket Holder Wire Organizer Rack Storage Rack

【ADJUSTABLE CLAMP】Screw clamp is easy to remove and reattach, adjustable clamps securely onto desks up to 4cm/1.57inch thick and as narrow as 1.2cm/0.47inch for a near universal fit on most desks.

View Product
NESTEA Cleanse Lemon Cucumber Powdered Green Tea with Fiber 8.5g x 10

NESTEA Cleanse Lemon Cucumber Powdered Green Tea with Fiber 8.5g x 10

Refresh with a delicious blend of all-natural green tea, lemon and cucumber extracts with NEW NESTEA CLEANSE! It's high in fiber which aids in digestion, and has no added table sugar. So go ahead -- start your wellness journey with NESTEA CLEANSE! Ang Gaan with NESTEA!

View Product
Page 1 of 9