Auth.js (formerly NextAuth) is a popular library that makes it easy to add third-party authentication (e.g Google login, GitHub login, etc.) to your Next.js application.
In this tutorial, we will learn how to implement Google login using nextAuth.
Before we begin, make sure you have the following prerequisites:
- A Next.js application. If you don't have one, you can create a new Next.js app using the following command:
npx create-next-app my-app
- A Google account. If you don't have one, you can sign up for a new account at https://accounts.google.com.
Now, let's get started.
Configuring NextAuth.js
Step 1: Install next-auth
Navigate to your Next.js project directory in your terminal and run the following command:
npm install next-auth
Step 2: Setup a Google Oauth client
To use Google login with nextAuth, you need to set up a Google OAuth client on the google cloud console. To do this, follow these steps:
- Go to the Google Cloud Console.
- Click the project drop-down and select or create the project that you want to use for this tutorial.
- Click the hamburger menu and select APIs & Services > Credentials.
- On the Credentials page, click Create credentials > OAuth client ID.
- Select Web application as the application type.
- In the Authorized JavaScript origins field, enter the URL of your Next.js application. For example, if your app is running on localhost, you would enter
http://localhost:3000
. - In the Authorized redirect URIs field, enter the URL of your Next.js application with
/api/auth/callback/google
appended to it. For example, if your app is running on localhost, you would enterhttp://localhost:3000/api/auth/callback/google
. - Click Create.
- On the OAuth client page, make a note of the client ID and client secret. You will need these later.
Step 3: Add a next.js serverless function to handle Google login
We need to add a serverless function to handle the Google Oauth process. So we're going to create a pages/api/auth/[...nextauth].js
file in the project directory with the following code:
import NextAuth from "next-auth"
import GoogleProvider from "next-auth/providers/google"
export default NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
],
})
In this code, we are using the Google provider provided by the next-auth
package to handle the Google login process.
We are also using environment variables to store the Google client ID and client secret obtained in Step 2.
And behind the scenes, the necessary Google OAuth's API routes are created within pages/api/auth/*
to handle all auth API requests to: /api/auth/callback
, /api/auth/signIn
, /api/auth/signOut
, etc.
Step 4: Set up environment variables
To set up the environment variables, create a new file called .env.local
in the root directory and paste the following code in it:
# .env.local
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
Replace your-google-client-id
and your-google-client-secret
with the client ID and client secret obtained in Step 2.
Step 5: Wrap the _app.tsx
component with SessionProvider
To use the useSession
hook, you must first wrap your application with the <SessionProvider />
component at the top level to expose the session context.
import { SessionProvider } from "next-auth/react"
export default function App({
Component,
pageProps: { session, ...pageProps },
}) {
return (
<SessionProvider session={session}>
<Component {...pageProps} />
</SessionProvider>
)
}
The <SessionProvider />
component also ensures that the session is kept up to date and synchronized across browser tabs and windows.
Step 5: Add a login button to your Next.js app
Now that the serverless function is set up, you can add a login button to your Next.js app. To do this, add the following code to your app:
// GoogleSignInButton.tsx
import React from "react";
import { useSession, signIn, signOut } from "next-auth/react";
import { useRouter } from "next/router";
export default function LoginButton() {
const { data: session, status } = useSession();
const router = useRouter();
if (status === 'authenticated') {
return (
<button
className="font-medium text-lg border-none"
onClick={() => signOut()}
>
Sign out
</button>
);
}
return (
<button
className="font-medium text-lg border-none"
onClick={() => signIn("google", { callbackUrl: router.asPath })}
>
Sign in with Google
</button>
);
}
This code adds a login button that redirects the user to the /api/auth/signin
route when clicked.
Step 7: Protect Next.js API routes
To protect Next.js API routes when using next-auth for login, getSession
function can be used, provided the API call is made from the client side and not the server side.
For server-side calls, it is recommended to use unstable_getServerSession
instead. Check out getSession and unstable_getServerSession to know more about these functions.
The getSession
function returns a session object from which we can determine whether the user is logged in or not.
import { getSession } from "next-auth/react"
import { NextApiRequest, NextApiResponse } from "next";
export default async function createPost(req: NextApiRequest, res: NextApiResponse) {
const session = await getSession({ req })
if (session) {
return res.send({
title: "New post title",
content: "The content"
})
} else {
return res.send({ error: "Unauthorized access!" })
}
}
Step 6: Test the login flow
Now that everything is set up, you can test the login flow. Start your Next.js app and click the login button. You should be redirected to the Google authorization page and back to your app after you've chosen the email you want to log in with. This is how it will look:
You are redirected to the screenshot below after clicking "Sign in with Google"
Conclusion
In conclusion, adding a Google login to your Next.js app with nextAuth is a total breeze! With just a few simple steps, you'll be able to give your users the option to log in with their Google account and keep your routes safe from unauthorized users.
If you found this tutorial helpful and want to stay up-to-date with the latest web development trends and techniques, be sure to subscribe to our newsletter. We will notify you of new articles, tech updates, and early access to exclusive content. Don't miss out on the opportunity to grow as a developer and stay ahead of the curve!
Thanks!
.
Further reading