Next.jsMedium
How do you handle OAuth providers with NextAuth?
Add provider objects (Google, GitHub and so on) to the providers array in your Auth.js config, register your app with each provider to get a client ID and secret, set the callback URL to /api/auth/callback/<provider>, and store credentials in env vars. Auth.js handles the redirect, PKCE, state checks, token exchange and session creation.
Steps (Auth.js v5)
- Create an OAuth app in the provider console.
- Set the authorized redirect URI:
https://your-domain.com/api/auth/callback/github(and the localhost version for dev). - Add env vars:
AUTH_SECRET,AUTH_GITHUB_ID,AUTH_GITHUB_SECRET. v5 readsAUTH_<PROVIDER>_ID/SECRETautomatically. - Add the provider:
providers: [GitHub, Google]. - Trigger sign-in with a Server Function:
await signIn("github", { redirectTo: "/dashboard" }).
Customizing
- Scopes:
Google({ authorization: { params: { scope: "openid email profile" } } }). - Restricting sign-in: the
signIncallback can reject users outside your domain. - Account linking: with a database adapter, multiple providers can map to one user. Linking accounts with the same email is off by default to prevent account takeover; enable it only for providers that verify email.
- Access tokens: persist provider tokens in the
jwtcallback if you need to call the provider's API, and refresh them before they expire.
Security reminders
- Keep client secrets server-side only (no
NEXT_PUBLIC_). - Use exact redirect URIs, not wildcards.
- Behind a proxy, set
AUTH_URLortrustHostso callback URLs are built correctly.
Alternatives
Better Auth (socialProviders config), Clerk and Auth0 offer the same flows with hosted UIs or different trade-offs.
Code example
tsx
1// auth.ts2import NextAuth from "next-auth";3import Google from "next-auth/providers/google";4import GitHub from "next-auth/providers/github";56export const { handlers, auth, signIn, signOut } = NextAuth({7 providers: [8 GitHub, // uses AUTH_GITHUB_ID / AUTH_GITHUB_SECRET9 Google({ authorization: { params: { prompt: "select_account" } } }),10 ],11 callbacks: {12 signIn({ profile }) {13 return profile?.email?.endsWith("@acme.com") ?? false; // company accounts only14 },15 },16});1718// app/login/page.tsx19// import { signIn } from "@/auth";20// export default function Login() {21// return (22// <form action={async () => { "use server"; await signIn("github", { redirectTo: "/dashboard" }); }}>23// <button>Sign in with GitHub</button>24// </form>25// );26// }
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.