Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 72 ยท Middleware, Proxy and Auth

Auth.js, Better Auth and Clerk

Compare Auth.js, Better Auth and Clerk for Next.js: how the OAuth flow works with state and PKCE, what each library gives you, and how to choose and wire one up.

In Authentication and Sessions you built a small login system by hand: password hashing, a signed cookie, a guard. That is the right way to learn it, but a production app usually needs much more: "Sign in with Google" and GitHub, email verification, password reset, rate limiting, two-factor codes, passkeys, account linking and a way to manage all of it. Writing and maintaining those flows yourself is slow and easy to get subtly wrong, so most teams reach for a library.

This lesson looks at three popular choices for Next.js: Auth.js, Better Auth and Clerk. It explains the OAuth flow that sits underneath social login (with two runnable models of its security checks), shows what each library's setup looks like, and gives you a way to choose. Library APIs change quickly, so the code here shows the shape of each setup. Check the current documentation of the version you install before copying it.

None of these libraries can run on this site, because they need a real Next.js server and, for two of them, accounts with outside services. Their code is read-only. The runnable examples model the OAuth security steps (state and PKCE) in plain Node.js with node:crypto. Those steps are the real algorithms, not toy versions.

Three libraries at a glance

Three ways to get auth

Auth.js Open source. Providers and adapters. Works in many frameworks.
Better Auth Open source, TypeScript first, plugins for 2FA and more.
Clerk Hosted service with ready-made sign-in screens.

Two run in your app and database. One runs in the cloud.

1 / 2

Before the code, one concept is worth learning properly, because every one of these libraries is built on it.

How "Sign in with GitHub" really works

Social login uses a protocol called OAuth 2.0, and for sign-in the OpenID Connect layer on top of it. The most common flow is the authorization code flow. Your app never sees the user's GitHub password. Instead, the browser visits GitHub, the user approves, and GitHub sends back a short-lived code that your server exchanges for tokens and a profile.

sequenceDiagram
  participant B as Browser
  participant A as Your Next.js app
  participant P as Provider (GitHub)
  B->>A: Click "Sign in with GitHub"
  A-->>B: Redirect to provider<br/>with state and code challenge
  B->>P: User logs in and approves
  P-->>B: Redirect to your callback<br/>with code and state
  B->>A: GET /api/auth/callback?code=...&state=...
  A->>A: Check state, keep code verifier
  A->>P: Exchange code + verifier (server to server)
  P-->>A: Tokens and user profile
  A-->>B: Set session cookie, redirect home

The code travels through the browser. The tokens never do.

Two protections are essential, and a good library applies both for you:

  • state: a random value your app creates before redirecting and stores in a cookie. The provider returns it unchanged. If the state in the callback does not match the cookie, the callback was not started by this browser, which is how an attacker's forged callback gets stopped (a cross-site request forgery on the login flow).
  • PKCE (Proof Key for Code Exchange): your app creates a random verifier, sends only its SHA-256 hash (the challenge) at the start, and sends the verifier itself when exchanging the code. If someone steals the code in transit, it is useless without the verifier.

The first example computes the PKCE challenge, checks it against the published test vector from the PKCE specification (RFC 7636), and then plays out a theft.

Node.js PKCE: a stolen code is useless

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The attacker holds the code and fails because they cannot produce a verifier that hashes to the stored challenge. Your server succeeds once, and a replay fails because a code is single use. The challenge is safe to send through the browser, because a hash cannot be reversed.

The second example models the callback handler that a library runs for you. It checks state first, then exchanges the code, then creates a session.

Node.js The callback handler: state first, then the code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Case 1 is the happy path. In case 2 an attacker tricks a user into visiting a callback link, but the state in the link cannot match the one stored in that user's cookie, so it is rejected before the code is even looked at. In case 3 the state is right but the code was issued for a different login, so the PKCE verifier does not match and the exchange fails. You never write this code yourself when you use a library. It is still worth knowing what "secure defaults" means.

Auth.js

Auth.js (the project that grew out of NextAuth.js) is the long-time default for Next.js. You configure providers in one file and mount its handlers on a catch-all route. It supports dozens of OAuth providers, email links, passkeys and a credentials option, plus adapters that store users in a database (Prisma, Drizzle and others).

TypeScript
// auth.ts
import NextAuth from 'next-auth';
import GitHub from 'next-auth/providers/github';

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [GitHub], // reads AUTH_GITHUB_ID and AUTH_GITHUB_SECRET from the environment
});
TypeScript
// app/api/auth/[...nextauth]/route.ts
import { handlers } from '@/auth';

export const { GET, POST } = handlers;
TSX
// app/page.tsx
import { auth, signIn, signOut } from '@/auth';

export default async function Home() {
  const session = await auth();

  if (!session?.user) {
    return (
      <form
        action={async () => {
          'use server';
          await signIn('github');
        }}
      >
        <button>Sign in with GitHub</button>
      </form>
    );
  }

  return (
    <form
      action={async () => {
        'use server';
        await signOut();
      }}
    >
      <p>Signed in as {session.user.name}</p>
      <button>Sign out</button>
    </form>
  );
}

You also set AUTH_SECRET (a random string used to sign and encrypt the session) and register the provider's callback URL, for example https://your-site.com/api/auth/callback/github, in the provider's dashboard. By default Auth.js keeps sessions in an encrypted cookie; add a database adapter to store users and sessions in tables.

Library status changes. Version 5 of next-auth has been the one to use with the App Router for a long time, and in 2025 the Auth.js maintainers announced that the project is now looked after by the Better Auth team. Read the current notes on the Auth.js website before starting a new project, and pin the version you choose.

Better Auth

Better Auth is a TypeScript-first library that runs in your app and stores data in your database. It covers email and password, social providers and sessions out of the box, and adds features such as two-factor authentication, passkeys, organizations and roles through plugins. A CLI generates the tables for your database.

TypeScript
// lib/auth.ts
import { betterAuth } from 'better-auth';
import { prismaAdapter } from 'better-auth/adapters/prisma';
import { nextCookies } from 'better-auth/next-js';
import { prisma } from '@/lib/prisma';

export const auth = betterAuth({
  database: prismaAdapter(prisma, { provider: 'postgresql' }),
  emailAndPassword: { enabled: true },
  socialProviders: {
    github: {
      clientId: process.env.GITHUB_CLIENT_ID!,
      clientSecret: process.env.GITHUB_CLIENT_SECRET!,
    },
  },
  plugins: [nextCookies()], // lets Server Actions set cookies
});
TypeScript
// app/api/auth/[...all]/route.ts
import { auth } from '@/lib/auth';
import { toNextJsHandler } from 'better-auth/next-js';

export const { GET, POST } = toNextJsHandler(auth);
TSX
// reading the session in a Server Component
import { headers } from 'next/headers';
import { auth } from '@/lib/auth';

export default async function Account() {
  const session = await auth.api.getSession({ headers: await headers() });
  if (!session) return <p>Please sign in.</p>;
  return <p>Hello, {session.user.name}</p>;
}

On the browser side you create a small client (createAuthClient() from better-auth/react) and call methods like signIn.email(...) or signIn.social({ provider: 'github' }) from your forms.

Clerk

Clerk is a hosted service. Users, sessions and sign-in screens live in Clerk's cloud, and you add its components and a bit of configuration. You do not build forms or store credentials. That makes it the fastest way to get a polished login, with organizations, multi-factor authentication and a user dashboard included, in exchange for a monthly bill that grows with active users and for keeping your user data in a third-party system.

TSX
// app/layout.tsx
import { ClerkProvider, SignInButton, SignedIn, SignedOut, UserButton } from '@clerk/nextjs';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <ClerkProvider>
      <html lang="en">
        <body>
          <header>
            <SignedOut>
              <SignInButton />
            </SignedOut>
            <SignedIn>
              <UserButton />
            </SignedIn>
          </header>
          {children}
        </body>
      </html>
    </ClerkProvider>
  );
}
TypeScript
// proxy.ts
import { clerkMiddleware } from '@clerk/nextjs/server';

export default clerkMiddleware();

export const config = {
  matcher: ['/((?!_next|.*\\..*).*)', '/(api|trpc)(.*)'],
};
TypeScript
// in a Server Component, action or route handler
import { auth } from '@clerk/nextjs/server';

const { userId } = await auth();
if (!userId) throw new Error('Not signed in');

You provide two environment variables, a publishable key and a secret key, from the Clerk dashboard. Clerk's setup instructions follow Next.js versions closely, so the exact proxy or middleware file name matches the guide for your version.

Choosing

Question Auth.js Better Auth Clerk
Where do users live? Your database, via adapters Your database Clerk's cloud
Ready-made UI No, you build forms No, you build forms Yes, prebuilt components
Cost Free Free Free tier, then per active user
Extra features (2FA, orgs, passkeys) Some, others DIY Many, through plugins Many, built in
Control and portability High High Lower (vendor lock-in)
Setup time Medium Medium Short

A few rules of thumb. Pick Clerk when speed matters and a vendor bill is acceptable, such as a prototype or a product that sells to teams. Pick Better Auth or Auth.js when you want users in your own database, no per-user fees, and full control. If you are unsure, the choice that keeps your user table in your own database is the one that is easiest to leave later.

Wiring a library into your app

Whichever library you choose, keep the structure from Authorization and Data Security:

  1. Wrap the library in one function. Your data layer's verifySession() calls auth() (or getSession, or Clerk's auth()) and returns your own { userId, role } shape. Then the rest of the app does not care which library you use, and changing later touches one file.
  2. Still check in every action and data function. A library gives you the session. It does not decide who may edit order 102.
  3. Use the proxy only as a quick filter, such as sending visitors without a session cookie to the sign-in page.
  4. Register the right callback URLs for each environment (local, preview, production), and keep client secrets in environment variables.
  5. Test the unhappy paths: expired sessions, a provider that is down, a user who denies consent, and sign-out on another tab.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the OAuth authorization code flow, what does your server exchange with the provider for tokens?

    The browser carries only the code. Your server sends it, together with the verifier, directly to the provider and receives the tokens.
  2. 2. What is the purpose of the state parameter?

    The app stores a random state in a cookie and compares it with the one returned by the provider. A mismatch means the callback is not part of this browser's flow.
  3. 3. Which option keeps your user data in a third-party hosted system and gives you ready-made sign-in components?

    Clerk is a hosted service with prebuilt components. Auth.js and Better Auth run inside your app and use your own database.
  4. 4. You installed an auth library. Do you still need to check permissions in Server Actions?

    Authentication and authorization are separate. Your data layer still decides what this user may read or change.
  5. 5. Why wrap the library's session call in your own verifySession() function?

    A thin wrapper isolates the library. Your pages and actions call your function and get your own session shape.

Summary

  • Libraries handle the hard parts of login: OAuth, sessions, verification, resets, two-factor and safe defaults.
  • Social login uses the authorization code flow. state protects against forged callbacks and PKCE makes a stolen code useless.
  • Auth.js and Better Auth run in your app and database; Clerk is a hosted service with prebuilt UI and a recurring cost.
  • All three mount handlers or a proxy, read a session on the server, and need secrets and callback URLs configured per environment.
  • Library APIs change often, so copy setup from the current docs and pin versions.
  • Wrap the library in your own verifySession() and keep authorization checks in your data layer.

Next: Image Optimization with next/image