Authentication with NextAuth

Authentication is a critical component of any web application. NextAuth.js (now Auth.js) greatly simplifies implementing secure login systems in Next.js.
Prerequisites
- Next.js 14 with App Router configured
- GitHub or Google account for OAuth
- Basic TypeScript knowledge
- Optional database (for persistent sessions)
Installing NextAuth.js
NextAuth.js is installed as a project dependency and configured through an API route file. It supports multiple authentication providers out of the box.
npm install next-auth
// app/api/auth/[...nextauth]/route.ts
import NextAuth from 'next-auth'
import GithubProvider from 'next-auth/providers/github'
const handler = NextAuth({
providers: [
GithubProvider({
clientId: process.env.GITHUB_ID!,
clientSecret: process.env.GITHUB_SECRET!
})
]
})
export { handler as GET, handler as POST }Pro Tip
Configuring OAuth providers
NextAuth supports over 50 authentication providers including Google, GitHub, Facebook, Twitter and more. You can also add email/password authentication with the Credentials provider.
- GitHub: Ideal for developer apps
- Google: The most universal, almost everyone has an account
- Credentials: Custom email and password login
- Email: Magic links sent by email
Conclusion
NextAuth.js makes implementing secure authentication accessible to any developer. With just a few configuration files, you have a robust login system with OAuth, sessions and route protection.
THE AUTHOR
Peter Lima
Peter is a full stack web developer with over 5 years of experience creating digital solutions. Specialist in React, Next.js and Node.js, passionate about sharing knowledge and helping other developers grow professionally.
More from Peter Lima

