Integrating a secure authentication system is an important development step that not only provides users with a safe environment, but also instills confidence in the product. This system ensures that your data is protected and that only authorized individuals can access your application.
Building secure authentication from scratch can be a time-consuming process and requires a thorough understanding of authentication protocols and processes, especially when dealing with different authentication providers.
NextAuth lets you focus on building core functionality. Learn how to integrate Google Social Login into your application using NextAuth.
How NextAuth Works
NextAuth.js is an open-source authentication library that simplifies the process of adding authentication and authorization functionality to your Next.js applications, as well as customizing authentication workflows. It offers various features such as email, passwordless authentication, support for different authentication providers such as Google, GitHub, etc.
At a high level, NextAuth acts as middleware, facilitating the authentication process between your application and your provider. Internally, when a user tries to log in, they are redirected to Google’s sign-in page. After successful authentication, Google returns a payload containing the user’s data such as name and email address. This data is used to authorize access to the application and its resources.
Using payload data, NextAuth creates a session for each authenticated user and stores the session token in a secure HTTP-only cookie. A session token is used to verify a user’s identity and maintain authentication status. This process also applies to other providers with slightly different implementations.
Register your Next.js application with the Google Developer Console
NextAuth provides support for Google Authentication Service. However, if you want your application to interact with Google APIs and allow the user to authenticate with her Google credentials, register your app in the Google Developer Console and client ID and client secret.
To do this, go to the Google Developer Console. Then sign in with your Google account to access the console. Once logged in, create a new project.
On the project overview page, APIs and services Select a tab from the list of services in the left menu pane and finally Qualification option.
please click Create Credentials Click the button to generate a Client ID and Client Secret. Then, specify the type of application from the options given and provide the name of the application.
Then specify the app’s home root URL and finally the application’s authorized redirect URIs.In this case it is http://localhost:3000/api/auth/callback/google As specified in the Google provider settings for NextAuth.
After completing the registration, Google will give you a Client ID and Client Secret to use in your app.
NextJS application setup
First, create a Next.js project locally.
npx create-next-app next-auth-app
Once setup is complete, navigate to the newly created project directory and run this command to start the development server.
npm run dev
Open a browser and go to http://localhost:3000. This should give the expected result.
.env file settings
In the root folder of your project, create a new file and give it a name. .env Keep your client ID, secret, and base URL.
NEXT_PUBLIC_GOOGLE_CLIENT_ID= 'client ID'
NEXT_PUBLIC_GOOGLE_CLIENT_SECRET= 'secret'
NEXT_PUBLIC_NEXTAUTH_URL= 'http://localhost:3000'
NextAUTH URL is used to specify the base URL of the application. This is used to redirect the user after authentication is complete.
Integrate NextAuth in your Next.js application
First, install the NextAuth library into your project.
npm install next-auth
next, /page directory, create a new folder and name it APIs. directory to APIs Create another folder called certification In the auth folder, add a new file and name it […nextauth].js Add the following lines of code.
import NextAuth from "next-auth/next";
import GoogleProvider from "next-auth/providers/google";
export default NextAuth({
providers:[
GoogleProvider({
clientId:process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID,
clientSecret: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_SECRET,
}),
]});
This code configures Google as an authentication provider. The NextAuth function defines a Google provider configuration object that receives her two properties client id and client secret to initialize the provider.
next, pages/_app.js Open the file and make the following changes to your code.
import '../styles/globals.css'
import { SessionProvider } from "next-auth/react"
function MyApp({ Component, pageProps: { session, ...pageProps } }) {
return (
<SessionProvider session={session}>
<Component {...pageProps} />
</SessionProvider>
)
}
export default MyApp
of NextAuth session provider The component provides authentication state management functionality for Next.js apps.it takes session A prop containing authentication session data returned from Google’s APIs, including user details such as ID, email, and access token.
By wrapping My app When used with the SessionProvider component, an authenticated session object containing user details is made available throughout the application, allowing the application to persist and render pages based on authentication state.
Configure the index.js file
open page/index.js Open the file, remove the boilerplate code, and add the code below to create a login button that routes the user to the login page.
import Head from 'next/head'
import styles from '../styles/Home.module.css'
import { useRouter } from 'next/router';export default function Home() {
const router = useRouter();
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h1 className={styles.title}>
Welcome to <a href="https://nextjs.org">Next.js!</a>
</h1>
<p className={styles.description}>
Get started by signing in{' '}
<code className={styles.code}>with your Google Account</code>
<button className={styles.loginButton}
onClick={() => router.push('/Login')}> Login</button>
</p>
</main>
</div>
)
}
This code uses Next.js Router used Use hooks to handle routing within your application by defining a router object.When the login button is clicked, the handler function is router.push A method that redirects the user to the login page.
Create a login authentication page
in the page directory, create new file login.jsthen add the following lines of code:
import { useSession, signIn, signOut } from "next-auth/react"
import { useRouter } from 'next/router';
import styles from '../styles/Login.module.css'export default function Login() {
const { data: session } = useSession()
const router = useRouter();
if (session) {
return (
<div className={styles.container}>
<h1 className="title">Create Next App</h1>
<div className={styles.content}>
<h2> Signed in as {session.user.email} <br /></h2>
<div classname={styles.btns}>
<button className={styles.button} onClick={() => router.push('/Profile')}>
User Profile
</button>
<button className={styles.button} onClick={() => {
signOut()
}}>
Sign out
</button>
</div>
</div>
</div>
)
}
return (
<div className={styles.container}>
<h1 className="title">Create Next App</h1>
<div className={styles.content}>
<h2> You are not signed in!!</h2>
<button className={styles.button}
onClick={() => signIn()}>Sign in</button>
</div>
</div>
)
}
useSession, loginand sign out is a hook provided by next certification. useSession Hooks are used to access the current user session object once the user is signed in and successfully authenticated by Google.
This allows Next.js to persist authentication state and render user details on the client side of the app (email in this case).
Additionally, the session object allows you to easily build custom user profiles for your application and store data in databases such as PostgreSQL. You can use Prisma to connect your PostgreSQL database to your Next.js application.
The signOut hook allows users to sign out of your application. This hook removes the session object created during the sign-in process and the user is signed out.
Spin up your development server, update your changes, and navigate to your Next.js application running in your browser to test the authentication functionality.
npm run dev
Additionally, you can use Tailwind CSS in your Next.js app to style the authentication model.
Authentication using NextAuth
NextAuth supports multiple authentication services that can be easily integrated into your Next.js application to handle client-side authentication.
Additionally, NextAuth provides support for various database integrations, so you can integrate databases that store user data and access tokens to implement server-side authentication for subsequent authentication requests.