
Add Google Authentication to your NextJs project using NextAuth.js
27 August, 2022
1
1
0
Contributors
Here in this blog tutorial, I will show you how you can use NextAuth.js in your NextJs project to add Google authentication. In this particular tutorial I am using
Typescript
but you can follow it for Javascript
.Installation
You can install it using yarn or using npm.
Adding api routes
To add NextAuth.js in your project you need to first create
[...nextauth].ts
inside you pages/api/auth
.Grab your keys from Google Cloud
Click here and setup you app
Step 1: Create a project with any name you want.
Step 2: Go to Credentials tab
Step 3: Create credentials
Step 4: Choose OAuth client ID option
Step 5: Fill some details to get you google client Id and Secret

Step 6: After you press create button, You will get you google client id and google client secret. Save these credentials in your pc.

Setting up environment variables
Create a
.env.local
file inside you root directory.Setting up OAuth inside our app
To be able to use
useSession
inside your app, you'll first need to wrap your top level component inside <SessionProvider></SessionProvider>
which is coming from next-auth/react
Now we are good to go.
Using Google Authentication in our app
To use authentication, we need to import some functions from
next-auth/react
Now, inside our components we can use
useSession
, signin
and signout
functionsCongratulations 🎉🎉🎉
You have successfully added NextAuth.js in your project for Google Authentication.
Full source code
you can see the full code on GitHub - Link
tutorial
react
nextjs
fullstack
next-auth