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)

  1. Create an OAuth app in the provider console.
  2. Set the authorized redirect URI: https://your-domain.com/api/auth/callback/github (and the localhost version for dev).
  3. Add env vars: AUTH_SECRET, AUTH_GITHUB_ID, AUTH_GITHUB_SECRET. v5 reads AUTH_<PROVIDER>_ID/SECRET automatically.
  4. Add the provider: providers: [GitHub, Google].
  5. 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 signIn callback 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 jwt callback 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_URL or trustHost so 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.ts
2import NextAuth from "next-auth";
3import Google from "next-auth/providers/google";
4import GitHub from "next-auth/providers/github";
5
6export const { handlers, auth, signIn, signOut } = NextAuth({
7 providers: [
8 GitHub, // uses AUTH_GITHUB_ID / AUTH_GITHUB_SECRET
9 Google({ authorization: { params: { prompt: "select_account" } } }),
10 ],
11 callbacks: {
12 signIn({ profile }) {
13 return profile?.email?.endsWith("@acme.com") ?? false; // company accounts only
14 },
15 },
16});
17
18// app/login/page.tsx
19// 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.

Open in study app