This project uses NextAuth.js to handle authentication. NextAuth.js is a complete open-source authentication solution for Next.js applications. It supports various authentication providers, including Google, which we are using in this project.
To get started with NextAuth.js using Google Provider, follow these steps:
npm install next-auth- Go to the Google Cloud Console.
- Create a new project or select an existing project.
- Navigate to the "Credentials" page in the API & Services section.
- Click on "Create Credentials" and select "OAuth 2.0 Client IDs".
- Configure the OAuth consent screen with the necessary information.
- Add your authorized redirect URI. It should be in the format:
http://localhost:3000/api/auth/callback/google
- After creating the OAuth 2.0 Client, you will get a Client ID and Client Secret.
Create a [...nextauth].js file inside the pages/api/auth directory with the following configuration:
import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
export default NextAuth({
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
],
// Optional: Configure session and callbacks as per your needs
session: {
jwt: true,
},
callbacks: {
async jwt(token, user) {
if (user) {
token.id = user.id;
}
return token;
},
async session(session, token) {
session.user.id = token.id;
return session;
},
},
});Ensure you have the environment variables set up in your .env.local file:
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
NextAuth.js provides signIn and signOut methods to handle authentication in your components.
import { signIn, signOut, useSession } from 'next-auth/react';
function AuthButton() {
const { data: session } = useSession();
if (session) {
return (
<>
<p>Signed in as {session.user.email}</p>
<button onClick={() => signOut()}>Sign out</button>
</>
);
}
return <button onClick={() => signIn('google')}>Sign in with Google</button>;
}
export default AuthButton;