In this article, we will explore how to authenticate users using Google and NextAuth.js in the latest version of Next.js (version 13).
We will start by setting up a new Next.js project and configuring our environment variables. Next, we will integrate Google OAuth with NextAuth.js, so users can sign in with their Google credentials.
🔆What is NextAuth.js ?
NextAuth.js is a complete open-source authentication library designed specifically for Next.js applications, it simplifies the authentication process and makes it easier for developers to build secure authentication systems.
🔆 Setting up NextAuth.js in a Next.js Project :
Install NextAuth.js: Install NextAuth.js as a dependency in your Next.js project using npm or yarn.
npm install next-auth
Next step go to the app directory and create a directory path
app/api/auth/[...nextauth]/route.js.
In the route.js file, we'll create a handler and set it to the NextAuth function (which is imported from "next-auth").
import NextAuth from "next-auth"; const handler = NextAuth({ })
Inside the NextAuth function, we're going to pass an object to specify the providers' list. In this example, we're specifying the GoogleProvider (which is imported from "next-auth/providers/google").
Inside the GoogleProvider we'll pass an object to specify our client ID and client Secret.
The last thing we need to export an object and set the handler as GET function and as POST function.
Next, create a
.env
file at the root of your project and add the client ID and client secret. For Google this would be:
- To get the Google client ID and client secret we can go to the Google Cloud platform console. Click here.
- Fill in the required fields.
Note: You should protect your Google ID and secret Key.
Next, create a SigninButton component to show if the user is signed in or not, and to do so, use The
useSession()
React Hook, which is the easiest way to check if someone is signed in.Note: this is a client component because we used the useSession hook, so mark it with "use client" at the top.
Then create an Appbar component and inside this component add the SigninButton component we just created.
Then We need to wrap our whole application with SessionProvider (which comes from "next-auth/react"). SessionProvider allows instances of
useSession()
to share the session object across components, by using React Context under the hood. It also takes care of keeping the session updated and synced between tabs/windows. First, create a Providers component:
- Then go to the RootLayout of your application, inside the body section wrap the whole app with the Providers component.
This is the final result. We successfully added NextAuth.js to our project for Google Authentication.
🔆source code
Here is the full code on GitHub.
🔆Conclusion
Now we understand how to implement user authentication with Google and NextAuth.js in our Next.js applications.