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
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 ] })
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 ] })
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
Then click on Create credentials
and then on OAuth Client ID
Select application type as Web application
Add Authorized JavaScript origins as http://localhost:3000 (during development)
Store the Credentials in your .env file
In the Credentials section go to your Web Client (or whatever if you changed the name)
And add this in the authorized redirect URIs
In the .env file, you have to set NEXTAUTH_URL and NEXTAUTH_SECRET
Set the NEXAUTH_URL as http://localhost:3000/api/auth
And generate the NEXTAUTH_SECRET from this openssl terminal
openssl rand -base64 32
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,
}),
],
});
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>
const handleGoogleLogin = async () => {
"use server";
await signIn("google");
};
the signIn function should be imported from the auth.ts file
Your Google Authentication has been setup
Top comments (0)