How to Use Next-Auth with Google Sign-In

2022/10/113 min read
bookmark this

Table of Contents

  1. Introduction
  2. Requirements
  3. Client ID, Secret, OAuth Consent Screen Setup
  4. Get Started with NextAuth.js with Google Sign-In
  5. Conclusion

Introduction

This tutorial shows how to integrate sign in with Google by using next-auth.js under a Next.js Web Application. For how to set up or configure Google Sign-In, please reference here for details about setting up Google Sign-In.

Requirements

Since this tutorial assumes we're using Google Account with next-auth.js in Next.js, below are the minimum requirements to follow this tutorial.

  • GCP
    • Has knowledge of using Google Cloud.
    • Has set up a project using Google Cloud.
  • Next.js
    • Already has an application built with Next.js.
    • Has knowledge of how to use Next.js.

Client ID, Secret, OAuth Consent Screen Setup

Regarding Google OAuth Client ID and Secret, and OAuth Consent Screen setup, please reference here to see more details.

Get Started with NextAuth.js with Google Sign-In

Here we'll set up NextAuth.js in the Next.js application. First, let's install the dependency packages.

npm install next-auth

Next, let's replace _app.js with the code below.

Before

export default function App({ Component, pageProps }) {
  return <Component {...pageProps} />;
}

After

import { SessionProvider } from 'next-auth/react';

export default function App({ Component, pageProps }) {
  return (
    <SessionProvider session={pageProps.session}>
      <Component {...pageProps} />
    </SessionProvider>
  );
}

Create [...nextauth...].js under the pages/api/auth location. NextAuth.js has many different providers, and Google Account is just one of them. Replace the below clientid and client_secret with the ones you already created in the OAuth setup. Also, _NextAuth.js has different callbacks that you can use to integrate with your own system, such as checking whether the user has already registered in your application or not.

import type { NextApiRequest, NextApiResponse } from 'next';
import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';

export default async function auth(req: NextApiRequest, res: NextApiResponse) {
  return await NextAuth(req, res, {
    providers: [
      GoogleProvider({
        clientId:
          'my_client_id',
        clientSecret: 'my_client_secret',
      }),
    ],
    callbacks: {
      async jwt({ token, account, isNewUser, profile, user }) {
        return token;
      },
      async signIn({ user, account, profile, email, credentials }) {

        if (account.provider === 'google') {
          // check if user already exist or not with custom db

          else {
            // existing user
          }
        }
        return true;
      },
      async redirect({ url, baseUrl }) {
        return baseUrl;
      },
      async session({ session, token, user }) {
        return session;
      },
    },
    theme: {
      colorScheme: 'light',
      brandColor: '#343434',
      logo: '',
      buttonText: '#333',
    },
  });
}

Conclusion

Sign In with Google is a straightforward way to let your users authenticate with your application. With next-auth, it's even better because it is able to manage the session and makes it easy to manage user information or integrate with Google Sign-In and other third-party sign-in platforms. Next, we will cover how to integrate Google Sign-In with a Next.js web application without using next-auth.