24 April 2024 — 2 min read
The prior article examined how Clerk may simplify user authentication for Next.js applications. Clerk provides a handy managed service option, but it's wise to weigh your options before making a choice. Today, we'll examine and contrast Clerk and NextAuth.js, two more well-liked authentication libraries for Next.js, to help you decide which is ideal for your project.
Why Next Auth instead of Clerk?
Setting Up Next Auth in Next.js
Install NextAuth
npm install next-auth
Configure NextAuth
Server
NextAuth.js will handle all queries to /api/auth/* (signIn, callback, signOut, etc.) automatically.
import NextAuth from "next-auth";
import GoogleProvider from 'next-auth/providers/google';
export const authOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET
})
]
}
export default NextAuth(authOptions)
Client
Provider
import { SessionProvider } from "next-auth/react"
export default function App({
Component, pageProps: { session, ...pageProps }
}) {
return (
<SessionProvider session={session}>
<Component {...pageProps}/>
</SessionProvider>
)
}
Consumer
import { useSession, signIn, signOut } from "next-auth/react"
export default function Component() {
const { data: session } = useSession()
if(session) {
return <>
Signed in as {session.user.email} <br/>
<button onClick={() => signOut()}>Sign out</button>
</>
}
return <>
Not signed in <br/>
<button onClick={() => signIn()}>Sign in</button>
</>
}
NextAuth.js is a compelling alternative to Clerk, offering developers greater control, flexibility, and cost-effectiveness. Its open-source nature, extensive community support, and seamless integration capabilities make it an attractive choice for Next.js applications. Whether you're looking for a self-hosted solution or prefer a managed service, NextAuth.js provides a robust and customizable authentication framework to meet your project's needs.