Getting Started with Next.js and OAuth Authentication
Let's dive into how you can implement OAuth authentication in your Next.js application. We'll focus on integrating with Google as an example, but the process is similar for other OAuth providers.Step 1: Set Up OAuth Provider Begin by creating a project in the Google Developers Console and obtaining OAuth credentials (Client ID and Client Secret). Configure the authorized redirect URI to point to your Next.js application.
Step 2: Install Dependencies Next, install the necessary packages using npm or yarn:
npm install next-auth next-auth/providers
import NextAuth from 'next-auth'; import Providers from 'next-auth/providers'; export default NextAuth({ providers: [ Providers.Google({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, }), // Add other providers as needed ], });
Step 4: Authenticate Users You can now use NextAuth's authentication hooks and components in your Next.js pages. For example, to create a login button:
import { signIn, signOut, useSession } from 'next-auth/react'; function LoginPage() { const { data: session } = useSession(); return ( <> {!session && ( <> <p>You are not signed in.</p> <button onClick={() => signIn('google')}>Sign in with Google</button> </> )} {session && ( <> <p>Signed in as {session.user.email}</p> <button onClick={() => signOut()}>Sign out</button> </> )} </> ); } export default LoginPage;
import { getSession } from 'next-auth/react'; export default async (req, res) => { const session = await getSession({ req }); if (!session) { res.status(401).json({ error: 'Unauthorized' }); return; } // Proceed with authenticated user };