DEV Community

Angela Palaszewski
Angela Palaszewski

Posted on

NextAuth.js with Google Provider for Seamless Authentication

What are we talking about?

NextAuth.js is a powerful authentication library for Next.js applications that provides a simple and flexible way to implement authentication and authorization. It supports various authentication providers, including Google, which allows users to log in to your application using their Google accounts. In this blog post, we will explore how to integrate NextAuth.js with the Google provider, enabling seamless and secure authentication in your Next.js application.

Side Note:
To follow along with this tutorial, you should have a basic understanding of Next.js, React, and JavaScript. Additionally, you'll need a Google account and a Next.js application set up.

Install NextAuth.js and Dependencies
First, create a new Next.js application or use an existing one. Open a terminal and navigate to your project's root directory. Install NextAuth.js and the required dependencies by running the following command:

npm install next-auth google
Enter fullscreen mode Exit fullscreen mode

Configure NextAuth.js
Next, create a file called next-auth.js in the root directory of your Next.js application. This file will contain the configuration for NextAuth.js. Add the following code to the next-auth.js file:

import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';

export default NextAuth({
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
  // Add any additional NextAuth.js configuration options here
});
Enter fullscreen mode Exit fullscreen mode

In this configuration, we're specifying the Google provider by creating an instance of the GoogleProvider class and passing the clientId and clientSecret obtained from the Google Cloud Console. Ensure you have the respective environment variables set up or replace process.env.GOOGLE_CLIENT_ID and process.env.GOOGLE_CLIENT_SECRET with the actual values.

Create the Google OAuth Credentials
To obtain the clientId and clientSecret, you need to set up a project in the Google Cloud Console. Follow these steps:

  1. Go to the Google Cloud Console.
  2. Create a new project or select an existing one.
  3. Enable the "Google+ API" by searching for it in the library and enabling it.
  4. In the "Credentials" section, click on "Create Credentials" and select "OAuth client ID."
  5. Choose "Web application" as the application type.
  6. Enter a name for your OAuth client and add the authorized JavaScript origins and redirect URIs for your Next.js application.
  7. After creating the OAuth client, you'll be provided with the clientId and clientSecret values.

Implement the Sign-In Button
To allow users to sign in using their Google accounts, add a sign-in button to your application's UI. In a React component, add the following code:

import { signIn, signOut, useSession } from 'next-auth/client';

export default function Home() {
  const [session, loading] = useSession();

  if (loading) {
    return <div>Loading...</div>;
  }

  if (!session) {
    return (
      <div>
        <button onClick={() => signIn('google')}>Sign in with Google</button>
      </div>
    );
  }

  return (
    <div>
      <p>Welcome, {session.user.name}</p>
      <button onClick={() => signOut()}>Sign out</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

This code uses the signIn and signOut functions from the next-auth/client module to handle the authentication flow. When the user clicks the "Sign in with Google" button, it triggers the signIn('google') function, which initiates the Google OAuth flow.

Protect Routes with Authentication
To protect specific routes or components, you can use the getSession function from the next-auth/client module. For example, to protect a route, create a higher-order component (HOC) like this:

import { getSession } from 'next-auth/client';
import { useRouter } from 'next/router';

export default function withAuth(Component) {
  return function WithAuth(props) {
    const router = useRouter();

    if (typeof window !== 'undefined' && !session) {
      router.replace('/login');
      return null;
    }

    return <Component {...props} />;
  };
}
Enter fullscreen mode Exit fullscreen mode

Wrap the components you want to protect with the withAuth HOC, and it will redirect users to the login page if they're not authenticated.

Try it!
In this blog post, we explored how to integrate NextAuth.js with the Google provider, allowing users to authenticate with their Google accounts in a Next.js application. By following the steps outlined above, you can leverage NextAuth.js's simplicity and flexibility to implement secure authentication and authorization in your Next.js projects. Was it helpful? Go try it and let me know!

Top comments (0)