DEV Community

Mateen Ahmed
Mateen Ahmed

Posted on

Setting up Next Auth to Register with Google

Setting up Authentication for a project might seem difficult, but it is quite easy to enable Google authentication with Next Auth

I'm currently working on a next js social media app for practice and here's how to set up Google authentication quickly and easily

In your next JS project install the next-auth Library
Checkout the docs

Image description

We then copy this piece of code from the docs

import NextAuth from "next-auth"
import GitHub from "next-auth/providers/github"
export const { handlers, auth } = NextAuth({ providers: [ GitHub ] })

Enter fullscreen mode Exit fullscreen mode

Create a file named auth.js or auth.ts (if using typescript)
create the file in the *lib * folder (lib/auth.ts)

The code can now be modified for Google authentication

import NextAuth from "next-auth"
import Google from "next-auth/providers/google"
export const { handlers, auth } = NextAuth({ providers: [ Google ] })
Enter fullscreen mode Exit fullscreen mode

Now we need the clientId and the clientSecret from Google.

Head to Google Cloud console
and create a project or select one

Then in the sidebar under APIs and services select Credentials

Image description

Then click on Create credentials

Image description

and then on OAuth Client ID

Image description

Select application type as Web application

Image description

Add Authorized JavaScript origins as http://localhost:3000 (during development)

Image description
Then click on create

Image description

Store the Credentials in your .env file

Image description

In the Credentials section go to your Web Client (or whatever if you changed the name)

Image description

And add this in the authorized redirect URIs

Image description

In the .env file, you have to set NEXTAUTH_URL and NEXTAUTH_SECRET

Set the NEXAUTH_URL as http://localhost:3000/api/auth

Image description

And generate the NEXTAUTH_SECRET from this openssl terminal

openssl rand -base64 32
Enter fullscreen mode Exit fullscreen mode

Now update the auth.ts file like this

export const {
    handlers: { GET, POST },
    auth,
    signIn,
    signOut,
} = NextAuth({
    providers: [
        Google({
            clientId: process.env.GOOGLE_ID,
            clientSecret: process.env.GOOGLE_CLIENT_SECRET,
        }),
    ],
});

Enter fullscreen mode Exit fullscreen mode

create a new route.ts file in the app/api/auth/[...nextauth]
folder.

It will only contain this

export { GET, POST } from "@/lib/auth";

Create a form with an action

<form action={handleGoogleLogin}>
    <button>Sign Up with Google</button>
</form>
Enter fullscreen mode Exit fullscreen mode
const handleGoogleLogin = async () => {
    "use server";
    await signIn("google");
};
Enter fullscreen mode Exit fullscreen mode

the signIn function should be imported from the auth.ts file
Your Google Authentication has been setup

Top comments (0)